test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149
  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. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. #ifndef _WIN32
  253. TEST(SocketStream, wait_writable_UNIX) {
  254. int fds[2];
  255. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  256. const auto asSocketStream = [&](socket_t fd,
  257. std::function<bool(Stream &)> func) {
  258. return detail::process_client_socket(
  259. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  260. };
  261. asSocketStream(fds[0], [&](Stream &s0) {
  262. EXPECT_EQ(s0.socket(), fds[0]);
  263. EXPECT_TRUE(s0.wait_writable());
  264. EXPECT_TRUE(s0.is_peer_alive());
  265. EXPECT_EQ(0, close(fds[1]));
  266. EXPECT_FALSE(s0.is_peer_alive());
  267. return true;
  268. });
  269. EXPECT_EQ(0, close(fds[0]));
  270. }
  271. TEST(SocketStream, wait_writable_INET) {
  272. sockaddr_in addr;
  273. memset(&addr, 0, sizeof(addr));
  274. addr.sin_family = AF_INET;
  275. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  276. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  277. int disconnected_svr_sock = -1;
  278. std::thread svr{[&] {
  279. const int s = socket(AF_INET, SOCK_STREAM, 0);
  280. ASSERT_LE(0, s);
  281. // PORT + 1 is shared with the SSL redirect tests and with
  282. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  283. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  284. // because that happens on a worker thread the ASSERT does not stop the
  285. // test: it runs on and fails at the disconnected_svr_sock check instead.
  286. default_socket_options(s);
  287. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  288. ASSERT_EQ(0, listen(s, 1));
  289. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  290. ASSERT_EQ(0, close(s));
  291. }};
  292. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  293. std::thread cli{[&] {
  294. const int s = socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_LE(0, s);
  296. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  297. ASSERT_EQ(0, close(s));
  298. }};
  299. cli.join();
  300. svr.join();
  301. ASSERT_NE(disconnected_svr_sock, -1);
  302. const auto asSocketStream = [&](socket_t fd,
  303. std::function<bool(Stream &)> func) {
  304. return detail::process_client_socket(
  305. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  306. };
  307. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  308. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  309. // wait_writable() returns true because select_write() only checks if the
  310. // send buffer has space. Peer disconnection is detected later by send().
  311. EXPECT_TRUE(ss.wait_writable());
  312. return true;
  313. });
  314. ASSERT_EQ(0, close(disconnected_svr_sock));
  315. }
  316. #endif // #ifndef _WIN32
  317. TEST(SetSocketOptTest, TcpNoDelay) {
  318. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  319. ASSERT_NE(sock, INVALID_SOCKET);
  320. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  321. int val = 0;
  322. socklen_t len = sizeof(val);
  323. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  324. reinterpret_cast<char *>(&val), &len));
  325. EXPECT_NE(val, 0);
  326. detail::close_socket(sock);
  327. }
  328. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  329. // accept() reports failures through WSAGetLastError() on Windows and through
  330. // errno everywhere else. Asking the wrong one is what made the accept loop
  331. // treat every recoverable failure as fatal on Windows.
  332. struct Classification {
  333. bool resource;
  334. bool transient;
  335. };
  336. auto classify = [](int err) {
  337. #ifdef _WIN32
  338. WSASetLastError(err);
  339. #else
  340. errno = err;
  341. #endif
  342. // Read both before asserting: an assertion may clobber the error slot.
  343. Classification c;
  344. c.resource = detail::is_accept_resource_error();
  345. c.transient = detail::is_accept_transient_error();
  346. return c;
  347. };
  348. #ifdef _WIN32
  349. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  350. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  351. WSAECONNRESET, WSAECONNABORTED};
  352. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  353. #else
  354. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  355. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  356. ECONNABORTED};
  357. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  358. #endif
  359. for (auto err : resource_errors) {
  360. const auto c = classify(err);
  361. EXPECT_TRUE(c.resource) << "error " << err;
  362. EXPECT_FALSE(c.transient) << "error " << err;
  363. }
  364. for (auto err : transient_errors) {
  365. const auto c = classify(err);
  366. EXPECT_TRUE(c.transient) << "error " << err;
  367. EXPECT_FALSE(c.resource) << "error " << err;
  368. }
  369. for (auto err : fatal_errors) {
  370. const auto c = classify(err);
  371. EXPECT_FALSE(c.resource) << "error " << err;
  372. EXPECT_FALSE(c.transient) << "error " << err;
  373. }
  374. #ifdef _WIN32
  375. WSASetLastError(0);
  376. #else
  377. errno = 0;
  378. #endif
  379. }
  380. TEST(ClientTest, MoveConstructible) {
  381. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  382. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  383. }
  384. TEST(ClientTest, MoveAssignable) {
  385. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  386. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  387. }
  388. #ifdef _WIN32
  389. TEST(StartupTest, WSAStartup) {
  390. WSADATA wsaData;
  391. int ret = WSAStartup(0x0002, &wsaData);
  392. ASSERT_EQ(0, ret);
  393. }
  394. #endif
  395. TEST(DecodePathTest, PercentCharacter) {
  396. EXPECT_EQ(
  397. decode_path_component(
  398. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  399. U8("descrip=Gastos áéíóúñÑ 6"));
  400. }
  401. TEST(DecodePathTest, PercentCharacterNUL) {
  402. string expected;
  403. expected.push_back('x');
  404. expected.push_back('\0');
  405. expected.push_back('x');
  406. EXPECT_EQ(decode_path_component("x%00x"), expected);
  407. }
  408. TEST(DecodePathTest, UnicodeEncoding) {
  409. // %u0041 = 'A' (1-byte UTF-8)
  410. EXPECT_EQ("A", decode_path_component("%u0041"));
  411. // %u00E9 = 'é' (2-byte UTF-8)
  412. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  413. // %u3042 = 'あ' (3-byte UTF-8)
  414. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  415. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  416. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  417. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  418. // neighbours)
  419. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  420. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  421. }
  422. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  423. // A sign or whitespace inside the two-character escape window must not be
  424. // accepted as a valid percent-encoding; the sequence is passed through
  425. // literally, matching decode_uri_component / decode_path_component.
  426. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  427. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  428. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  429. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  430. // Well-formed escapes still decode.
  431. EXPECT_EQ("-", decode_query_component("%2D", false));
  432. EXPECT_EQ("A", decode_query_component("%41", false));
  433. }
  434. TEST(SanitizeFilenameTest, VariousPatterns) {
  435. // Path traversal
  436. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  437. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  438. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  439. // Normal and edge cases
  440. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  441. EXPECT_EQ("filename.txt",
  442. httplib::sanitize_filename("/path/to/filename.txt"));
  443. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  444. EXPECT_EQ("", httplib::sanitize_filename(".."));
  445. EXPECT_EQ("", httplib::sanitize_filename(""));
  446. // Null bytes stripped
  447. EXPECT_EQ("safe.txt",
  448. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  449. // Whitespace-only rejected
  450. EXPECT_EQ("", httplib::sanitize_filename(" "));
  451. }
  452. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  453. // before it is dropped; anywhere else it is an ordinary file name character.
  454. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  455. #ifdef _WIN32
  456. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  457. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  458. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  459. #else
  460. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  461. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  462. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  463. #endif
  464. }
  465. // Forward declaration (see the base64_encode note below): split builds move the
  466. // definition into httplib.cc, so re-declaring it here lets the test link.
  467. namespace httplib {
  468. namespace detail {
  469. bool is_chunked_transfer_encoding(const Headers &headers);
  470. } // namespace detail
  471. } // namespace httplib
  472. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  473. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  474. auto make = [](std::initializer_list<const char *> lines) {
  475. Headers h;
  476. for (auto te : lines) {
  477. if (te) { h.emplace("Transfer-Encoding", te); }
  478. }
  479. return h;
  480. };
  481. // Sole coding, matched case-insensitively.
  482. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  483. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  484. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  485. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  486. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  487. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  488. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  489. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  490. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  491. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  492. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  493. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  494. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  495. // were received, into one list. Headers preserves that order, so the answer
  496. // is decided by the last coding of the last line and the order the lines
  497. // arrived in is significant.
  498. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  499. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  500. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  501. // The split can fall anywhere in the list.
  502. EXPECT_TRUE(
  503. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  504. EXPECT_FALSE(
  505. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  506. // A trailing line naming no coding leaves the list ending in nothing, so it
  507. // must not inherit the chunked from the line before it.
  508. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  509. }
  510. // Forward declarations (see the base64_encode note below).
  511. namespace httplib {
  512. namespace detail {
  513. bool parse_status_line(const char *line, std::string &version, int &status,
  514. std::string &reason);
  515. std::string file_extension(const std::string &path);
  516. std::string
  517. find_content_type(const std::string &path,
  518. const std::map<std::string, std::string> &user_data,
  519. const std::string &default_content_type);
  520. bool can_compress_content_type(const std::string &content_type);
  521. bool is_prohibited_header_name(const std::string &name);
  522. bool is_valid_path(const std::string &path);
  523. #ifdef CPPHTTPLIB_SSL_ENABLED
  524. bool match_hostname(const std::string &pattern, const std::string &hostname);
  525. #endif
  526. } // namespace detail
  527. } // namespace httplib
  528. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  529. struct {
  530. const char *line;
  531. const char *version;
  532. int status;
  533. const char *reason;
  534. } cases[] = {
  535. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  536. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  537. // The reason phrase may be empty, or left out along with its space.
  538. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  539. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  540. };
  541. for (const auto &c : cases) {
  542. std::string version;
  543. int status = 0;
  544. std::string reason = "unset";
  545. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  546. << c.line;
  547. EXPECT_EQ(c.version, version);
  548. EXPECT_EQ(c.status, status);
  549. EXPECT_EQ(c.reason, reason);
  550. }
  551. }
  552. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  553. const char *lines[] = {
  554. "HTTP/2 200 OK\r\n",
  555. "HTTP/1.2 200 OK\r\n",
  556. "HTTP/1.1 20 OK\r\n",
  557. "HTTP/1.1 2000 OK\r\n",
  558. "HTTP/1.1 2x0 OK\r\n",
  559. "HTTP/1.1 200 OK\r\n",
  560. "HTTP/1.1 200OK\r\n",
  561. "HTTP/1.1 200 O\rK\r\n",
  562. "HTTP/1.1 200 OK",
  563. "HTTP/1.1 200 OK\r\nX",
  564. "",
  565. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  566. "HTTP/1.1 200 OK\n",
  567. #endif
  568. };
  569. for (auto line : lines) {
  570. std::string version;
  571. int status = 0;
  572. std::string reason;
  573. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  574. << line;
  575. }
  576. }
  577. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  578. // Long enough to overflow the stack when matched with std::regex.
  579. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  580. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  581. std::string version;
  582. int status = 0;
  583. std::string reason;
  584. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  585. EXPECT_EQ(200, status);
  586. EXPECT_EQ(long_reason, reason);
  587. }
  588. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  589. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  590. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  591. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  592. EXPECT_EQ("", detail::file_extension("noext"));
  593. EXPECT_EQ("", detail::file_extension("a."));
  594. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  595. EXPECT_EQ("", detail::file_extension("a.b-c"));
  596. // Long enough to overflow the stack when matched with std::regex.
  597. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  598. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  599. }
  600. #ifdef CPPHTTPLIB_SSL_ENABLED
  601. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  602. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  603. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  604. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  605. // A wildcard needs two labels after it, in the leftmost label only
  606. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  607. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  608. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  609. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  610. EXPECT_FALSE(
  611. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  612. // No name may have an empty label
  613. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  614. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  615. }
  616. #endif
  617. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  618. detail::case_ignore::hash hash;
  619. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  620. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  621. // Long enough to overflow the stack if hashed one call per character.
  622. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  623. }
  624. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  625. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  626. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  627. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  628. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  629. // Same 26-bit hash as html, svg and js.
  630. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  631. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  632. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  633. }
  634. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  635. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  636. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  637. }
  638. }
  639. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  640. // name anywhere else.
  641. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  642. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  643. #ifdef _WIN32
  644. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  645. #else
  646. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  647. #endif
  648. }
  649. }
  650. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  651. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  652. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  653. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  654. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  655. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  656. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  657. // Same 26-bit hash as application/json.
  658. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  659. }
  660. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  661. Request req;
  662. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  663. EXPECT_TRUE(req.is_multipart_form_data());
  664. std::string boundary;
  665. EXPECT_TRUE(detail::parse_multipart_boundary(
  666. req.get_header_value("Content-Type"), boundary));
  667. EXPECT_EQ("x", boundary);
  668. }
  669. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  670. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  671. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  672. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  673. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  674. // Same 26-bit hash as REMOTE_ADDR.
  675. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  676. }
  677. // Forward declaration: in split builds split.py strips `inline` and moves the
  678. // definition into httplib.cc, so detail::base64_encode is not visible from the
  679. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  680. // in both header-only and split builds.
  681. namespace httplib {
  682. namespace detail {
  683. std::string base64_encode(const std::string &in);
  684. } // namespace detail
  685. } // namespace httplib
  686. TEST(Base64EncodeTest, KnownAnswers) {
  687. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  688. // where the accumulator's top bit is already set before the next shift.
  689. EXPECT_EQ("", detail::base64_encode(""));
  690. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  691. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  692. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  693. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  694. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  695. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  696. // High bytes keep the top bit set across several rounds.
  697. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  698. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  699. }
  700. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  701. string unescapedCharacters = "-_.!~*'()";
  702. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  703. }
  704. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  705. string reservedCharacters = ";,/?:@&=+$";
  706. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  707. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  708. }
  709. TEST(ClientQueryOrder, PreserveOrder) {
  710. // This test reproduces Issue #2259: client may reorder query parameters
  711. // when sending a GET request. The expected behavior is that the client
  712. // preserves the original query string order when the caller supplied it
  713. // as part of the path.
  714. Server svr;
  715. svr.Get("/", [&](const Request &req, Response &res) {
  716. // Echo back the raw target so the test can assert ordering
  717. res.set_content(req.target, "text/plain");
  718. });
  719. std::thread t{[&] { svr.listen(HOST, PORT); }};
  720. auto se = detail::scope_exit([&] {
  721. svr.stop();
  722. t.join();
  723. ASSERT_FALSE(svr.is_running());
  724. });
  725. svr.wait_until_ready();
  726. Client cli(HOST, PORT);
  727. ASSERT_TRUE(cli.is_valid());
  728. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  729. auto res = cli.Get(original);
  730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  731. // Expect the echoed target to exactly match the original path (order
  732. // preserved)
  733. EXPECT_EQ(res->body, original);
  734. }
  735. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  736. string chineseCharacters = U8("中国語");
  737. string russianCharacters = U8("дом");
  738. string brazilianCharacters = U8("óculos");
  739. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  740. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  741. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  742. "%D0%B4%D0%BE%D0%BC");
  743. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  744. }
  745. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  746. string unescapedCharacters = "-_.!~*'()";
  747. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  748. }
  749. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  750. string reservedCharacters = ";,/?:@&=+$";
  751. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  752. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  753. }
  754. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  755. string chineseCharacters = U8("中国語");
  756. string russianCharacters = U8("дом");
  757. string brazilianCharacters = U8("óculos");
  758. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  759. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  760. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  761. "%D0%B4%D0%BE%D0%BC");
  762. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  763. }
  764. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  765. // Issue #2082 use case: encoding path component with ampersand
  766. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  767. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  768. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  769. }
  770. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'()";
  772. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  773. }
  774. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  775. string reservedCharacters = ";,/?:@&=+$#";
  776. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  777. }
  778. TEST(EncodeUriTest, TestUTF8Characters) {
  779. string chineseCharacters = U8("中国語");
  780. string russianCharacters = U8("дом");
  781. string brazilianCharacters = U8("óculos");
  782. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  783. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  784. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  785. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  786. }
  787. TEST(EncodeUriTest, TestCompleteUri) {
  788. string uri =
  789. "https://example.com/path/to/resource?query=value&param=test#fragment";
  790. EXPECT_EQ(
  791. httplib::encode_uri(uri),
  792. "https://example.com/path/to/resource?query=value&param=test#fragment");
  793. }
  794. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  795. string uri =
  796. "https://example.com/path with spaces/file name.html?q=hello world";
  797. EXPECT_EQ(httplib::encode_uri(uri),
  798. "https://example.com/path%20with%20spaces/"
  799. "file%20name.html?q=hello%20world");
  800. }
  801. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  802. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  803. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  804. }
  805. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  806. string unescapedCharacters = "-_.!~*'()";
  807. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  808. }
  809. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  810. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  811. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  812. string encodedBrazilian = "%C3%B3culos";
  813. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  814. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  815. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  816. }
  817. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  818. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  819. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  820. "Piri Tommy Villiers - on & on");
  821. }
  822. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  823. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  824. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  825. }
  826. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  827. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  828. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  829. }
  830. TEST(DecodeUriTest, TestUTF8Characters) {
  831. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  832. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  833. string encodedBrazilian = "%C3%B3culos";
  834. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  835. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  836. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  837. }
  838. TEST(DecodeUriTest, TestCompleteUri) {
  839. string encodedUri = "https://example.com/path%20with%20spaces/"
  840. "file%20name.html?q=hello%20world";
  841. EXPECT_EQ(
  842. httplib::decode_uri(encodedUri),
  843. "https://example.com/path with spaces/file name.html?q=hello world");
  844. }
  845. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  846. string original =
  847. "https://example.com/path with spaces/file name.html?q=hello world";
  848. string encoded = httplib::encode_uri(original);
  849. string decoded = httplib::decode_uri(encoded);
  850. EXPECT_EQ(decoded, original);
  851. }
  852. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  853. // decode_uri is the inverse of encode_uri: an escaped reserved character
  854. // stays encoded so it is not promoted into a real delimiter, while
  855. // non-reserved escapes still decode (like JS decodeURI).
  856. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  857. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  858. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  859. "%3F%3A%40%26%3D%2B%24%2C%3B");
  860. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  861. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  862. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  863. "http://example.com/a%2Fb");
  864. // decode_uri_component still decodes the reserved character.
  865. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  866. }
  867. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  868. string original = "Piri Tommy Villiers - on & on";
  869. string encoded = httplib::encode_uri_component(original);
  870. string decoded = httplib::decode_uri_component(encoded);
  871. EXPECT_EQ(decoded, original);
  872. }
  873. TEST(TrimTests, TrimStringTests) {
  874. EXPECT_EQ("abc", detail::trim_copy("abc"));
  875. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  876. EXPECT_TRUE(detail::trim_copy("").empty());
  877. }
  878. TEST(AsciiTest, LocaleIndependentClassification) {
  879. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  880. // which consult the global C locale: std::isalnum(0xC5) can return true
  881. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  882. // helpers must classify every byte by the ASCII grammar alone.
  883. for (int i = 0; i < 256; i++) {
  884. auto c = static_cast<char>(i);
  885. auto is_digit = i >= '0' && i <= '9';
  886. auto is_upper = i >= 'A' && i <= 'Z';
  887. auto is_lower = i >= 'a' && i <= 'z';
  888. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  889. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  890. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  891. << "byte " << i;
  892. }
  893. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  894. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  895. // Non-ASCII bytes must be percent-encoded, never passed through as
  896. // alphanumeric.
  897. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  898. }
  899. TEST(FromCharsTest, Double) {
  900. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  901. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  902. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  903. auto parse = [](const std::string &s, double &v) {
  904. return detail::from_chars(s.data(), s.data() + s.size(), v);
  905. };
  906. double v = -1.0;
  907. // Representative quality values.
  908. EXPECT_EQ(parse("0", v).ec, std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.0);
  910. EXPECT_EQ(parse("1", v).ec, std::errc{});
  911. EXPECT_DOUBLE_EQ(v, 1.0);
  912. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  913. EXPECT_DOUBLE_EQ(v, 0.8);
  914. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  915. EXPECT_DOUBLE_EQ(v, 0.001);
  916. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  917. EXPECT_DOUBLE_EQ(v, 1.0);
  918. // A missing integer or fractional part is tolerated.
  919. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  920. EXPECT_DOUBLE_EQ(v, 0.5);
  921. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  922. EXPECT_DOUBLE_EQ(v, 5.0);
  923. // Values outside [0, 1] still parse; the caller range-checks them.
  924. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  925. EXPECT_DOUBLE_EQ(v, 123.456);
  926. // Stops at the first byte that is not part of the number and reports where.
  927. std::string trailing = "0.9, text/html";
  928. auto r = parse(trailing, v);
  929. EXPECT_EQ(r.ec, std::errc{});
  930. EXPECT_DOUBLE_EQ(v, 0.9);
  931. EXPECT_EQ(*r.ptr, ',');
  932. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  933. // outright, and an 'e'/'E' simply ends the number.
  934. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  935. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  936. std::string exp_input = "1.5e3";
  937. r = parse(exp_input, v);
  938. EXPECT_EQ(r.ec, std::errc{});
  939. EXPECT_DOUBLE_EQ(v, 1.5);
  940. EXPECT_EQ(*r.ptr, 'e');
  941. // Invalid inputs.
  942. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  943. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  944. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  945. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  946. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  947. // Pathological but well-formed inputs must stay bounded (no overflow, no
  948. // out-of-bounds table access) and stay within [0, 1] for the caller.
  949. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  950. std::errc{});
  951. EXPECT_DOUBLE_EQ(v, 0.0);
  952. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  953. std::errc{});
  954. EXPECT_GE(v, 0.0);
  955. EXPECT_LE(v, 1.0);
  956. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  957. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  958. }
  959. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  960. // Simple case without quality values
  961. std::vector<std::string> result1;
  962. EXPECT_TRUE(detail::parse_accept_header(
  963. "text/html,application/json,text/plain", result1));
  964. EXPECT_EQ(result1.size(), 3U);
  965. EXPECT_EQ(result1[0], "text/html");
  966. EXPECT_EQ(result1[1], "application/json");
  967. EXPECT_EQ(result1[2], "text/plain");
  968. // With quality values
  969. std::vector<std::string> result2;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  972. EXPECT_EQ(result2.size(), 3U);
  973. EXPECT_EQ(result2[0], "application/json"); // highest q value
  974. EXPECT_EQ(result2[1], "text/html");
  975. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  976. }
  977. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  978. // Mixed with and without quality values
  979. std::vector<std::string> result;
  980. EXPECT_TRUE(detail::parse_accept_header(
  981. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  982. EXPECT_EQ(result.size(), 3U);
  983. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  984. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  985. EXPECT_EQ(result[2], "application/json"); // q=0.5
  986. }
  987. TEST(ParseAcceptHeaderTest, EdgeCases) {
  988. // Empty header
  989. std::vector<std::string> empty_result;
  990. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  991. EXPECT_TRUE(empty_result.empty());
  992. // Single type
  993. std::vector<std::string> single_result;
  994. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  995. EXPECT_EQ(single_result.size(), 1U);
  996. EXPECT_EQ(single_result[0], "application/json");
  997. // Wildcard types
  998. std::vector<std::string> wildcard_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1001. EXPECT_EQ(wildcard_result.size(), 3U);
  1002. EXPECT_EQ(wildcard_result[0], "application/json");
  1003. EXPECT_EQ(wildcard_result[1], "text/*");
  1004. EXPECT_EQ(wildcard_result[2], "*/*");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1007. // Common browser Accept header
  1008. std::vector<std::string> browser_result;
  1009. EXPECT_TRUE(
  1010. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1011. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1012. browser_result));
  1013. EXPECT_EQ(browser_result.size(), 6U);
  1014. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1015. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1016. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1017. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1018. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1019. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1020. // API client header
  1021. std::vector<std::string> api_result;
  1022. EXPECT_TRUE(detail::parse_accept_header(
  1023. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1024. api_result));
  1025. EXPECT_EQ(api_result.size(), 3U);
  1026. EXPECT_EQ(api_result[0], "application/json");
  1027. EXPECT_EQ(api_result[1], "application/xml");
  1028. EXPECT_EQ(api_result[2], "text/plain");
  1029. }
  1030. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1031. // Quality value with 3 decimal places
  1032. std::vector<std::string> decimal_result;
  1033. EXPECT_TRUE(detail::parse_accept_header(
  1034. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1035. EXPECT_EQ(decimal_result.size(), 2U);
  1036. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1037. EXPECT_EQ(decimal_result[1], "text/html");
  1038. // Zero quality (should still be included but with lowest priority)
  1039. std::vector<std::string> zero_q_result;
  1040. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1041. zero_q_result));
  1042. EXPECT_EQ(zero_q_result.size(), 2U);
  1043. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1044. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1045. // No spaces around commas
  1046. std::vector<std::string> no_space_result;
  1047. EXPECT_TRUE(detail::parse_accept_header(
  1048. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1049. no_space_result));
  1050. EXPECT_EQ(no_space_result.size(), 3U);
  1051. EXPECT_EQ(no_space_result[0], "text/html");
  1052. EXPECT_EQ(no_space_result[1], "application/json");
  1053. EXPECT_EQ(no_space_result[2], "text/plain");
  1054. }
  1055. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1056. // Quality values always use '.' as the decimal separator, so parsing must
  1057. // not depend on the process locale. An embedding application may have
  1058. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1059. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1060. std::string saved = cur ? cur : "C";
  1061. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1062. "fr_FR.UTF-8"};
  1063. bool switched = false;
  1064. for (const auto loc : comma_locales) {
  1065. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1066. std::localeconv()->decimal_point[0] == ',') {
  1067. switched = true;
  1068. break;
  1069. }
  1070. }
  1071. if (!switched) {
  1072. std::setlocale(LC_NUMERIC, saved.c_str());
  1073. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1074. }
  1075. // The higher-weighted type appears later in the list, so a correct parse
  1076. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1077. // sensitive parse reads both weights as 0 and leaves the original order.
  1078. std::vector<std::string> result;
  1079. EXPECT_TRUE(detail::parse_accept_header(
  1080. "application/json;q=0.1,text/html;q=0.9", result));
  1081. ASSERT_EQ(result.size(), 2U);
  1082. EXPECT_EQ(result[0], "text/html");
  1083. EXPECT_EQ(result[1], "application/json");
  1084. std::setlocale(LC_NUMERIC, saved.c_str());
  1085. }
  1086. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1087. std::vector<std::string> result;
  1088. // Invalid quality value (> 1.0)
  1089. EXPECT_FALSE(
  1090. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1091. // Invalid quality value (< 0.0)
  1092. EXPECT_FALSE(
  1093. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1094. // Invalid quality value (not a number)
  1095. EXPECT_FALSE(detail::parse_accept_header(
  1096. "text/html;q=invalid,application/json", result));
  1097. // A valid numeric prefix does not make the entire quality value valid.
  1098. EXPECT_FALSE(detail::parse_accept_header(
  1099. "text/html;q=0.5junk,application/json", result));
  1100. // Empty quality value
  1101. EXPECT_FALSE(
  1102. detail::parse_accept_header("text/html;q=,application/json", result));
  1103. // Invalid media type format (no slash and not wildcard)
  1104. EXPECT_FALSE(
  1105. detail::parse_accept_header("invalidtype,application/json", result));
  1106. // Valid cases should still work
  1107. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1108. EXPECT_EQ(result.size(), 1U);
  1109. EXPECT_EQ(result[0], "*/*");
  1110. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1111. EXPECT_EQ(result.size(), 1U);
  1112. EXPECT_EQ(result[0], "*");
  1113. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1114. EXPECT_EQ(result.size(), 1U);
  1115. EXPECT_EQ(result[0], "text/*");
  1116. }
  1117. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1118. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1119. // and must not be answered with 400 Bad Request.
  1120. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1121. struct {
  1122. const char *value;
  1123. std::vector<std::string> expected;
  1124. } cases[] = {
  1125. {",application/json", {"application/json"}},
  1126. {"text/html,", {"text/html"}},
  1127. {"text/html,,*/*", {"text/html", "*/*"}},
  1128. // An empty element may be spelled with whitespace in it
  1129. {"text/html, , application/json", {"text/html", "application/json"}},
  1130. // Nothing but empty elements is an empty list, which means the same
  1131. // thing as no Accept header at all
  1132. {",,,", {}},
  1133. // Quality values still apply across ignored empty elements
  1134. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1135. };
  1136. for (const auto &c : cases) {
  1137. std::vector<std::string> result;
  1138. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1139. << "value: " << c.value;
  1140. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1141. }
  1142. // An invalid entry is still rejected when empty elements surround it
  1143. std::vector<std::string> result;
  1144. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1145. }
  1146. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1147. // or ';' inside one does not end the list element or the parameter. Section
  1148. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1149. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1150. struct {
  1151. const char *value;
  1152. std::vector<std::string> expected;
  1153. } cases[] = {
  1154. {"text/html;profile=\"a,b\",application/json",
  1155. {"text/html", "application/json"}},
  1156. // A "q=" inside a quoted value is not the weight
  1157. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1158. {"text/html", "application/json"}},
  1159. // The weight after a quoted value still applies
  1160. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1161. {"application/json", "text/html"}},
  1162. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1163. {"application/json", "text/html"}},
  1164. {"text/html;profile=\"a\\\"b\",application/json",
  1165. {"text/html", "application/json"}},
  1166. // An escaped backslash does not escape the '"' after it
  1167. {"text/html;profile=\"a\\\\\",application/json",
  1168. {"text/html", "application/json"}},
  1169. };
  1170. for (const auto &c : cases) {
  1171. std::vector<std::string> result;
  1172. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1173. << "value: " << c.value;
  1174. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1175. }
  1176. }
  1177. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1178. Server svr;
  1179. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1180. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1181. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1182. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1183. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1184. res.set_content("ok", "text/plain");
  1185. });
  1186. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1187. EXPECT_TRUE(false);
  1188. res.set_content("bad request", "text/plain");
  1189. });
  1190. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1191. auto se = detail::scope_exit([&] {
  1192. svr.stop();
  1193. listen_thread.join();
  1194. ASSERT_FALSE(svr.is_running());
  1195. });
  1196. svr.wait_until_ready();
  1197. Client cli("localhost", PORT);
  1198. {
  1199. auto res = cli.Get(
  1200. "/accept_ok",
  1201. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1203. EXPECT_EQ(StatusCode::OK_200, res->status);
  1204. }
  1205. {
  1206. auto res = cli.Get("/accept_bad_request",
  1207. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1209. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1210. }
  1211. }
  1212. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1213. Server svr;
  1214. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1215. res.set_content("ok", "text/plain");
  1216. });
  1217. std::atomic<int> start_count{0};
  1218. std::atomic<bool> running_when_called{false};
  1219. svr.set_start_handler([&]() {
  1220. running_when_called = svr.is_running();
  1221. start_count++;
  1222. });
  1223. auto port = svr.bind_to_any_port(HOST);
  1224. std::thread t([&]() { svr.listen_after_bind(); });
  1225. auto se = detail::scope_exit([&] {
  1226. svr.stop();
  1227. t.join();
  1228. ASSERT_FALSE(svr.is_running());
  1229. });
  1230. svr.wait_until_ready();
  1231. // A successful request proves the accept loop is running, which the start
  1232. // handler precedes; so by now the handler must have run exactly once.
  1233. Client cli(HOST, port);
  1234. cli.set_connection_timeout(std::chrono::seconds(5));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1237. EXPECT_EQ(StatusCode::OK_200, res->status);
  1238. EXPECT_EQ(1, start_count.load());
  1239. EXPECT_TRUE(running_when_called.load());
  1240. }
  1241. TEST(DivideTest, DivideStringTests) {
  1242. auto divide = [](const std::string &str, char d) {
  1243. std::string lhs;
  1244. std::string rhs;
  1245. detail::divide(str, d,
  1246. [&](const char *lhs_data, std::size_t lhs_size,
  1247. const char *rhs_data, std::size_t rhs_size) {
  1248. lhs.assign(lhs_data, lhs_size);
  1249. rhs.assign(rhs_data, rhs_size);
  1250. });
  1251. return std::make_pair(std::move(lhs), std::move(rhs));
  1252. };
  1253. {
  1254. const auto res = divide("", '=');
  1255. EXPECT_EQ(res.first, "");
  1256. EXPECT_EQ(res.second, "");
  1257. }
  1258. {
  1259. const auto res = divide("=", '=');
  1260. EXPECT_EQ(res.first, "");
  1261. EXPECT_EQ(res.second, "");
  1262. }
  1263. {
  1264. const auto res = divide(" ", '=');
  1265. EXPECT_EQ(res.first, " ");
  1266. EXPECT_EQ(res.second, "");
  1267. }
  1268. {
  1269. const auto res = divide("a", '=');
  1270. EXPECT_EQ(res.first, "a");
  1271. EXPECT_EQ(res.second, "");
  1272. }
  1273. {
  1274. const auto res = divide("a=", '=');
  1275. EXPECT_EQ(res.first, "a");
  1276. EXPECT_EQ(res.second, "");
  1277. }
  1278. {
  1279. const auto res = divide("=b", '=');
  1280. EXPECT_EQ(res.first, "");
  1281. EXPECT_EQ(res.second, "b");
  1282. }
  1283. {
  1284. const auto res = divide("a=b", '=');
  1285. EXPECT_EQ(res.first, "a");
  1286. EXPECT_EQ(res.second, "b");
  1287. }
  1288. {
  1289. const auto res = divide("a=b=", '=');
  1290. EXPECT_EQ(res.first, "a");
  1291. EXPECT_EQ(res.second, "b=");
  1292. }
  1293. {
  1294. const auto res = divide("a=b=c", '=');
  1295. EXPECT_EQ(res.first, "a");
  1296. EXPECT_EQ(res.second, "b=c");
  1297. }
  1298. }
  1299. TEST(SplitTest, ParseQueryString) {
  1300. string s = "key1=val1&key2=val2&key3=val3";
  1301. Params dic;
  1302. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1303. [&](const char *b, const char *e) {
  1304. string key, val;
  1305. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1306. if (key.empty()) {
  1307. key.assign(b2, e2);
  1308. } else {
  1309. val.assign(b2, e2);
  1310. }
  1311. });
  1312. dic.emplace(key, val);
  1313. });
  1314. EXPECT_EQ("val1", dic.find("key1")->second);
  1315. EXPECT_EQ("val2", dic.find("key2")->second);
  1316. EXPECT_EQ("val3", dic.find("key3")->second);
  1317. }
  1318. TEST(SplitTest, ParseInvalidQueryTests) {
  1319. {
  1320. string s = " ";
  1321. Params dict;
  1322. detail::parse_query_text(s, dict);
  1323. EXPECT_TRUE(dict.empty());
  1324. }
  1325. {
  1326. string s = " = =";
  1327. Params dict;
  1328. detail::parse_query_text(s, dict);
  1329. EXPECT_TRUE(dict.empty());
  1330. }
  1331. }
  1332. TEST(ParseQueryTest, ParseQueryString) {
  1333. {
  1334. std::string s = "key1=val1&key2=val2&key3=val3";
  1335. Params dic;
  1336. detail::parse_query_text(s, dic);
  1337. EXPECT_EQ("val1", dic.find("key1")->second);
  1338. EXPECT_EQ("val2", dic.find("key2")->second);
  1339. EXPECT_EQ("val3", dic.find("key3")->second);
  1340. }
  1341. {
  1342. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1343. Params dic;
  1344. detail::parse_query_text(s, dic);
  1345. EXPECT_EQ("", dic.find("key1")->second);
  1346. EXPECT_EQ("val1", dic.find("key2")->second);
  1347. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1348. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1349. }
  1350. }
  1351. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1352. Params dic;
  1353. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1354. dic.emplace("key1", "val1");
  1355. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1356. dic.emplace("key2", "val2");
  1357. dic.emplace("key3", "val3");
  1358. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1359. }
  1360. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1361. Params params;
  1362. params.emplace("a", "1");
  1363. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1364. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1365. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1366. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1367. // Long enough to overflow the stack when matched with std::regex.
  1368. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1369. EXPECT_EQ("/p?" + long_query + "&a=1",
  1370. append_query_params("/p?" + long_query, params));
  1371. }
  1372. // Joins every entry of a Headers or Params into "key=value " so a whole
  1373. // traversal can be compared in one assertion. Both are instantiations of the
  1374. // same insertion-ordered container, so one helper serves both.
  1375. template <typename Map> static std::string entries_to_string(const Map &m) {
  1376. std::string s;
  1377. for (const auto &entry : m) {
  1378. s += entry.first + "=" + entry.second + " ";
  1379. }
  1380. return s;
  1381. }
  1382. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1383. // Params used to be a std::multimap, which sorted by name and handed the
  1384. // caller's query back alphabetised. A client signing its query string could
  1385. // not reproduce the order it asked for.
  1386. Params dic;
  1387. dic.emplace("zulu", "1");
  1388. dic.emplace("alpha", "2");
  1389. dic.emplace("mike", "3");
  1390. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1391. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1392. }
  1393. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1394. Params dic;
  1395. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1396. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1397. }
  1398. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1399. Request req;
  1400. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1401. req.params);
  1402. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1403. EXPECT_EQ("first", req.get_param_value("tag"));
  1404. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1405. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1406. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1407. EXPECT_EQ("", req.get_param_value("tag", 3));
  1408. }
  1409. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1410. // Params shares its container with Headers, which matches field names
  1411. // case-insensitively. Parameter names must not pick that up.
  1412. Params dic;
  1413. dic.emplace("Key", "upper");
  1414. dic.emplace("key", "lower");
  1415. EXPECT_EQ(2U, dic.size());
  1416. EXPECT_EQ(1U, dic.count("Key"));
  1417. EXPECT_EQ(1U, dic.count("key"));
  1418. EXPECT_EQ("upper", dic.find("Key")->second);
  1419. EXPECT_EQ("lower", dic.find("key")->second);
  1420. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1421. }
  1422. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1423. Server svr;
  1424. std::string order;
  1425. svr.Get("/order", [&](const Request &req, Response &res) {
  1426. order = entries_to_string(req.params);
  1427. res.set_content("ok", "text/plain");
  1428. });
  1429. auto port = svr.bind_to_any_port(HOST);
  1430. thread t = thread([&] { svr.listen_after_bind(); });
  1431. auto se = detail::scope_exit([&] {
  1432. svr.stop();
  1433. t.join();
  1434. ASSERT_FALSE(svr.is_running());
  1435. });
  1436. svr.wait_until_ready();
  1437. Client cli(HOST, port);
  1438. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1439. ASSERT_TRUE(res);
  1440. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1441. }
  1442. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1443. Server svr;
  1444. std::string field_order, file_order;
  1445. svr.Post("/order", [&](const Request &req, Response &res) {
  1446. for (const auto &field : req.form.fields) {
  1447. field_order += field.first + "=" + field.second.content + " ";
  1448. }
  1449. for (const auto &file : req.form.files) {
  1450. file_order += file.first + "=" + file.second.filename + " ";
  1451. }
  1452. res.set_content("ok", "text/plain");
  1453. });
  1454. auto port = svr.bind_to_any_port(HOST);
  1455. thread t = thread([&] { svr.listen_after_bind(); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. t.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. UploadFormDataItems items = {
  1463. {"zulu", "1", "", ""},
  1464. {"alpha", "2", "", ""},
  1465. {"mike", "3", "", ""},
  1466. {"zebra", "z", "z.txt", "text/plain"},
  1467. {"apple", "a", "a.txt", "text/plain"},
  1468. };
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/order", items);
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1473. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1474. }
  1475. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1476. Server svr;
  1477. std::vector<std::string> values;
  1478. std::string first, second, out_of_range, order;
  1479. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1480. values = req.form.get_fields("tag");
  1481. first = req.form.get_field("tag", 0);
  1482. second = req.form.get_field("tag", 1);
  1483. out_of_range = req.form.get_field("tag", 2);
  1484. for (const auto &field : req.form.fields) {
  1485. order += field.first + "=" + field.second.content + " ";
  1486. }
  1487. res.set_content("ok", "text/plain");
  1488. });
  1489. auto port = svr.bind_to_any_port(HOST);
  1490. thread t = thread([&] { svr.listen_after_bind(); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. t.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1498. // not adjacent in the container.
  1499. UploadFormDataItems items = {
  1500. {"tag", "first", "", ""},
  1501. {"other", "x", "", ""},
  1502. {"tag", "second", "", ""},
  1503. };
  1504. Client cli(HOST, port);
  1505. auto res = cli.Post("/repeated", items);
  1506. ASSERT_TRUE(res);
  1507. ASSERT_EQ(2U, values.size());
  1508. EXPECT_EQ("first", values[0]);
  1509. EXPECT_EQ("second", values[1]);
  1510. EXPECT_EQ("first", first);
  1511. EXPECT_EQ("second", second);
  1512. // std::multimap already kept entries sharing a name in insertion order, so
  1513. // everything above passes without this change too. The whole traversal is
  1514. // what tells the two apart: sorting by name would hoist "other" to the front
  1515. // and the two "tag" parts would end up adjacent.
  1516. EXPECT_EQ("tag=first other=x tag=second ", order);
  1517. // Advancing past the last entry of a name used to run off the container;
  1518. // the container's saturating increment makes it return the default instead.
  1519. EXPECT_EQ("", out_of_range);
  1520. }
  1521. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1522. Server svr;
  1523. std::string file_names;
  1524. svr.Post("/upload", [&](const Request &req, Response &res) {
  1525. for (const auto &file : req.form.files) {
  1526. file_names += file.first + "|" + file.second.filename + " ";
  1527. }
  1528. res.set_content("ok", "text/plain");
  1529. });
  1530. auto port = svr.bind_to_any_port(HOST);
  1531. thread t = thread([&] { svr.listen_after_bind(); });
  1532. auto se = detail::scope_exit([&] {
  1533. svr.stop();
  1534. t.join();
  1535. ASSERT_FALSE(svr.is_running());
  1536. });
  1537. svr.wait_until_ready();
  1538. // A trailing backslash would otherwise escape the closing quote.
  1539. UploadFormDataItems items = {
  1540. {"dir\\", "x", "a.txt", "text/plain"},
  1541. {"b", "y", "a\\\\b.txt", "text/plain"},
  1542. };
  1543. Client cli(HOST, port);
  1544. auto res = cli.Post("/upload", items);
  1545. ASSERT_TRUE(res);
  1546. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1547. }
  1548. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1549. // Server::read_content() keeps a FormFields::iterator alive across the
  1550. // content callbacks that fill the part it points at. The container is
  1551. // vector-backed, so a later emplace can reallocate and invalidate an older
  1552. // iterator; 64 parts grow the vector through seven reallocations, which
  1553. // checks that every part's content still lands in its own entry.
  1554. const size_t part_count = 64;
  1555. // One formula for both the parts sent and the values expected back, so the
  1556. // two cannot drift apart.
  1557. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1558. auto content_of = [](size_t i) {
  1559. return std::string(64, static_cast<char>('a' + (i % 26)));
  1560. };
  1561. Server svr;
  1562. std::vector<std::pair<std::string, std::string>> received;
  1563. svr.Post("/many", [&](const Request &req, Response &res) {
  1564. for (const auto &field : req.form.fields) {
  1565. received.emplace_back(field.first, field.second.content);
  1566. }
  1567. res.set_content("ok", "text/plain");
  1568. });
  1569. auto port = svr.bind_to_any_port(HOST);
  1570. thread t = thread([&] { svr.listen_after_bind(); });
  1571. auto se = detail::scope_exit([&] {
  1572. svr.stop();
  1573. t.join();
  1574. ASSERT_FALSE(svr.is_running());
  1575. });
  1576. svr.wait_until_ready();
  1577. UploadFormDataItems items;
  1578. for (size_t i = 0; i < part_count; i++) {
  1579. items.push_back({name_of(i), content_of(i), "", ""});
  1580. }
  1581. Client cli(HOST, port);
  1582. auto res = cli.Post("/many", items);
  1583. ASSERT_TRUE(res);
  1584. ASSERT_EQ(part_count, received.size());
  1585. for (size_t i = 0; i < part_count; i++) {
  1586. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1587. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1588. }
  1589. }
  1590. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1591. string content_type = "multipart/form-data; boundary=something";
  1592. string boundary;
  1593. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1594. EXPECT_TRUE(ret);
  1595. EXPECT_EQ(boundary, "something");
  1596. }
  1597. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1598. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1599. string boundary;
  1600. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1601. EXPECT_TRUE(ret);
  1602. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1603. }
  1604. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1605. string content_type =
  1606. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1607. string boundary;
  1608. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1609. EXPECT_TRUE(ret);
  1610. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1611. }
  1612. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1613. string content_type =
  1614. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1615. string boundary;
  1616. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1617. EXPECT_TRUE(ret);
  1618. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1619. }
  1620. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1621. const string boundary(70, 'a');
  1622. string content_type = "multipart/form-data; boundary=" + boundary;
  1623. string parsed;
  1624. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1625. EXPECT_TRUE(ret);
  1626. EXPECT_EQ(parsed, boundary);
  1627. }
  1628. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1629. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1630. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1631. string parsed;
  1632. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1633. EXPECT_FALSE(ret);
  1634. }
  1635. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1636. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1637. // is 72 characters on the wire and still valid.
  1638. const string boundary(70, 'a');
  1639. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1640. string parsed;
  1641. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1642. EXPECT_EQ(parsed, boundary);
  1643. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1644. parsed.clear();
  1645. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1646. }
  1647. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1648. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1649. // The parameter parser must not treat that '=' as the key/value separator.
  1650. string content_type =
  1651. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1652. "charset=UTF-8";
  1653. string parsed;
  1654. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1655. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1656. }
  1657. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1658. // A ';' inside the quoted-string is part of the value, not a parameter
  1659. // separator, so it must not truncate the boundary.
  1660. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1661. string parsed;
  1662. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1663. EXPECT_EQ(parsed, "a;b");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1666. string parsed;
  1667. EXPECT_TRUE(detail::parse_multipart_boundary(
  1668. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1669. EXPECT_EQ("a\\b", parsed);
  1670. EXPECT_TRUE(detail::parse_multipart_boundary(
  1671. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1672. EXPECT_EQ("a\"b", parsed);
  1673. }
  1674. TEST(ParseDispositionParamsTest, QuotedValues) {
  1675. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1676. // ';' and '=' are ordinary characters inside one.
  1677. struct {
  1678. const char *value;
  1679. std::vector<std::pair<const char *, const char *>> expected;
  1680. } cases[] = {
  1681. {"name=\"file1\"; filename=\"a.txt\"",
  1682. {{"name", "file1"}, {"filename", "a.txt"}}},
  1683. // Whitespace around '=' and ';' is still trimmed
  1684. {"name=\"file2\" ;filename = \"a.html\"",
  1685. {{"name", "file2"}, {"filename", "a.html"}}},
  1686. // '=' inside the value used to leave only the text after the last one
  1687. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1688. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1689. {"name=\"x=y\"", {{"name", "x=y"}}},
  1690. // ';' inside the value used to truncate the pair and leave a bogus one
  1691. {"name=\"file3\"; filename=\"a;b.txt\"",
  1692. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1693. // An unquoted value keeps working, and so does filename*
  1694. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1695. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1696. // A parameter with no key is dropped rather than turned into one whose
  1697. // key is the value
  1698. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1699. // An escaped quote does not end the value
  1700. {"name=\"a\\\"; filename=evil.php\"",
  1701. {{"name", "a\"; filename=evil.php"}}},
  1702. // Other backslashes, as in a Windows path, are kept
  1703. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1704. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1705. };
  1706. for (const auto &c : cases) {
  1707. Params params;
  1708. detail::parse_disposition_params(c.value, params);
  1709. for (const auto &kv : c.expected) {
  1710. auto it = params.find(kv.first);
  1711. ASSERT_NE(it, params.end())
  1712. << "value: " << c.value << ", key: " << kv.first;
  1713. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1714. }
  1715. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1716. }
  1717. }
  1718. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1719. Server svr;
  1720. std::string filename;
  1721. std::string content;
  1722. svr.Post("/upload", [&](const Request &req, Response &) {
  1723. const auto &file = req.form.get_file("file");
  1724. filename = file.filename;
  1725. content = file.content;
  1726. });
  1727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1728. auto se = detail::scope_exit([&] {
  1729. svr.stop();
  1730. thread.join();
  1731. ASSERT_FALSE(svr.is_running());
  1732. });
  1733. svr.wait_until_ready();
  1734. std::string body = "--B\r\n"
  1735. "Content-Disposition: form-data; name=\"file\"; "
  1736. "filename=\"a.txt\"\r\n"
  1737. "Content-Type: text/plain\r\n"
  1738. "\r\n"
  1739. "hello\r\n"
  1740. "--B--\r\n";
  1741. Client cli(HOST, PORT);
  1742. auto res = cli.Post(
  1743. "/upload",
  1744. [&](size_t offset, DataSink &sink) {
  1745. if (offset < body.size()) {
  1746. sink.write(&body[offset], 1);
  1747. } else {
  1748. sink.done();
  1749. }
  1750. return true;
  1751. },
  1752. "multipart/form-data; boundary=B");
  1753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1754. EXPECT_EQ(StatusCode::OK_200, res->status);
  1755. EXPECT_EQ("a.txt", filename);
  1756. EXPECT_EQ("hello", content);
  1757. }
  1758. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1759. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1760. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1761. Server svr;
  1762. std::string field_value, file_name, file_filename;
  1763. bool has_field = false, has_file = false;
  1764. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1765. has_field = req.form.has_field("x=y");
  1766. field_value = req.form.get_field("x=y");
  1767. has_file = req.form.has_file("file1");
  1768. const auto &file = req.form.get_file("file1");
  1769. file_name = file.name;
  1770. file_filename = file.filename;
  1771. res.set_content("ok", "text/plain");
  1772. });
  1773. auto port = svr.bind_to_any_port(HOST);
  1774. thread t = thread([&] { svr.listen_after_bind(); });
  1775. auto se = detail::scope_exit([&] {
  1776. svr.stop();
  1777. t.join();
  1778. ASSERT_FALSE(svr.is_running());
  1779. });
  1780. svr.wait_until_ready();
  1781. UploadFormDataItems items = {
  1782. {"x=y", "field-value", "", ""},
  1783. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1784. };
  1785. Client cli(HOST, port);
  1786. auto res = cli.Post("/quoted", items);
  1787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1788. ASSERT_EQ(StatusCode::OK_200, res->status);
  1789. EXPECT_TRUE(has_field);
  1790. EXPECT_EQ("field-value", field_value);
  1791. EXPECT_TRUE(has_file);
  1792. EXPECT_EQ("file1", file_name);
  1793. EXPECT_EQ("a;b=report.pdf", file_filename);
  1794. }
  1795. TEST(GetHeaderValueTest, DefaultValue) {
  1796. Headers headers = {{"Dummy", "Dummy"}};
  1797. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1798. EXPECT_STREQ("text/plain", val);
  1799. }
  1800. TEST(GetHeaderValueTest, DefaultValueInt) {
  1801. Headers headers = {{"Dummy", "Dummy"}};
  1802. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1803. EXPECT_EQ(100ull, val);
  1804. }
  1805. TEST(GetHeaderValueTest, RegularValue) {
  1806. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1807. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1808. EXPECT_STREQ("text/html", val);
  1809. }
  1810. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1811. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1812. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1813. EXPECT_STREQ("text/html", val);
  1814. }
  1815. TEST(GetHeaderValueTest, SetContent) {
  1816. Response res;
  1817. res.set_content("html", "text/html");
  1818. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1819. res.set_content("text", "text/plain");
  1820. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1821. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1822. }
  1823. TEST(GetHeaderValueTest, RegularValueInt) {
  1824. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1825. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1826. EXPECT_EQ(100ull, val);
  1827. }
  1828. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1829. Headers headers = {{"Content-Length", "x"}};
  1830. auto is_invalid_value = false;
  1831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1832. is_invalid_value);
  1833. EXPECT_EQ(0ull, val);
  1834. EXPECT_TRUE(is_invalid_value);
  1835. }
  1836. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1837. // An all-digit value that overflows size_t must be reported as invalid, not
  1838. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1839. // a large length to a small one on 32-bit builds, leaving the framing length
  1840. // wrong while is_invalid_value stayed false.
  1841. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1842. auto is_invalid_value = false;
  1843. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1844. is_invalid_value);
  1845. EXPECT_TRUE(is_invalid_value);
  1846. // A well-formed length is unaffected.
  1847. Headers ok = {{"Content-Length", "1234"}};
  1848. is_invalid_value = false;
  1849. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1850. is_invalid_value);
  1851. EXPECT_EQ(1234ull, val);
  1852. EXPECT_FALSE(is_invalid_value);
  1853. }
  1854. TEST(GetHeaderValueTest, Range) {
  1855. {
  1856. Headers headers = {make_range_header({{1, -1}})};
  1857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1858. EXPECT_STREQ("bytes=1-", val);
  1859. }
  1860. {
  1861. Headers headers = {make_range_header({{-1, 1}})};
  1862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1863. EXPECT_STREQ("bytes=-1", val);
  1864. }
  1865. {
  1866. Headers headers = {make_range_header({{1, 10}})};
  1867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1868. EXPECT_STREQ("bytes=1-10", val);
  1869. }
  1870. {
  1871. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1873. EXPECT_STREQ("bytes=1-10, 100-", val);
  1874. }
  1875. {
  1876. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1878. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1879. }
  1880. {
  1881. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1882. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1883. EXPECT_STREQ("bytes=0-0, -1", val);
  1884. }
  1885. }
  1886. TEST(BearerTokenAuthTest, SchemeValidation) {
  1887. // A value shorter than "Bearer " must not throw from the fixed-length
  1888. // substr, and a non-Bearer scheme must not be reported as a token.
  1889. struct {
  1890. const char *value;
  1891. const char *expected;
  1892. } cases[] = {
  1893. {"x", ""},
  1894. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1895. {"Bearer abc123", "abc123"},
  1896. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1897. };
  1898. for (const auto &c : cases) {
  1899. Request req;
  1900. req.set_header("Authorization", c.value);
  1901. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1902. }
  1903. }
  1904. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1905. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1906. // to depend on the standard library (libstdc++ handed back duplicates in
  1907. // reverse insertion order, libc++ in insertion order).
  1908. Request req;
  1909. req.set_header("Accept-Encoding", "gzip");
  1910. req.set_header("Accept-Encoding", "deflate");
  1911. req.set_header("Accept-Encoding", "br");
  1912. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1913. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1914. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1915. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1916. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1917. }
  1918. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1919. Request req;
  1920. req.set_header("X-Test", "only");
  1921. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1922. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1923. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1924. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1925. }
  1926. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1927. Request req;
  1928. req.set_header("X-First", "1");
  1929. req.set_header("X-Test", "2");
  1930. req.params.emplace("first", "1");
  1931. req.params.emplace("test", "2");
  1932. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1933. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1934. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1935. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1936. // The second one is negative when read as a signed value
  1937. const auto max_id = (std::numeric_limits<size_t>::max)();
  1938. for (auto id : {max_id / 2, max_id}) {
  1939. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1940. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1941. EXPECT_EQ("", req.get_param_value("test", id));
  1942. EXPECT_EQ("", req.form.get_field("test", id));
  1943. EXPECT_EQ("", req.form.get_file("test", id).content);
  1944. }
  1945. }
  1946. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1947. Headers headers;
  1948. headers.emplace("Host", "example.com");
  1949. headers.emplace("Accept-Encoding", "gzip");
  1950. headers.emplace("User-Agent", "test");
  1951. headers.emplace("Accept-Encoding", "deflate");
  1952. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1953. "Accept-Encoding=deflate ",
  1954. entries_to_string(headers));
  1955. }
  1956. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1957. Headers headers = {{"Content-Type", "text/html"},
  1958. {"CONTENT-TYPE", "text/xml"}};
  1959. EXPECT_EQ(2U, headers.count("content-type"));
  1960. auto it = headers.find("content-type");
  1961. ASSERT_TRUE(it != headers.end());
  1962. EXPECT_EQ("text/html", it->second);
  1963. }
  1964. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1965. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1966. // drop only those fields and leave everything positioned between them.
  1967. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1968. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1969. auto rng = headers.equal_range("a");
  1970. headers.erase(rng.first, rng.second);
  1971. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1972. }
  1973. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1974. Headers headers = {
  1975. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1976. EXPECT_EQ(3U, headers.erase("A"));
  1977. EXPECT_EQ(0U, headers.count("A"));
  1978. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1979. }
  1980. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1981. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1982. headers.emplace_front("Host", "example.com");
  1983. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1984. entries_to_string(headers));
  1985. }
  1986. TEST(ParseHeaderValueTest, Range) {
  1987. {
  1988. Ranges ranges;
  1989. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1990. EXPECT_TRUE(ret);
  1991. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1992. }
  1993. {
  1994. Ranges ranges;
  1995. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1996. EXPECT_TRUE(ret);
  1997. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1998. }
  1999. {
  2000. Ranges ranges;
  2001. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2002. EXPECT_TRUE(ret);
  2003. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2004. }
  2005. {
  2006. Ranges ranges;
  2007. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2008. EXPECT_FALSE(ret);
  2009. }
  2010. {
  2011. Ranges ranges;
  2012. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2013. EXPECT_TRUE(ret);
  2014. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2015. }
  2016. {
  2017. Ranges ranges;
  2018. auto ret =
  2019. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2020. EXPECT_TRUE(ret);
  2021. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2022. }
  2023. {
  2024. Ranges ranges;
  2025. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2026. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2027. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2028. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2029. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2030. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2031. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2032. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2033. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2034. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2035. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2036. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2037. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2038. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2039. EXPECT_FALSE(
  2040. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2041. EXPECT_TRUE(ranges.empty());
  2042. }
  2043. {
  2044. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2045. // remainder of the representation, so it stays accepted.
  2046. Ranges ranges;
  2047. auto ret =
  2048. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2049. EXPECT_TRUE(ret);
  2050. ASSERT_EQ(1u, ranges.size());
  2051. EXPECT_EQ(0, ranges[0].first);
  2052. EXPECT_EQ(-1, ranges[0].second);
  2053. }
  2054. // RFC 9110 14.1: range unit names are case-insensitive.
  2055. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2056. Ranges ranges;
  2057. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2058. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2059. }
  2060. }
  2061. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2062. Request req;
  2063. req.set_header("Accept-Encoding", "gzip");
  2064. Response res;
  2065. res.set_header("Content-Type", "text/plain");
  2066. auto ret = detail::encoding_type(req, res);
  2067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2074. Request req;
  2075. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2076. Response res;
  2077. res.set_header("Content-Type", "text/plain");
  2078. auto ret = detail::encoding_type(req, res);
  2079. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2081. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2082. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2083. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2084. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2085. #else
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. #endif
  2088. }
  2089. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding",
  2092. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2093. Response res;
  2094. res.set_header("Content-Type", "text/plain");
  2095. auto ret = detail::encoding_type(req, res);
  2096. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2098. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2100. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2102. #else
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. #endif
  2105. }
  2106. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2107. // All supported encodings rejected with q=0 should return None
  2108. Request req;
  2109. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2110. Response res;
  2111. res.set_header("Content-Type", "text/plain");
  2112. auto ret = detail::encoding_type(req, res);
  2113. EXPECT_TRUE(ret == detail::EncodingType::None);
  2114. }
  2115. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2116. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2117. Request req;
  2118. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2119. Response res;
  2120. res.set_header("Content-Type", "text/plain");
  2121. auto ret = detail::encoding_type(req, res);
  2122. EXPECT_TRUE(ret == detail::EncodingType::None);
  2123. }
  2124. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2125. Request req;
  2126. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2127. Response res;
  2128. res.set_header("Content-Type", "text/plain");
  2129. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2130. }
  2131. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2132. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2133. Request req;
  2134. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2135. Response res;
  2136. res.set_header("Content-Type", "text/plain");
  2137. auto ret = detail::encoding_type(req, res);
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. }
  2140. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2141. // RFC 7231: Accept-Encoding values are case-insensitive
  2142. Request req;
  2143. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2144. Response res;
  2145. res.set_header("Content-Type", "text/plain");
  2146. auto ret = detail::encoding_type(req, res);
  2147. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2149. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2151. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2152. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2153. #else
  2154. EXPECT_TRUE(ret == detail::EncodingType::None);
  2155. #endif
  2156. }
  2157. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2158. // q value should determine priority, not hardcoded order
  2159. Request req;
  2160. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2161. Response res;
  2162. res.set_header("Content-Type", "text/plain");
  2163. auto ret = detail::encoding_type(req, res);
  2164. // gzip has highest q=1.0, so it should be selected even though
  2165. // br and zstd are also supported
  2166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2168. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2169. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2170. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2171. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2172. #else
  2173. EXPECT_TRUE(ret == detail::EncodingType::None);
  2174. #endif
  2175. }
  2176. TEST(BufferStreamTest, read) {
  2177. detail::BufferStream strm1;
  2178. Stream &strm = strm1;
  2179. EXPECT_EQ(5, strm.write("hello"));
  2180. char buf[512];
  2181. EXPECT_EQ(2, strm.read(buf, 2));
  2182. EXPECT_EQ('h', buf[0]);
  2183. EXPECT_EQ('e', buf[1]);
  2184. EXPECT_EQ(2, strm.read(buf, 2));
  2185. EXPECT_EQ('l', buf[0]);
  2186. EXPECT_EQ('l', buf[1]);
  2187. EXPECT_EQ(1, strm.read(buf, 1));
  2188. EXPECT_EQ('o', buf[0]);
  2189. EXPECT_EQ(0, strm.read(buf, 1));
  2190. }
  2191. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2192. auto host = "www.httpwatch.com";
  2193. auto ip = hosted_at(host);
  2194. EXPECT_EQ("23.96.13.243", ip);
  2195. std::vector<std::string> addrs;
  2196. hosted_at(host, addrs);
  2197. EXPECT_EQ(1u, addrs.size());
  2198. }
  2199. #if 0 // It depends on each test environment...
  2200. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2201. auto host = "www.youtube.com";
  2202. std::vector<std::string> addrs;
  2203. hosted_at(host, addrs);
  2204. EXPECT_EQ(20u, addrs.size());
  2205. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2206. EXPECT_TRUE(it != addrs.end());
  2207. }
  2208. #endif
  2209. class ChunkedEncodingTest : public ::testing::Test {
  2210. protected:
  2211. ChunkedEncodingTest()
  2212. : cli_(HOST, PORT)
  2213. #ifdef CPPHTTPLIB_SSL_ENABLED
  2214. ,
  2215. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2216. #endif
  2217. {
  2218. cli_.set_connection_timeout(2);
  2219. #ifdef CPPHTTPLIB_SSL_ENABLED
  2220. cli_.enable_server_certificate_verification(false);
  2221. #endif
  2222. }
  2223. virtual void SetUp() {
  2224. read_file("./image.jpg", image_data_);
  2225. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2226. res.set_content("Hello World!", "text/plain");
  2227. });
  2228. svr_.Get(
  2229. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2230. res.set_chunked_content_provider(
  2231. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2232. size_t remaining = image_data_.size() - offset;
  2233. if (remaining == 0) {
  2234. sink.done();
  2235. } else {
  2236. constexpr size_t CHUNK_SIZE = 1024;
  2237. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2238. sink.write(&image_data_[offset], send_size);
  2239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2240. }
  2241. return true;
  2242. });
  2243. });
  2244. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2245. svr_.wait_until_ready();
  2246. }
  2247. virtual void TearDown() {
  2248. svr_.stop();
  2249. if (!request_threads_.empty()) {
  2250. std::this_thread::sleep_for(std::chrono::seconds(1));
  2251. for (auto &t : request_threads_) {
  2252. t.join();
  2253. }
  2254. }
  2255. t_.join();
  2256. }
  2257. #ifdef CPPHTTPLIB_SSL_ENABLED
  2258. SSLClient cli_;
  2259. SSLServer svr_;
  2260. #else
  2261. Client cli_;
  2262. Server svr_;
  2263. #endif
  2264. thread t_;
  2265. std::vector<thread> request_threads_;
  2266. std::string image_data_;
  2267. };
  2268. TEST_F(ChunkedEncodingTest, NormalGet) {
  2269. auto res = cli_.Get("/chunked");
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. std::string out;
  2272. read_file("./image.jpg", out);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. EXPECT_EQ(out, res->body);
  2275. }
  2276. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2277. std::string body;
  2278. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2279. body.append(data, data_length);
  2280. return true;
  2281. });
  2282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2283. std::string out;
  2284. read_file("./image.jpg", out);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. EXPECT_EQ(out, body);
  2287. }
  2288. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2289. std::string body;
  2290. auto res = cli_.Get(
  2291. "/chunked",
  2292. [&](const Response &response) {
  2293. EXPECT_EQ(StatusCode::OK_200, response.status);
  2294. return true;
  2295. },
  2296. [&](const char *data, size_t data_length) {
  2297. body.append(data, data_length);
  2298. return true;
  2299. });
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. std::string out;
  2302. read_file("./image.jpg", out);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ(out, body);
  2305. }
  2306. TEST(RangeTest, FromHTTPBin_Online) {
  2307. auto host = "httpbingo.org";
  2308. auto path = std::string{"/range/32"};
  2309. #ifdef CPPHTTPLIB_SSL_ENABLED
  2310. auto port = 443;
  2311. SSLClient cli(host, port);
  2312. #else
  2313. auto port = 80;
  2314. Client cli(host, port);
  2315. #endif
  2316. cli.set_connection_timeout(5);
  2317. {
  2318. auto res = cli.Get(path);
  2319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2320. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2321. EXPECT_EQ(StatusCode::OK_200, res->status);
  2322. }
  2323. {
  2324. Headers headers = {make_range_header({{1, -1}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2329. }
  2330. {
  2331. Headers headers = {make_range_header({{1, 10}})};
  2332. auto res = cli.Get(path, headers);
  2333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2334. EXPECT_EQ("bcdefghijk", res->body);
  2335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2336. }
  2337. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2338. // entire resource, while the original httpbin returned 200. Both are
  2339. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2340. {
  2341. Headers headers = {make_range_header({{0, 31}})};
  2342. auto res = cli.Get(path, headers);
  2343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2344. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2345. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2346. res->status == StatusCode::PartialContent_206);
  2347. }
  2348. {
  2349. Headers headers = {make_range_header({{0, -1}})};
  2350. auto res = cli.Get(path, headers);
  2351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2352. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2353. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2354. res->status == StatusCode::PartialContent_206);
  2355. }
  2356. // go-httpbin returns 206 with clamped range for over-range requests,
  2357. // while the original httpbin returned 416. Both behaviors are observed
  2358. // in real servers, so we only verify the request succeeds.
  2359. {
  2360. Headers headers = {make_range_header({{0, 32}})};
  2361. auto res = cli.Get(path, headers);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. }
  2364. }
  2365. TEST(RangeTest, IgnoredForPost) {
  2366. Server svr;
  2367. svr.Post("/", [](const Request &, Response &res) {
  2368. res.set_content("abcdefg", "text/plain");
  2369. });
  2370. auto port = svr.bind_to_any_port(HOST);
  2371. ASSERT_GT(port, 0);
  2372. thread t = thread([&] { svr.listen_after_bind(); });
  2373. auto se = detail::scope_exit([&] {
  2374. svr.stop();
  2375. t.join();
  2376. ASSERT_FALSE(svr.is_running());
  2377. });
  2378. svr.wait_until_ready();
  2379. Client cli(HOST, port);
  2380. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2381. auto res = cli.Post("/", Headers{{"Range", range}});
  2382. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2383. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2384. EXPECT_EQ("abcdefg", res->body) << range;
  2385. }
  2386. }
  2387. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2388. auto host = "unresolvableaddress.local";
  2389. auto path = std::string{"/"};
  2390. #ifdef CPPHTTPLIB_SSL_ENABLED
  2391. auto port = 443;
  2392. SSLClient cli(host, port);
  2393. #else
  2394. auto port = 80;
  2395. Client cli(host, port);
  2396. #endif
  2397. cli.set_connection_timeout(1);
  2398. {
  2399. auto res = cli.Get(path);
  2400. ASSERT_FALSE(res);
  2401. }
  2402. std::this_thread::sleep_for(std::chrono::seconds(8));
  2403. }
  2404. #if defined(__linux__) && defined(__GLIBC__) && \
  2405. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2406. // Forward declaration: in split builds split.py strips `inline` and moves the
  2407. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2408. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2409. // against the symbol in both header-only and split builds.
  2410. namespace httplib {
  2411. namespace detail {
  2412. int getaddrinfo_with_timeout(const char *node, const char *service,
  2413. const struct addrinfo *hints,
  2414. struct addrinfo **res, time_t timeout_sec);
  2415. } // namespace detail
  2416. } // namespace httplib
  2417. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2418. //
  2419. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2420. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2421. // gai_suspend() call hits the connection timeout the function calls
  2422. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2423. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2424. // still alive and still references the now-destroyed stack frame.
  2425. //
  2426. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2427. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2428. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2429. // and runs them in a container.
  2430. namespace {
  2431. bool should_run_issue_2431_tests() {
  2432. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2433. return v && *v && std::string(v) != "0";
  2434. }
  2435. std::string unique_unresolvable_host(int n) {
  2436. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2437. // glibc still asks the configured nameserver — which is exactly the path
  2438. // we want to exercise. A unique label per call avoids the resolver cache.
  2439. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2440. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2441. std::to_string(n) + ".invalid";
  2442. }
  2443. } // namespace
  2444. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2445. if (!should_run_issue_2431_tests()) {
  2446. GTEST_SKIP()
  2447. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2448. }
  2449. for (int i = 0; i < 8; ++i) {
  2450. struct addrinfo hints;
  2451. memset(&hints, 0, sizeof(hints));
  2452. hints.ai_family = AF_UNSPEC;
  2453. hints.ai_socktype = SOCK_STREAM;
  2454. auto host = unique_unresolvable_host(i);
  2455. struct addrinfo *result = nullptr;
  2456. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2457. &result, /*timeout_sec=*/1);
  2458. if (rc == 0 && result) { freeaddrinfo(result); }
  2459. }
  2460. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2461. // stack region they still believe holds their gaicb.
  2462. std::this_thread::sleep_for(std::chrono::seconds(3));
  2463. }
  2464. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2465. if (!should_run_issue_2431_tests()) {
  2466. GTEST_SKIP()
  2467. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2468. }
  2469. std::atomic<bool> stop{false};
  2470. std::vector<std::thread> threads;
  2471. for (int t = 0; t < 8; ++t) {
  2472. threads.emplace_back([t, &stop] {
  2473. int i = 0;
  2474. while (!stop.load(std::memory_order_relaxed)) {
  2475. struct addrinfo hints;
  2476. memset(&hints, 0, sizeof(hints));
  2477. hints.ai_family = AF_UNSPEC;
  2478. hints.ai_socktype = SOCK_STREAM;
  2479. auto host = unique_unresolvable_host(t * 100000 + i++);
  2480. struct addrinfo *result = nullptr;
  2481. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2482. &result, /*timeout_sec=*/1);
  2483. if (rc == 0 && result) { freeaddrinfo(result); }
  2484. }
  2485. });
  2486. }
  2487. std::this_thread::sleep_for(std::chrono::seconds(8));
  2488. stop.store(true, std::memory_order_relaxed);
  2489. for (auto &th : threads) {
  2490. th.join();
  2491. }
  2492. std::this_thread::sleep_for(std::chrono::seconds(3));
  2493. }
  2494. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2495. if (!should_run_issue_2431_tests()) {
  2496. GTEST_SKIP()
  2497. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2498. }
  2499. std::atomic<bool> stop{false};
  2500. std::vector<std::thread> threads;
  2501. for (int t = 0; t < 8; ++t) {
  2502. threads.emplace_back([t, &stop] {
  2503. int i = 0;
  2504. while (!stop.load(std::memory_order_relaxed)) {
  2505. auto host = unique_unresolvable_host(t * 100000 + i++);
  2506. Client cli(host, 80);
  2507. cli.set_connection_timeout(1, 0);
  2508. cli.set_read_timeout(1, 0);
  2509. cli.set_write_timeout(1, 0);
  2510. (void)cli.Get("/");
  2511. }
  2512. });
  2513. }
  2514. std::this_thread::sleep_for(std::chrono::seconds(8));
  2515. stop.store(true, std::memory_order_relaxed);
  2516. for (auto &th : threads) {
  2517. th.join();
  2518. }
  2519. std::this_thread::sleep_for(std::chrono::seconds(3));
  2520. }
  2521. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2522. TEST(ConnectionErrorTest, InvalidHost) {
  2523. auto host = "-abcde.com";
  2524. #ifdef CPPHTTPLIB_SSL_ENABLED
  2525. auto port = 443;
  2526. SSLClient cli(host, port);
  2527. #else
  2528. auto port = 80;
  2529. Client cli(host, port);
  2530. #endif
  2531. cli.set_connection_timeout(std::chrono::seconds(2));
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::Connection, res.error());
  2535. }
  2536. TEST(ConnectionErrorTest, InvalidHost2) {
  2537. auto host = "httpcan.org/";
  2538. #ifdef CPPHTTPLIB_SSL_ENABLED
  2539. SSLClient cli(host);
  2540. #else
  2541. Client cli(host);
  2542. #endif
  2543. cli.set_connection_timeout(std::chrono::seconds(2));
  2544. auto res = cli.Get("/");
  2545. ASSERT_TRUE(!res);
  2546. EXPECT_EQ(Error::Connection, res.error());
  2547. }
  2548. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2549. auto host = "httpcan.org/";
  2550. #ifdef CPPHTTPLIB_SSL_ENABLED
  2551. SSLClient cli(host);
  2552. #else
  2553. Client cli(host);
  2554. #endif
  2555. cli.set_connection_timeout(std::chrono::seconds(2));
  2556. auto res = cli.Get("/");
  2557. ASSERT_TRUE(!res);
  2558. stringstream s;
  2559. s << "error code: " << res.error();
  2560. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2561. }
  2562. TEST(ConnectionErrorTest, InvalidPort) {
  2563. auto host = "localhost";
  2564. auto port = 44380;
  2565. #ifdef CPPHTTPLIB_SSL_ENABLED
  2566. SSLClient cli(host, port);
  2567. #else
  2568. Client cli(host, port);
  2569. #endif
  2570. cli.set_connection_timeout(std::chrono::seconds(2));
  2571. auto res = cli.Get("/");
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_TRUE(Error::Connection == res.error() ||
  2574. Error::ConnectionTimeout == res.error());
  2575. }
  2576. TEST(ConnectionErrorTest, Timeout_Online) {
  2577. auto host = "google.com";
  2578. #ifdef CPPHTTPLIB_SSL_ENABLED
  2579. auto port = 44380;
  2580. SSLClient cli(host, port);
  2581. #else
  2582. auto port = 8080;
  2583. Client cli(host, port);
  2584. #endif
  2585. cli.set_connection_timeout(std::chrono::seconds(2));
  2586. // only probe one address type so that the error reason
  2587. // correlates to the timed-out IPv4, not the unsupported
  2588. // IPv6 connection attempt
  2589. cli.set_address_family(AF_INET);
  2590. auto res = cli.Get("/");
  2591. ASSERT_TRUE(!res);
  2592. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2593. }
  2594. TEST(CancelTest, NoCancel_Online) {
  2595. auto host = "httpbingo.org";
  2596. auto path = std::string{"/range/32"};
  2597. #ifdef CPPHTTPLIB_SSL_ENABLED
  2598. auto port = 443;
  2599. SSLClient cli(host, port);
  2600. #else
  2601. auto port = 80;
  2602. Client cli(host, port);
  2603. #endif
  2604. cli.set_connection_timeout(std::chrono::seconds(5));
  2605. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. }
  2610. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2611. // Use /bytes with a large payload so that the DownloadProgress callback
  2612. // (which only fires for Content-Length responses) is invoked before the
  2613. // entire body is received, giving cancellation a chance to fire.
  2614. auto host = "httpbingo.org";
  2615. auto path = std::string{"/bytes/524288"};
  2616. #ifdef CPPHTTPLIB_SSL_ENABLED
  2617. auto port = 443;
  2618. SSLClient cli(host, port);
  2619. #else
  2620. auto port = 80;
  2621. Client cli(host, port);
  2622. #endif
  2623. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayload_Online) {
  2629. auto host = "httpbingo.org";
  2630. auto path = std::string{"/bytes/524288"};
  2631. #ifdef CPPHTTPLIB_SSL_ENABLED
  2632. auto port = 443;
  2633. SSLClient cli(host, port);
  2634. #else
  2635. auto port = 80;
  2636. Client cli(host, port);
  2637. #endif
  2638. cli.set_connection_timeout(std::chrono::seconds(5));
  2639. uint32_t count = 0;
  2640. auto res =
  2641. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2642. ASSERT_TRUE(!res);
  2643. EXPECT_EQ(Error::Canceled, res.error());
  2644. }
  2645. TEST(CancelTest, NoCancelPost) {
  2646. Server svr;
  2647. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2648. res.set_content("Hello World!", "text/plain");
  2649. });
  2650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2651. auto se = detail::scope_exit([&] {
  2652. svr.stop();
  2653. thread.join();
  2654. ASSERT_FALSE(svr.is_running());
  2655. });
  2656. svr.wait_until_ready();
  2657. Client cli(HOST, PORT);
  2658. cli.set_connection_timeout(std::chrono::seconds(5));
  2659. auto res =
  2660. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2661. "application/json", [](uint64_t, uint64_t) { return true; });
  2662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2663. EXPECT_EQ("Hello World!", res->body);
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. }
  2666. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2667. Server svr;
  2668. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2669. res.set_content("Hello World!", "text/plain");
  2670. });
  2671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2672. auto se = detail::scope_exit([&] {
  2673. svr.stop();
  2674. thread.join();
  2675. ASSERT_FALSE(svr.is_running());
  2676. });
  2677. svr.wait_until_ready();
  2678. Client cli(HOST, PORT);
  2679. cli.set_connection_timeout(std::chrono::seconds(5));
  2680. auto res =
  2681. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2682. "application/json", [](uint64_t, uint64_t) { return false; });
  2683. ASSERT_TRUE(!res);
  2684. EXPECT_EQ(Error::Canceled, res.error());
  2685. }
  2686. TEST(CancelTest, WithCancelLargePayloadPost) {
  2687. Server svr;
  2688. svr.set_payload_max_length(200 * 1024 * 1024);
  2689. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2690. res.set_content(LARGE_DATA, "text/plain");
  2691. });
  2692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. thread.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, PORT);
  2700. cli.set_payload_max_length(200 * 1024 * 1024);
  2701. cli.set_connection_timeout(std::chrono::seconds(5));
  2702. auto res =
  2703. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2704. "application/json", [](uint64_t, uint64_t) { return false; });
  2705. ASSERT_TRUE(!res);
  2706. EXPECT_EQ(Error::Canceled, res.error());
  2707. }
  2708. TEST(CancelTest, NoCancelPut) {
  2709. Server svr;
  2710. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2711. res.set_content("Hello World!", "text/plain");
  2712. });
  2713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2714. auto se = detail::scope_exit([&] {
  2715. svr.stop();
  2716. thread.join();
  2717. ASSERT_FALSE(svr.is_running());
  2718. });
  2719. svr.wait_until_ready();
  2720. Client cli(HOST, PORT);
  2721. cli.set_connection_timeout(std::chrono::seconds(5));
  2722. auto res =
  2723. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2724. "application/json", [](uint64_t, uint64_t) { return true; });
  2725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2726. EXPECT_EQ("Hello World!", res->body);
  2727. EXPECT_EQ(StatusCode::OK_200, res->status);
  2728. }
  2729. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2730. Server svr;
  2731. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2732. res.set_content("Hello World!", "text/plain");
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. Client cli(HOST, PORT);
  2742. cli.set_connection_timeout(std::chrono::seconds(5));
  2743. auto res =
  2744. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2745. "application/json", [](uint64_t, uint64_t) { return false; });
  2746. ASSERT_TRUE(!res);
  2747. EXPECT_EQ(Error::Canceled, res.error());
  2748. }
  2749. TEST(CancelTest, WithCancelLargePayloadPut) {
  2750. Server svr;
  2751. svr.set_payload_max_length(200 * 1024 * 1024);
  2752. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2753. res.set_content(LARGE_DATA, "text/plain");
  2754. });
  2755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli(HOST, PORT);
  2763. cli.set_payload_max_length(200 * 1024 * 1024);
  2764. cli.set_connection_timeout(std::chrono::seconds(5));
  2765. auto res =
  2766. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2767. "application/json", [](uint64_t, uint64_t) { return false; });
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. TEST(CancelTest, NoCancelPatch) {
  2772. Server svr;
  2773. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2777. auto se = detail::scope_exit([&] {
  2778. svr.stop();
  2779. thread.join();
  2780. ASSERT_FALSE(svr.is_running());
  2781. });
  2782. svr.wait_until_ready();
  2783. Client cli(HOST, PORT);
  2784. cli.set_connection_timeout(std::chrono::seconds(5));
  2785. auto res =
  2786. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2787. "application/json", [](uint64_t, uint64_t) { return true; });
  2788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2789. EXPECT_EQ("Hello World!", res->body);
  2790. EXPECT_EQ(StatusCode::OK_200, res->status);
  2791. }
  2792. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2793. Server svr;
  2794. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2795. res.set_content("Hello World!", "text/plain");
  2796. });
  2797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(HOST, PORT);
  2805. cli.set_connection_timeout(std::chrono::seconds(5));
  2806. auto res =
  2807. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2808. "application/json", [](uint64_t, uint64_t) { return false; });
  2809. ASSERT_TRUE(!res);
  2810. EXPECT_EQ(Error::Canceled, res.error());
  2811. }
  2812. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2813. Server svr;
  2814. svr.set_payload_max_length(200 * 1024 * 1024);
  2815. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2816. res.set_content(LARGE_DATA, "text/plain");
  2817. });
  2818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2819. auto se = detail::scope_exit([&] {
  2820. svr.stop();
  2821. thread.join();
  2822. ASSERT_FALSE(svr.is_running());
  2823. });
  2824. svr.wait_until_ready();
  2825. Client cli(HOST, PORT);
  2826. cli.set_payload_max_length(200 * 1024 * 1024);
  2827. cli.set_connection_timeout(std::chrono::seconds(5));
  2828. auto res =
  2829. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2830. "application/json", [](uint64_t, uint64_t) { return false; });
  2831. ASSERT_TRUE(!res);
  2832. EXPECT_EQ(Error::Canceled, res.error());
  2833. }
  2834. TEST(CancelTest, NoCancelDelete) {
  2835. Server svr;
  2836. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2837. res.set_content("Hello World!", "text/plain");
  2838. });
  2839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2840. auto se = detail::scope_exit([&] {
  2841. svr.stop();
  2842. thread.join();
  2843. ASSERT_FALSE(svr.is_running());
  2844. });
  2845. svr.wait_until_ready();
  2846. Client cli(HOST, PORT);
  2847. cli.set_connection_timeout(std::chrono::seconds(5));
  2848. auto res =
  2849. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2850. "application/json", [](uint64_t, uint64_t) { return true; });
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. EXPECT_EQ("Hello World!", res->body);
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2856. Server svr;
  2857. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2858. res.set_content("Hello World!", "text/plain");
  2859. });
  2860. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2861. auto se = detail::scope_exit([&] {
  2862. svr.stop();
  2863. thread.join();
  2864. ASSERT_FALSE(svr.is_running());
  2865. });
  2866. svr.wait_until_ready();
  2867. Client cli(HOST, PORT);
  2868. cli.set_connection_timeout(std::chrono::seconds(5));
  2869. auto res =
  2870. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2871. "application/json", [](uint64_t, uint64_t) { return false; });
  2872. ASSERT_TRUE(!res);
  2873. EXPECT_EQ(Error::Canceled, res.error());
  2874. }
  2875. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2876. Server svr;
  2877. svr.set_payload_max_length(200 * 1024 * 1024);
  2878. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2879. res.set_content(LARGE_DATA, "text/plain");
  2880. });
  2881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. thread.join();
  2885. ASSERT_FALSE(svr.is_running());
  2886. });
  2887. svr.wait_until_ready();
  2888. Client cli(HOST, PORT);
  2889. cli.set_payload_max_length(200 * 1024 * 1024);
  2890. cli.set_connection_timeout(std::chrono::seconds(5));
  2891. auto res =
  2892. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2893. "application/json", [](uint64_t, uint64_t) { return false; });
  2894. ASSERT_TRUE(!res);
  2895. EXPECT_EQ(Error::Canceled, res.error());
  2896. }
  2897. static std::string remove_whitespace(const std::string &input) {
  2898. std::string output;
  2899. output.reserve(input.size());
  2900. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2901. [](unsigned char c) { return !std::isspace(c); });
  2902. return output;
  2903. }
  2904. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2905. auto host = "httpbingo.org";
  2906. auto path = std::string{"/basic-auth/hello/world"};
  2907. #ifdef CPPHTTPLIB_SSL_ENABLED
  2908. auto port = 443;
  2909. SSLClient cli(host, port);
  2910. #else
  2911. auto port = 80;
  2912. Client cli(host, port);
  2913. #endif
  2914. {
  2915. auto res = cli.Get(path);
  2916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2917. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2918. }
  2919. {
  2920. auto res = cli.Get(
  2921. path, Headers{make_basic_authentication_header("hello", "world")});
  2922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2923. auto body = remove_whitespace(res->body);
  2924. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2925. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2926. EXPECT_EQ(StatusCode::OK_200, res->status);
  2927. }
  2928. {
  2929. cli.set_basic_auth("hello", "world");
  2930. auto res = cli.Get(path);
  2931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2932. auto body = remove_whitespace(res->body);
  2933. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2934. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2935. EXPECT_EQ(StatusCode::OK_200, res->status);
  2936. }
  2937. {
  2938. cli.set_basic_auth("hello", "bad");
  2939. auto res = cli.Get(path);
  2940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2941. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2942. }
  2943. {
  2944. cli.set_basic_auth("bad", "world");
  2945. auto res = cli.Get(path);
  2946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2947. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2948. }
  2949. }
  2950. #ifdef CPPHTTPLIB_SSL_ENABLED
  2951. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2952. auto host = "httpbingo.org";
  2953. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2954. auto paths = std::vector<std::string>{
  2955. "/digest-auth/auth/hello/world/MD5",
  2956. "/digest-auth/auth/hello/world/SHA-256",
  2957. };
  2958. auto port = 443;
  2959. SSLClient cli(host, port);
  2960. {
  2961. auto res = cli.Get(unauth_path);
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2964. }
  2965. {
  2966. cli.set_digest_auth("hello", "world");
  2967. for (const auto &path : paths) {
  2968. auto res = cli.Get(path.c_str());
  2969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2970. auto body = remove_whitespace(res->body);
  2971. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2972. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2973. EXPECT_EQ(StatusCode::OK_200, res->status);
  2974. }
  2975. cli.set_digest_auth("hello", "bad");
  2976. for (const auto &path : paths) {
  2977. auto res = cli.Get(path.c_str());
  2978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2979. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2980. }
  2981. }
  2982. }
  2983. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2984. // comma-separated list of challenges, and each challenge may itself carry a
  2985. // comma-separated auth-param list, so a server can legally offer Basic
  2986. // before Digest, either as two field lines or packed into one. Runs one 401
  2987. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2988. // value() joins them in receipt order) and checks that the retry carries a
  2989. // well-formed Digest Authorization header naming expected_realm.
  2990. static void
  2991. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2992. const std::string &expected_realm) {
  2993. std::atomic<int> hits{0};
  2994. Server svr;
  2995. svr.Get("/x", [&](const Request &req, Response &res) {
  2996. if (++hits == 1) {
  2997. res.status = StatusCode::Unauthorized_401;
  2998. for (const auto &challenge : challenges) {
  2999. res.set_header("WWW-Authenticate", challenge);
  3000. }
  3001. } else {
  3002. auto authorization = req.get_header_value("Authorization");
  3003. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3004. EXPECT_NE(std::string::npos,
  3005. authorization.find("realm=\"" + expected_realm + "\""));
  3006. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3007. res.set_content("ok", "text/plain");
  3008. }
  3009. });
  3010. auto port = svr.bind_to_any_port(HOST);
  3011. std::thread t([&]() { svr.listen_after_bind(); });
  3012. auto se = detail::scope_exit([&] {
  3013. svr.stop();
  3014. t.join();
  3015. });
  3016. svr.wait_until_ready();
  3017. Client cli(HOST, port);
  3018. cli.set_digest_auth("hello", "world");
  3019. auto res = cli.Get("/x");
  3020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3021. EXPECT_EQ(2, hits.load());
  3022. }
  3023. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3024. static const char *kDigestChallenge =
  3025. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3026. "algorithm=MD5";
  3027. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3028. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3029. "testrealm");
  3030. }
  3031. // Same challenge list with the schemes in the opposite order, to make sure
  3032. // the fix above didn't just special-case "Basic first".
  3033. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3034. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3035. "testrealm");
  3036. }
  3037. // A comma inside a quoted auth-param value must not be mistaken for the
  3038. // separator between two challenges (or two auth-params).
  3039. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3040. run_digest_challenge_list_test(
  3041. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3042. "algorithm=MD5"},
  3043. "test,realm");
  3044. }
  3045. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3046. // the params and leaves out the fragment.
  3047. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3048. Server svr;
  3049. std::string uri, target;
  3050. svr.Get("/a b", [&](const Request &req, Response &res) {
  3051. auto auth = req.get_header_value("Authorization");
  3052. if (auth.empty()) {
  3053. res.status = StatusCode::Unauthorized_401;
  3054. res.set_header("WWW-Authenticate",
  3055. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3056. return;
  3057. }
  3058. auto b = auth.find("uri=\"") + 5;
  3059. uri = auth.substr(b, auth.find('"', b) - b);
  3060. target = req.target;
  3061. });
  3062. auto port = svr.bind_to_any_port(HOST);
  3063. std::thread t([&]() { svr.listen_after_bind(); });
  3064. auto se = detail::scope_exit([&] {
  3065. svr.stop();
  3066. t.join();
  3067. });
  3068. svr.wait_until_ready();
  3069. Client cli(HOST, port);
  3070. cli.set_digest_auth("hello", "world");
  3071. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3073. EXPECT_EQ("/a%20b?x=1", target);
  3074. EXPECT_EQ(target, uri);
  3075. }
  3076. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3077. // make_digest_authentication_header() dereferences both unconditionally, so
  3078. // a server sending a challenge missing either one must not be treated as
  3079. // usable -- doing so used to crash the client with std::out_of_range.
  3080. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3081. Server svr;
  3082. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3083. res.status = StatusCode::Unauthorized_401;
  3084. res.set_header("WWW-Authenticate", challenge);
  3085. });
  3086. auto port = svr.bind_to_any_port(HOST);
  3087. std::thread t([&]() { svr.listen_after_bind(); });
  3088. auto se = detail::scope_exit([&] {
  3089. svr.stop();
  3090. t.join();
  3091. });
  3092. svr.wait_until_ready();
  3093. Client cli(HOST, port);
  3094. cli.set_digest_auth("hello", "world");
  3095. auto res = cli.Get("/x");
  3096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3097. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3098. }
  3099. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3100. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3101. }
  3102. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3103. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3104. }
  3105. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3106. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3107. }
  3108. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3109. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3110. // when storing the values, so the header builder has to re-escape them (and
  3111. // keep algorithm a bare token); otherwise the value breaks out of its
  3112. // quoted-string and injects extra auth-params into the client's Authorization.
  3113. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3114. std::atomic<int> hits{0};
  3115. std::string authorization;
  3116. Server svr;
  3117. svr.Get("/x", [&](const Request &req, Response &res) {
  3118. if (++hits == 1) {
  3119. res.status = StatusCode::Unauthorized_401;
  3120. // On the wire the quotes embedded in the values are backslash-escaped.
  3121. res.set_header("WWW-Authenticate",
  3122. "Digest realm=\"testrealm\", "
  3123. "nonce=\"n\\\"; injected=\\\"x\", "
  3124. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3125. } else {
  3126. authorization = req.get_header_value("Authorization");
  3127. res.set_content("ok", "text/plain");
  3128. }
  3129. });
  3130. auto port = svr.bind_to_any_port(HOST);
  3131. std::thread t([&]() { svr.listen_after_bind(); });
  3132. auto se = detail::scope_exit([&] {
  3133. svr.stop();
  3134. t.join();
  3135. });
  3136. svr.wait_until_ready();
  3137. Client cli(HOST, port);
  3138. cli.set_digest_auth("hello", "world");
  3139. auto res = cli.Get("/x");
  3140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3141. EXPECT_EQ(2, hits.load());
  3142. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3143. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3144. // inside its quoted-string rather than starting an "injected" auth-param.
  3145. EXPECT_NE(std::string::npos,
  3146. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3147. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3148. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3149. }
  3150. #endif
  3151. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3152. auto host = "google.com";
  3153. auto another_host = "example.com";
  3154. auto wrong_ip = "0.0.0.0";
  3155. #ifdef CPPHTTPLIB_SSL_ENABLED
  3156. SSLClient cli(host);
  3157. #else
  3158. Client cli(host);
  3159. #endif
  3160. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3161. auto res = cli.Get("/");
  3162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3163. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3164. }
  3165. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3166. auto host = "google.com";
  3167. auto wrong_ip = "0.0.0.0";
  3168. #ifdef CPPHTTPLIB_SSL_ENABLED
  3169. SSLClient cli(host);
  3170. #else
  3171. Client cli(host);
  3172. #endif
  3173. cli.set_hostname_addr_map({{host, wrong_ip}});
  3174. auto res = cli.Get("/");
  3175. ASSERT_TRUE(!res);
  3176. EXPECT_EQ(Error::Connection, res.error());
  3177. }
  3178. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3179. // A mapped value that is not an IP literal must be resolved. "localhost"
  3180. // resolves from the hosts file, so this test needs no external DNS.
  3181. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3182. auto host = "target.invalid";
  3183. Server svr;
  3184. std::string received_host;
  3185. svr.Get("/hi", [&](const Request &req, Response &res) {
  3186. received_host = req.get_header_value("Host");
  3187. res.set_content("Hello World!", "text/plain");
  3188. });
  3189. auto port = svr.bind_to_any_port(HOST);
  3190. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3191. auto se = detail::scope_exit([&] {
  3192. svr.stop();
  3193. thread.join();
  3194. ASSERT_FALSE(svr.is_running());
  3195. });
  3196. svr.wait_until_ready();
  3197. Client cli(host, port);
  3198. cli.set_hostname_addr_map({{host, HOST}});
  3199. auto res = cli.Get("/hi");
  3200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3201. EXPECT_EQ(StatusCode::OK_200, res->status);
  3202. // The mapping only redirects the connection; the identity stays host_.
  3203. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3204. }
  3205. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3206. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3207. auto host = "target.invalid";
  3208. Server svr;
  3209. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3210. res.set_content("Hello World!", "text/plain");
  3211. });
  3212. auto port = svr.bind_to_any_port("127.0.0.1");
  3213. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3214. auto se = detail::scope_exit([&] {
  3215. svr.stop();
  3216. thread.join();
  3217. ASSERT_FALSE(svr.is_running());
  3218. });
  3219. svr.wait_until_ready();
  3220. Client cli(host, port);
  3221. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3222. auto res = cli.Get("/hi");
  3223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3224. EXPECT_EQ(StatusCode::OK_200, res->status);
  3225. }
  3226. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3227. // An empty mapped value must leave host_ as the connection target. Without
  3228. // that guard the empty value would become the host argument, getaddrinfo
  3229. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3230. // loopback - silently connecting somewhere the caller never asked for.
  3231. // The server listens on loopback, so such a fallback would succeed and is
  3232. // therefore observable as a failure of this test.
  3233. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3234. Server svr;
  3235. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3236. res.set_content("Hello World!", "text/plain");
  3237. });
  3238. auto port = svr.bind_to_any_port(HOST);
  3239. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3240. auto se = detail::scope_exit([&] {
  3241. svr.stop();
  3242. thread.join();
  3243. ASSERT_FALSE(svr.is_running());
  3244. });
  3245. svr.wait_until_ready();
  3246. Client cli(blackhole, port);
  3247. cli.set_hostname_addr_map({{blackhole, ""}});
  3248. cli.set_connection_timeout(1);
  3249. auto res = cli.Get("/hi");
  3250. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3251. }
  3252. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3253. auto host = "httpbingo.org";
  3254. auto path = std::string{"/absolute-redirect/3"};
  3255. #ifdef CPPHTTPLIB_SSL_ENABLED
  3256. SSLClient cli(host);
  3257. #else
  3258. Client cli(host);
  3259. #endif
  3260. cli.set_follow_location(true);
  3261. auto res = cli.Get(path);
  3262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3263. EXPECT_EQ(StatusCode::OK_200, res->status);
  3264. }
  3265. TEST(RedirectTest, Redirect_Online) {
  3266. auto host = "httpbingo.org";
  3267. auto path = std::string{"/redirect/3"};
  3268. #ifdef CPPHTTPLIB_SSL_ENABLED
  3269. SSLClient cli(host);
  3270. #else
  3271. Client cli(host);
  3272. #endif
  3273. cli.set_follow_location(true);
  3274. auto res = cli.Get(path);
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. }
  3278. TEST(RelativeRedirectTest, Redirect_Online) {
  3279. auto host = "httpbingo.org";
  3280. auto path = std::string{"/relative-redirect/3"};
  3281. #ifdef CPPHTTPLIB_SSL_ENABLED
  3282. SSLClient cli(host);
  3283. #else
  3284. Client cli(host);
  3285. #endif
  3286. cli.set_follow_location(true);
  3287. auto res = cli.Get(path);
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. }
  3291. TEST(TooManyRedirectTest, Redirect_Online) {
  3292. auto host = "httpbingo.org";
  3293. auto path = std::string{"/redirect/21"};
  3294. #ifdef CPPHTTPLIB_SSL_ENABLED
  3295. SSLClient cli(host);
  3296. #else
  3297. Client cli(host);
  3298. #endif
  3299. cli.set_follow_location(true);
  3300. auto res = cli.Get(path);
  3301. ASSERT_TRUE(!res);
  3302. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3303. }
  3304. #ifdef CPPHTTPLIB_SSL_ENABLED
  3305. TEST(YahooRedirectTest, Redirect_Online) {
  3306. Client cli("yahoo.com");
  3307. auto res = cli.Get("/");
  3308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3309. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3310. cli.set_follow_location(true);
  3311. res = cli.Get("/");
  3312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3313. EXPECT_EQ(StatusCode::OK_200, res->status);
  3314. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3315. }
  3316. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3317. #define REDIR_HOST "httpbingo.org"
  3318. #define REDIR_PATH "/redirect-to"
  3319. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3320. SSLClient cli(REDIR_HOST);
  3321. cli.set_follow_location(true);
  3322. auto res =
  3323. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3325. EXPECT_EQ(StatusCode::OK_200, res->status);
  3326. }
  3327. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3328. SSLClient cli(REDIR_HOST);
  3329. cli.set_follow_location(true);
  3330. Params params;
  3331. params.emplace("url", "http://example.com");
  3332. params.emplace("status_code", "302");
  3333. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3335. EXPECT_EQ(StatusCode::OK_200, res->status);
  3336. }
  3337. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3338. SSLClient cli(REDIR_HOST);
  3339. cli.set_follow_location(true);
  3340. Params params;
  3341. params.emplace("url", "http://example.com");
  3342. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3344. EXPECT_EQ(StatusCode::OK_200, res->status);
  3345. }
  3346. TEST(UrlWithSpace, Redirect_Online) {
  3347. SSLClient cli("edge.forgecdn.net");
  3348. cli.set_follow_location(true);
  3349. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3351. EXPECT_EQ(StatusCode::OK_200, res->status);
  3352. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3353. }
  3354. #endif
  3355. #if !defined(_WIN32) && !defined(_WIN64)
  3356. TEST(ReceiveSignals, Signal) {
  3357. auto setupSignalHandlers = []() {
  3358. struct sigaction act;
  3359. sigemptyset(&act.sa_mask);
  3360. act.sa_flags = SA_SIGINFO;
  3361. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3362. switch (sig) {
  3363. case SIGINT:
  3364. default: break;
  3365. }
  3366. };
  3367. ::sigaction(SIGINT, &act, nullptr);
  3368. };
  3369. Server svr;
  3370. int port = 0;
  3371. auto thread = std::thread([&]() {
  3372. setupSignalHandlers();
  3373. port = svr.bind_to_any_port(HOST);
  3374. svr.listen_after_bind();
  3375. });
  3376. auto se = detail::scope_exit([&] {
  3377. svr.stop();
  3378. thread.join();
  3379. ASSERT_FALSE(svr.is_running());
  3380. });
  3381. svr.wait_until_ready();
  3382. ASSERT_TRUE(svr.is_running());
  3383. pthread_kill(thread.native_handle(), SIGINT);
  3384. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3385. ASSERT_TRUE(svr.is_running());
  3386. }
  3387. #endif
  3388. TEST(RedirectToDifferentPort, Redirect) {
  3389. Server svr1;
  3390. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3391. res.set_content("Hello World!", "text/plain");
  3392. });
  3393. int svr1_port = 0;
  3394. auto thread1 = std::thread([&]() {
  3395. svr1_port = svr1.bind_to_any_port(HOST);
  3396. svr1.listen_after_bind();
  3397. });
  3398. Server svr2;
  3399. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3400. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3401. });
  3402. int svr2_port = 0;
  3403. auto thread2 = std::thread([&]() {
  3404. svr2_port = svr2.bind_to_any_port(HOST);
  3405. svr2.listen_after_bind();
  3406. });
  3407. auto se = detail::scope_exit([&] {
  3408. svr2.stop();
  3409. thread2.join();
  3410. svr1.stop();
  3411. thread1.join();
  3412. ASSERT_FALSE(svr2.is_running());
  3413. ASSERT_FALSE(svr1.is_running());
  3414. });
  3415. svr1.wait_until_ready();
  3416. svr2.wait_until_ready();
  3417. Client cli("localhost", svr2_port);
  3418. cli.set_follow_location(true);
  3419. auto res = cli.Get("/2");
  3420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3421. EXPECT_EQ(StatusCode::OK_200, res->status);
  3422. EXPECT_EQ("Hello World!", res->body);
  3423. }
  3424. // GET /redir on one server redirects to /target on another port, so the
  3425. // client follows it with a new client.
  3426. static Result
  3427. GetThroughRedirectToDifferentPort(Server::Handler target,
  3428. const std::function<void(Client &)> &setup,
  3429. const Headers &headers = Headers()) {
  3430. Server target_svr;
  3431. target_svr.Get("/target", target);
  3432. int target_port = 0;
  3433. auto target_thread = std::thread([&]() {
  3434. target_port = target_svr.bind_to_any_port(HOST);
  3435. target_svr.listen_after_bind();
  3436. });
  3437. Server origin_svr;
  3438. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3439. res.set_redirect(
  3440. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3441. });
  3442. int origin_port = 0;
  3443. auto origin_thread = std::thread([&]() {
  3444. origin_port = origin_svr.bind_to_any_port(HOST);
  3445. origin_svr.listen_after_bind();
  3446. });
  3447. auto se = detail::scope_exit([&] {
  3448. origin_svr.stop();
  3449. origin_thread.join();
  3450. target_svr.stop();
  3451. target_thread.join();
  3452. });
  3453. target_svr.wait_until_ready();
  3454. origin_svr.wait_until_ready();
  3455. Client cli("localhost", origin_port);
  3456. cli.set_follow_location(true);
  3457. setup(cli);
  3458. return cli.Get("/redir", headers);
  3459. }
  3460. static void
  3461. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3462. std::string captured_authorization;
  3463. auto result = GetThroughRedirectToDifferentPort(
  3464. [&](const Request &req, Response &res) {
  3465. captured_authorization = req.get_header_value("Authorization");
  3466. res.set_content("OK", "text/plain");
  3467. },
  3468. set_auth);
  3469. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3470. EXPECT_EQ(StatusCode::OK_200, result->status);
  3471. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3472. EXPECT_TRUE(captured_authorization.empty());
  3473. }
  3474. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3475. TestDoNotForwardCredentialsOnRedirect(
  3476. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3477. }
  3478. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3479. TestDoNotForwardCredentialsOnRedirect(
  3480. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3481. }
  3482. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3483. std::string captured_cookie;
  3484. auto result = GetThroughRedirectToDifferentPort(
  3485. [&](const Request &req, Response &res) {
  3486. captured_cookie = req.get_header_value("Cookie");
  3487. res.set_content("OK", "text/plain");
  3488. },
  3489. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3490. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3491. EXPECT_EQ(StatusCode::OK_200, result->status);
  3492. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3493. EXPECT_TRUE(captured_cookie.empty());
  3494. }
  3495. TEST(RedirectToSamePort, ForwardCookie) {
  3496. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3497. // header so that ordinary session flows keep working.
  3498. Server svr;
  3499. std::string captured_cookie;
  3500. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3501. res.set_redirect("/target", 302);
  3502. });
  3503. svr.Get("/target", [&](const Request &req, Response &res) {
  3504. captured_cookie = req.get_header_value("Cookie");
  3505. res.set_content("OK", "text/plain");
  3506. });
  3507. auto port = svr.bind_to_any_port(HOST);
  3508. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3509. auto se = detail::scope_exit([&] {
  3510. svr.stop();
  3511. thread.join();
  3512. ASSERT_FALSE(svr.is_running());
  3513. });
  3514. svr.wait_until_ready();
  3515. Client cli(HOST, port);
  3516. cli.set_follow_location(true);
  3517. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3518. auto res = cli.Get("/redir", headers);
  3519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3520. EXPECT_EQ(StatusCode::OK_200, res->status);
  3521. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3522. }
  3523. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3524. std::string authorization;
  3525. std::string trace_id;
  3526. auto result = GetThroughRedirectToDifferentPort(
  3527. [&](const Request &req, Response &res) {
  3528. authorization = req.get_header_value("Authorization");
  3529. trace_id = req.get_header_value("X-Trace-Id");
  3530. res.set_content("OK", "text/plain");
  3531. },
  3532. [](Client &cli) {
  3533. cli.set_default_headers(
  3534. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3535. });
  3536. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3537. EXPECT_EQ(StatusCode::OK_200, result->status);
  3538. // Like a header given with the request, a default one goes along unless it
  3539. // carries credentials (RFC 9110 15.4).
  3540. EXPECT_TRUE(authorization.empty());
  3541. EXPECT_EQ("42", trace_id);
  3542. }
  3543. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3544. auto result = GetThroughRedirectToDifferentPort(
  3545. [](const Request &, Response &res) {
  3546. res.set_content(std::string(2048, 'x'), "text/plain");
  3547. },
  3548. [](Client &cli) { cli.set_payload_max_length(1024); });
  3549. EXPECT_FALSE(result);
  3550. }
  3551. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3552. auto result = GetThroughRedirectToDifferentPort(
  3553. [](const Request &req, Response &res) {
  3554. // Answer after a second, or once the client gives up.
  3555. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3556. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3557. }
  3558. res.set_content("late", "text/plain");
  3559. },
  3560. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3561. ASSERT_FALSE(result);
  3562. EXPECT_EQ(Error::Read, result.error());
  3563. }
  3564. #ifdef CPPHTTPLIB_SSL_ENABLED
  3565. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3566. auto result = GetThroughRedirectToDifferentPort(
  3567. [](const Request &, Response &res) {
  3568. res.status = StatusCode::Unauthorized_401;
  3569. res.set_header("WWW-Authenticate",
  3570. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3571. },
  3572. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3573. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3574. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3575. }
  3576. #endif
  3577. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3578. Server svr;
  3579. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3580. // Port number that overflows int — should not crash
  3581. res.set_redirect("http://localhost:99999999999999999999/target");
  3582. });
  3583. auto port = svr.bind_to_any_port(HOST);
  3584. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3585. auto se = detail::scope_exit([&] {
  3586. svr.stop();
  3587. thread.join();
  3588. ASSERT_FALSE(svr.is_running());
  3589. });
  3590. svr.wait_until_ready();
  3591. Client cli(HOST, port);
  3592. cli.set_follow_location(true);
  3593. auto res = cli.Get("/redir");
  3594. // Should fail gracefully, not crash (no valid response due to bad port)
  3595. EXPECT_FALSE(res);
  3596. }
  3597. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3598. Server svr;
  3599. auto port = svr.bind_to_any_port(HOST);
  3600. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3601. // The server's own port followed by junk must not be followed
  3602. res.set_redirect("http://" + std::string(HOST) + ":" +
  3603. std::to_string(port) + "junk/target");
  3604. });
  3605. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3606. res.set_content("target", "text/plain");
  3607. });
  3608. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3609. auto se = detail::scope_exit([&] {
  3610. svr.stop();
  3611. thread.join();
  3612. ASSERT_FALSE(svr.is_running());
  3613. });
  3614. svr.wait_until_ready();
  3615. Client cli(HOST, port);
  3616. cli.set_follow_location(true);
  3617. auto res = cli.Get("/redir");
  3618. EXPECT_FALSE(res);
  3619. }
  3620. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3621. Server svr;
  3622. std::atomic<bool> followed{false};
  3623. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3624. res.status = StatusCode::NotModified_304;
  3625. res.set_header("Location", "/target");
  3626. });
  3627. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3628. res.status = StatusCode::UseProxy_305;
  3629. res.set_header("Location", "/target");
  3630. });
  3631. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3632. followed = true;
  3633. res.set_content("target", "text/plain");
  3634. });
  3635. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3636. auto se = detail::scope_exit([&] {
  3637. svr.stop();
  3638. th.join();
  3639. ASSERT_FALSE(svr.is_running());
  3640. });
  3641. svr.wait_until_ready();
  3642. Client cli("localhost", PORT);
  3643. cli.set_follow_location(true);
  3644. auto res = cli.Get("/304");
  3645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3646. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3647. res = cli.Get("/305");
  3648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3649. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3650. EXPECT_FALSE(followed);
  3651. }
  3652. TEST(RedirectFromPageWithContent, Redirect) {
  3653. Server svr;
  3654. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3655. res.set_content("___", "text/plain");
  3656. res.set_redirect("/2");
  3657. });
  3658. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3659. res.set_content("Hello World!", "text/plain");
  3660. });
  3661. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3662. auto se = detail::scope_exit([&] {
  3663. svr.stop();
  3664. th.join();
  3665. ASSERT_FALSE(svr.is_running());
  3666. });
  3667. svr.wait_until_ready();
  3668. {
  3669. Client cli("localhost", PORT);
  3670. cli.set_follow_location(true);
  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::OK_200, res->status);
  3678. EXPECT_EQ("Hello World!", body);
  3679. }
  3680. {
  3681. Client cli("localhost", PORT);
  3682. std::string body;
  3683. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3684. body.append(data, data_length);
  3685. return true;
  3686. });
  3687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3688. EXPECT_EQ(StatusCode::Found_302, res->status);
  3689. EXPECT_EQ("___", body);
  3690. }
  3691. }
  3692. // A server can close the connection after a request with "Connection: close"
  3693. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3694. // redirected request must go out on a new connection.
  3695. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3696. #ifndef _WIN32
  3697. signal(SIGPIPE, SIG_IGN);
  3698. #endif
  3699. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3700. default_socket_options(srv);
  3701. sockaddr_in addr{};
  3702. addr.sin_family = AF_INET;
  3703. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3704. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3705. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3706. ASSERT_EQ(0, ::listen(srv, 2));
  3707. auto send_text = [](socket_t sock, const std::string &text) {
  3708. ::send(sock,
  3709. #ifdef _WIN32
  3710. static_cast<const char *>(text.c_str()),
  3711. static_cast<int>(text.size()),
  3712. #else
  3713. text.c_str(), text.size(),
  3714. #endif
  3715. 0);
  3716. };
  3717. auto reused = false;
  3718. auto server_thread = std::thread([&] {
  3719. char buf[4096];
  3720. auto first = ::accept(srv, nullptr, nullptr);
  3721. if (first == INVALID_SOCKET) { return; }
  3722. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3723. ::recv(first, buf, sizeof(buf), 0);
  3724. send_text(
  3725. first,
  3726. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3727. auto next = first;
  3728. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3729. reused = true;
  3730. } else {
  3731. detail::close_socket(first);
  3732. next = ::accept(srv, nullptr, nullptr);
  3733. if (next == INVALID_SOCKET) { return; }
  3734. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3735. ::recv(next, buf, sizeof(buf), 0);
  3736. }
  3737. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3738. "Connection: close\r\n\r\nok");
  3739. detail::close_socket(next);
  3740. });
  3741. Client cli("127.0.0.1", PORT + 2);
  3742. cli.set_follow_location(true);
  3743. cli.set_read_timeout(5, 0);
  3744. auto res = cli.Get("/1");
  3745. server_thread.join();
  3746. detail::close_socket(srv);
  3747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3748. EXPECT_EQ(StatusCode::OK_200, res->status);
  3749. EXPECT_EQ("ok", res->body);
  3750. EXPECT_FALSE(reused);
  3751. }
  3752. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3753. Server svr;
  3754. auto port_str = std::to_string(PORT);
  3755. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3756. auto expected_host = "[::1]:" + port_str;
  3757. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3758. res.set_content("___", "text/plain");
  3759. // res.set_redirect("/2");
  3760. res.set_redirect(redirect_url);
  3761. });
  3762. svr.Get("/2", [&](const Request &req, Response &res) {
  3763. auto host_header = req.headers.find("Host");
  3764. ASSERT_TRUE(host_header != req.headers.end());
  3765. EXPECT_EQ(expected_host, host_header->second);
  3766. res.set_content("Hello World!", "text/plain");
  3767. });
  3768. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3769. auto se = detail::scope_exit([&] {
  3770. svr.stop();
  3771. th.join();
  3772. ASSERT_FALSE(svr.is_running());
  3773. });
  3774. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3775. // actually starts anything, so the condition !svr.is_running() will
  3776. // always remain true, and the loop never stops.
  3777. // This basically counts how many milliseconds have passed since the
  3778. // call to svr.listen(), and if after 5 seconds nothing started yet
  3779. // aborts the test.
  3780. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3781. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3782. ASSERT_LT(milliseconds, 5000U);
  3783. }
  3784. {
  3785. Client cli("::1", PORT);
  3786. cli.set_follow_location(true);
  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::OK_200, res->status);
  3794. EXPECT_EQ("Hello World!", body);
  3795. }
  3796. {
  3797. Client cli("::1", PORT);
  3798. std::string body;
  3799. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3800. body.append(data, data_length);
  3801. return true;
  3802. });
  3803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3804. EXPECT_EQ(StatusCode::Found_302, res->status);
  3805. EXPECT_EQ("___", body);
  3806. }
  3807. }
  3808. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3809. Server svr;
  3810. svr.Get("/foo", [](const Request &req, Response &res) {
  3811. auto a = req.params.find("a");
  3812. if (a != req.params.end()) {
  3813. res.set_content((*a).second, "text/plain");
  3814. res.status = StatusCode::OK_200;
  3815. } else {
  3816. res.status = StatusCode::BadRequest_400;
  3817. }
  3818. });
  3819. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3820. auto se = detail::scope_exit([&] {
  3821. svr.stop();
  3822. thread.join();
  3823. ASSERT_FALSE(svr.is_running());
  3824. });
  3825. svr.wait_until_ready();
  3826. {
  3827. Client cli(HOST, PORT);
  3828. cli.set_path_encode(false);
  3829. auto res = cli.Get("/foo?a=explicitly+encoded");
  3830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3831. EXPECT_EQ(StatusCode::OK_200, res->status);
  3832. // This expects it back with a space, as the `+` won't have been
  3833. // url-encoded, and server-side the params get decoded turning `+`
  3834. // into spaces.
  3835. EXPECT_EQ("explicitly encoded", res->body);
  3836. }
  3837. }
  3838. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3839. // When path encoding is disabled the client must transmit the supplied
  3840. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3841. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3842. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3843. // than a space (0x20). Assert on the raw wire target to catch this.
  3844. Server svr;
  3845. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3846. svr.Get("/foo", [&](const Request &req, Response &res) {
  3847. EXPECT_EQ(expected_target, req.target);
  3848. res.status = StatusCode::OK_200;
  3849. });
  3850. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3851. auto se = detail::scope_exit([&] {
  3852. svr.stop();
  3853. thread.join();
  3854. ASSERT_FALSE(svr.is_running());
  3855. });
  3856. svr.wait_until_ready();
  3857. {
  3858. Client cli(HOST, PORT);
  3859. cli.set_path_encode(false);
  3860. auto res = cli.Get(expected_target.c_str());
  3861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3862. EXPECT_EQ(StatusCode::OK_200, res->status);
  3863. }
  3864. }
  3865. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3866. // `open_stream()` used to skip the path encoding that the buffered send
  3867. // path applies, so the same `path` produced different bytes in the request
  3868. // line depending on which API was used. Assert the two agree.
  3869. Server svr;
  3870. std::string target;
  3871. svr.Get(".*", [&](const Request &req, Response &res) {
  3872. target = req.target;
  3873. res.status = StatusCode::OK_200;
  3874. });
  3875. auto port = svr.bind_to_any_port(HOST);
  3876. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3877. auto se = detail::scope_exit([&] {
  3878. svr.stop();
  3879. thread.join();
  3880. ASSERT_FALSE(svr.is_running());
  3881. });
  3882. svr.wait_until_ready();
  3883. struct {
  3884. const char *path;
  3885. const char *expected;
  3886. } cases[] = {
  3887. {"/a b?x=1", "/a%20b?x=1"},
  3888. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3889. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3890. };
  3891. for (const auto &c : cases) {
  3892. Client cli(HOST, port);
  3893. target.clear();
  3894. auto res = cli.Get(c.path);
  3895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3896. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3897. auto buffered_target = target;
  3898. target.clear();
  3899. auto handle = cli.open_stream("GET", c.path);
  3900. EXPECT_TRUE(handle.is_valid())
  3901. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3902. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3903. }
  3904. }
  3905. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3906. // The `set_path_encode(false)` contract — transmit the supplied target
  3907. // verbatim — must hold for the streaming API too.
  3908. Server svr;
  3909. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3910. std::string target;
  3911. svr.Get("/foo", [&](const Request &req, Response &res) {
  3912. target = req.target;
  3913. res.status = StatusCode::OK_200;
  3914. });
  3915. auto port = svr.bind_to_any_port(HOST);
  3916. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3917. auto se = detail::scope_exit([&] {
  3918. svr.stop();
  3919. thread.join();
  3920. ASSERT_FALSE(svr.is_running());
  3921. });
  3922. svr.wait_until_ready();
  3923. {
  3924. Client cli(HOST, port);
  3925. cli.set_path_encode(false);
  3926. auto handle = cli.open_stream("GET", expected_target);
  3927. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3928. EXPECT_EQ(expected_target, target);
  3929. }
  3930. }
  3931. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3932. // With path encoding enabled a CR/LF in the target is percent-encoded
  3933. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3934. // write_request_line still backstops `set_path_encode(false)`, which is
  3935. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3936. Server svr;
  3937. // Captured before routing: the decoded path contains a newline, which a
  3938. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3939. std::string target;
  3940. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3941. target = req.target;
  3942. res.status = StatusCode::OK_200;
  3943. return Server::HandlerResponse::Handled;
  3944. });
  3945. auto port = svr.bind_to_any_port(HOST);
  3946. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3947. auto se = detail::scope_exit([&] {
  3948. svr.stop();
  3949. thread.join();
  3950. ASSERT_FALSE(svr.is_running());
  3951. });
  3952. svr.wait_until_ready();
  3953. {
  3954. Client cli(HOST, port);
  3955. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3956. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3957. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3958. }
  3959. }
  3960. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3961. // Every control character is percent-encoded, not just CR/LF, so the target
  3962. // passes the request-target check in write_request_line.
  3963. Server svr;
  3964. std::string target;
  3965. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3966. target = req.target;
  3967. res.status = StatusCode::OK_200;
  3968. return Server::HandlerResponse::Handled;
  3969. });
  3970. auto port = svr.bind_to_any_port(HOST);
  3971. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3972. auto se = detail::scope_exit([&] {
  3973. svr.stop();
  3974. thread.join();
  3975. ASSERT_FALSE(svr.is_running());
  3976. });
  3977. svr.wait_until_ready();
  3978. {
  3979. Client cli(HOST, port);
  3980. auto res = cli.Get("/a\tb\x1b\x7f");
  3981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3982. EXPECT_EQ("/a%09b%1B%7F", target);
  3983. }
  3984. }
  3985. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3986. // Nothing may reach the wire: a raw CR/LF target would split the request
  3987. // line and inject headers.
  3988. Server svr;
  3989. // Pre-routing so that "not called" means nothing reached the server at all,
  3990. // rather than merely failing to match a handler pattern.
  3991. auto handler_called = false;
  3992. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3993. handler_called = true;
  3994. res.status = StatusCode::OK_200;
  3995. return Server::HandlerResponse::Handled;
  3996. });
  3997. auto port = svr.bind_to_any_port(HOST);
  3998. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3999. auto se = detail::scope_exit([&] {
  4000. svr.stop();
  4001. thread.join();
  4002. ASSERT_FALSE(svr.is_running());
  4003. });
  4004. svr.wait_until_ready();
  4005. {
  4006. Client cli(HOST, port);
  4007. cli.set_path_encode(false);
  4008. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4009. EXPECT_FALSE(handle.is_valid());
  4010. EXPECT_EQ(Error::Write, handle.error);
  4011. EXPECT_FALSE(handler_called);
  4012. }
  4013. }
  4014. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4015. // Which of the two branches runs is decided by whether the query component
  4016. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4017. // an empty query and must still fall back to building one from
  4018. // `req.params`, while a non-empty query must win over `req.params`.
  4019. Server svr;
  4020. std::string target;
  4021. svr.Get("/foo", [&](const Request &req, Response &res) {
  4022. target = req.target;
  4023. res.status = StatusCode::OK_200;
  4024. });
  4025. auto port = svr.bind_to_any_port(HOST);
  4026. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4027. auto se = detail::scope_exit([&] {
  4028. svr.stop();
  4029. thread.join();
  4030. ASSERT_FALSE(svr.is_running());
  4031. });
  4032. svr.wait_until_ready();
  4033. {
  4034. // Trailing `?` -> empty query component -> `req.params` is used.
  4035. Client cli(HOST, port);
  4036. Request req;
  4037. req.method = "GET";
  4038. req.path = "/foo?";
  4039. req.params.emplace("a", "1");
  4040. target.clear();
  4041. auto res = cli.send(req);
  4042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4043. EXPECT_EQ("/foo?a=1", target);
  4044. }
  4045. {
  4046. // Non-empty query in `req.path` -> `req.params` is not appended.
  4047. Client cli(HOST, port);
  4048. Request req;
  4049. req.method = "GET";
  4050. req.path = "/foo?b=2";
  4051. req.params.emplace("a", "1");
  4052. target.clear();
  4053. auto res = cli.send(req);
  4054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4055. EXPECT_EQ("/foo?b=2", target);
  4056. }
  4057. }
  4058. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4059. Server svr;
  4060. svr.Get("/", [](const Request &req, Response &) {
  4061. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4062. });
  4063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4064. auto se = detail::scope_exit([&] {
  4065. svr.stop();
  4066. thread.join();
  4067. ASSERT_FALSE(svr.is_running());
  4068. });
  4069. svr.wait_until_ready();
  4070. {
  4071. Client cli(HOST, PORT);
  4072. cli.set_path_encode(false);
  4073. auto res = cli.Get("/?something=%0A");
  4074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4075. EXPECT_EQ(StatusCode::OK_200, res->status);
  4076. }
  4077. }
  4078. TEST(BindServerTest, BindDualStack) {
  4079. Server svr;
  4080. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4081. res.set_content("Hello World!", "text/plain");
  4082. });
  4083. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4084. auto se = detail::scope_exit([&] {
  4085. svr.stop();
  4086. thread.join();
  4087. ASSERT_FALSE(svr.is_running());
  4088. });
  4089. svr.wait_until_ready();
  4090. {
  4091. Client cli("127.0.0.1", PORT);
  4092. auto res = cli.Get("/1");
  4093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4094. EXPECT_EQ(StatusCode::OK_200, res->status);
  4095. EXPECT_EQ("Hello World!", res->body);
  4096. }
  4097. {
  4098. Client cli("::1", PORT);
  4099. auto res = cli.Get("/1");
  4100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4101. EXPECT_EQ(StatusCode::OK_200, res->status);
  4102. EXPECT_EQ("Hello World!", res->body);
  4103. }
  4104. }
  4105. TEST(BindServerTest, BindAndListenSeparately) {
  4106. Server svr;
  4107. int port = svr.bind_to_any_port("0.0.0.0");
  4108. ASSERT_TRUE(svr.is_valid());
  4109. ASSERT_TRUE(port > 0);
  4110. svr.stop();
  4111. }
  4112. // Reports whether anything is still listening on a loopback port. A plain
  4113. // connect() is used instead of a Client request because a socket left bound by
  4114. // mistake accepts the connection into its backlog and never answers, which
  4115. // would hang the test instead of failing it.
  4116. static bool is_loopback_port_accepting(int port) {
  4117. sockaddr_in addr{};
  4118. addr.sin_family = AF_INET;
  4119. addr.sin_port = htons(static_cast<uint16_t>(port));
  4120. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4121. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4122. EXPECT_NE(sock, INVALID_SOCKET);
  4123. if (sock == INVALID_SOCKET) { return false; }
  4124. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4125. static_cast<socklen_t>(sizeof(addr)));
  4126. detail::close_socket(sock);
  4127. return ret == 0;
  4128. }
  4129. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4130. Server svr;
  4131. auto port = svr.bind_to_any_port("127.0.0.1");
  4132. ASSERT_TRUE(port > 0);
  4133. svr.stop();
  4134. // bind_to_any_port() already called listen(2), so until stop() closed the
  4135. // descriptor the port kept accepting connections into the backlog. ASSERT
  4136. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4137. // below blocks forever in the accept loop.
  4138. ASSERT_FALSE(is_loopback_port_accepting(port));
  4139. // Nothing is left to accept on, so listen_after_bind() must report failure
  4140. // instead of returning success without ever serving.
  4141. EXPECT_FALSE(svr.listen_after_bind());
  4142. // The failed listen marks the server decommissioned, so a waiter returns
  4143. // instead of spinning forever.
  4144. svr.wait_until_ready();
  4145. }
  4146. #ifdef CPPHTTPLIB_SSL_ENABLED
  4147. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4148. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4149. CLIENT_CA_CERT_DIR);
  4150. int port = svr.bind_to_any_port("0.0.0.0");
  4151. ASSERT_TRUE(svr.is_valid());
  4152. ASSERT_TRUE(port > 0);
  4153. svr.stop();
  4154. }
  4155. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4156. // or a rejected CustomRoute() registration would not stop the server binding.
  4157. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4158. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4159. CLIENT_CA_CERT_DIR);
  4160. ASSERT_TRUE(svr.is_valid());
  4161. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4162. EXPECT_FALSE(svr.is_valid());
  4163. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4164. }
  4165. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4166. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4167. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4168. int port = svr.bind_to_any_port("0.0.0.0");
  4169. ASSERT_TRUE(svr.is_valid());
  4170. ASSERT_TRUE(port > 0);
  4171. svr.stop();
  4172. }
  4173. TEST(BindServerTest, UpdateCertsPem) {
  4174. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4175. int port = svr.bind_to_any_port("0.0.0.0");
  4176. ASSERT_TRUE(svr.is_valid());
  4177. ASSERT_TRUE(port > 0);
  4178. // Read PEM files
  4179. std::string cert_pem, key_pem, ca_pem;
  4180. read_file(SERVER_CERT_FILE, cert_pem);
  4181. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4182. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4183. // Update server certificates using PEM API
  4184. ASSERT_TRUE(
  4185. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4186. ASSERT_TRUE(svr.is_valid());
  4187. svr.stop();
  4188. }
  4189. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4190. // Start server with client CA (enables client auth)
  4191. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4192. ASSERT_TRUE(svr.is_valid());
  4193. bool handler_called = false;
  4194. svr.Get("/test", [&](const Request &req, Response &res) {
  4195. handler_called = true;
  4196. // Verify client certificate is present
  4197. auto cert = req.peer_cert();
  4198. EXPECT_TRUE(static_cast<bool>(cert));
  4199. res.set_content("ok", "text/plain");
  4200. });
  4201. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4202. auto se = detail::scope_exit([&] {
  4203. svr.stop();
  4204. t.join();
  4205. ASSERT_FALSE(svr.is_running());
  4206. });
  4207. svr.wait_until_ready();
  4208. // Read PEM files
  4209. std::string cert_pem, key_pem, ca_pem;
  4210. read_file(SERVER_CERT_FILE, cert_pem);
  4211. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4212. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4213. // Update server certificates and client CA using PEM API while server running
  4214. ASSERT_TRUE(
  4215. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4216. // Connect with client certificate
  4217. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4218. cli.enable_server_certificate_verification(false);
  4219. cli.set_connection_timeout(30);
  4220. auto res = cli.Get("/test");
  4221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4222. ASSERT_EQ(StatusCode::OK_200, res->status);
  4223. ASSERT_TRUE(handler_called);
  4224. EXPECT_EQ("ok", res->body);
  4225. }
  4226. // Puts a CA that did not sign the client's certificate in the old one's place.
  4227. static bool replace_client_ca(SSLServer &svr) {
  4228. std::string cert_pem, key_pem, ca_pem;
  4229. read_file(SERVER_CERT_FILE, cert_pem);
  4230. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4231. read_file(SERVER_CERT2_FILE, ca_pem);
  4232. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4233. ca_pem.c_str());
  4234. }
  4235. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4237. ASSERT_TRUE(svr.is_valid());
  4238. svr.Get("/test", [](const Request &, Response &res) {
  4239. res.set_content("ok", "text/plain");
  4240. });
  4241. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4242. auto se = detail::scope_exit([&] {
  4243. svr.stop();
  4244. t.join();
  4245. ASSERT_FALSE(svr.is_running());
  4246. });
  4247. svr.wait_until_ready();
  4248. auto get = [] {
  4249. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4250. cli.enable_server_certificate_verification(false);
  4251. return cli.Get("/test");
  4252. };
  4253. ASSERT_TRUE(get());
  4254. ASSERT_TRUE(replace_client_ca(svr));
  4255. EXPECT_FALSE(get());
  4256. }
  4257. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4258. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4259. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4260. ASSERT_TRUE(svr.is_valid());
  4261. tls::set_verify_callback(svr.tls_context(),
  4262. [](const tls::VerifyContext &) -> bool {
  4263. throw std::runtime_error("verify");
  4264. });
  4265. svr.Get("/test", [](const Request &, Response &res) {
  4266. res.set_content("ok", "text/plain");
  4267. });
  4268. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4269. auto se = detail::scope_exit([&] {
  4270. svr.stop();
  4271. t.join();
  4272. ASSERT_FALSE(svr.is_running());
  4273. });
  4274. svr.wait_until_ready();
  4275. auto get = [] {
  4276. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4277. cli.enable_server_certificate_verification(false);
  4278. return cli.Get("/test");
  4279. };
  4280. EXPECT_FALSE(get());
  4281. // The handshake is over, so an update does not wait for it.
  4282. std::string cert_pem, key_pem;
  4283. read_file(SERVER_CERT_FILE, cert_pem);
  4284. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4285. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4286. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4287. return v.preverify_ok;
  4288. });
  4289. auto res = get();
  4290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4291. EXPECT_EQ("ok", res->body);
  4292. }
  4293. #endif
  4294. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4295. // Sends each request over a new connection with a client certificate,
  4296. // resuming the session of the one before when there is one.
  4297. class ResumingClient {
  4298. public:
  4299. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4300. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4301. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4302. SSL_FILETYPE_PEM);
  4303. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4304. // callback, not through SSL_get1_session().
  4305. SSL_CTX_set_app_data(ctx_, this);
  4306. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4307. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4308. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4309. auto self = static_cast<ResumingClient *>(
  4310. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4311. SSL_SESSION_free(self->session_);
  4312. self->session_ = session;
  4313. return 1; // Keeps the reference
  4314. });
  4315. }
  4316. ~ResumingClient() {
  4317. SSL_SESSION_free(session_);
  4318. SSL_CTX_free(ctx_);
  4319. }
  4320. // Tells whether the request was answered.
  4321. bool get() {
  4322. auto error = Error::Success;
  4323. auto sock = detail::create_client_socket(
  4324. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4325. /*connection_timeout_sec=*/5, 0,
  4326. /*read_timeout_sec=*/5, 0,
  4327. /*write_timeout_sec=*/5, 0, std::string(), error);
  4328. if (sock == INVALID_SOCKET) { return false; }
  4329. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4330. auto ssl = SSL_new(ctx_);
  4331. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4332. SSL_set_fd(ssl, static_cast<int>(sock));
  4333. if (session_) { SSL_set_session(ssl, session_); }
  4334. if (SSL_connect(ssl) != 1) { return false; }
  4335. reused_ = SSL_session_reused(ssl) == 1;
  4336. // Reading the response also takes in a TLS 1.3 session ticket.
  4337. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4338. "Connection: close\r\n\r\n";
  4339. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4340. std::string res;
  4341. char buf[256];
  4342. int n;
  4343. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4344. res.append(buf, static_cast<size_t>(n));
  4345. }
  4346. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4347. SSL_shutdown(ssl);
  4348. return res.find("200 OK") != std::string::npos;
  4349. }
  4350. // Whether the last connection resumed a session
  4351. bool reused() const { return reused_; }
  4352. private:
  4353. SSL_CTX *ctx_;
  4354. SSL_SESSION *session_ = nullptr;
  4355. bool reused_ = false;
  4356. };
  4357. // A client that resumes its session gets through, but not once the client CA
  4358. // has changed, as a resumed session does not show the certificate again.
  4359. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4360. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4361. ASSERT_TRUE(svr.is_valid());
  4362. svr.Get("/test", [](const Request &, Response &res) {
  4363. res.set_content("ok", "text/plain");
  4364. });
  4365. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4366. auto se = detail::scope_exit([&] {
  4367. svr.stop();
  4368. t.join();
  4369. ASSERT_FALSE(svr.is_running());
  4370. });
  4371. svr.wait_until_ready();
  4372. ResumingClient cli;
  4373. ASSERT_TRUE(cli.get());
  4374. ASSERT_TRUE(cli.get());
  4375. EXPECT_TRUE(cli.reused());
  4376. ASSERT_TRUE(replace_client_ca(svr));
  4377. EXPECT_FALSE(cli.get());
  4378. }
  4379. // A resumed session does not show the certificate again, so the server does
  4380. // not resume one with a verify callback to run on it.
  4381. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4382. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4383. ASSERT_TRUE(svr.is_valid());
  4384. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4385. return v.preverify_ok;
  4386. });
  4387. svr.Get("/test", [](const Request &, Response &res) {
  4388. res.set_content("ok", "text/plain");
  4389. });
  4390. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4391. auto se = detail::scope_exit([&] {
  4392. svr.stop();
  4393. t.join();
  4394. ASSERT_FALSE(svr.is_running());
  4395. });
  4396. svr.wait_until_ready();
  4397. ResumingClient cli;
  4398. ASSERT_TRUE(cli.get());
  4399. ASSERT_TRUE(cli.get());
  4400. EXPECT_FALSE(cli.reused());
  4401. }
  4402. #endif
  4403. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4404. // wolfSSL shares its session cache between contexts, so a resumed session
  4405. // could carry a client certificate checked against another server's CA, or
  4406. // against a client CA since replaced.
  4407. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4409. ASSERT_TRUE(svr.is_valid());
  4410. // Trusts a CA that did not sign the client's certificate.
  4411. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4412. ASSERT_TRUE(other.is_valid());
  4413. for (auto s : {&svr, &other}) {
  4414. s->Get("/test", [](const Request &, Response &res) {
  4415. res.set_content("ok", "text/plain");
  4416. });
  4417. }
  4418. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4419. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4420. auto se = detail::scope_exit([&] {
  4421. other.stop();
  4422. svr.stop();
  4423. t2.join();
  4424. t.join();
  4425. });
  4426. svr.wait_until_ready();
  4427. other.wait_until_ready();
  4428. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4429. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4430. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4431. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4432. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4433. ASSERT_EQ(WOLFSSL_SUCCESS,
  4434. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4435. WOLFSSL_FILETYPE_PEM));
  4436. WOLFSSL_SESSION *session = nullptr;
  4437. auto session_se = detail::scope_exit([&] {
  4438. if (session) { wolfSSL_SESSION_free(session); }
  4439. });
  4440. // A request over a new connection, resuming `session` when there is one and
  4441. // keeping the connection's own in its place. Tells whether it was answered.
  4442. auto get = [&](int port) {
  4443. auto error = Error::Success;
  4444. auto sock = detail::create_client_socket(
  4445. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4446. /*connection_timeout_sec=*/5, 0,
  4447. /*read_timeout_sec=*/5, 0,
  4448. /*write_timeout_sec=*/5, 0, std::string(), error);
  4449. if (sock == INVALID_SOCKET) { return false; }
  4450. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4451. auto ssl = wolfSSL_new(ctx);
  4452. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4453. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4454. if (session) { wolfSSL_set_session(ssl, session); }
  4455. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4456. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4457. "Connection: close\r\n\r\n";
  4458. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4459. std::string res;
  4460. char buf[256];
  4461. int n;
  4462. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4463. res.append(buf, static_cast<size_t>(n));
  4464. }
  4465. wolfSSL_shutdown(ssl);
  4466. if (session) { wolfSSL_SESSION_free(session); }
  4467. session = wolfSSL_get1_session(ssl);
  4468. return res.find("200 OK") != std::string::npos;
  4469. };
  4470. ASSERT_TRUE(get(PORT));
  4471. EXPECT_FALSE(get(PORT + 1));
  4472. ASSERT_TRUE(get(PORT));
  4473. ASSERT_TRUE(replace_client_ca(svr));
  4474. EXPECT_FALSE(get(PORT));
  4475. }
  4476. #endif
  4477. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4479. ASSERT_TRUE(svr.is_valid());
  4480. svr.Get("/test", [](const Request &, Response &res) {
  4481. res.set_content("ok", "text/plain");
  4482. });
  4483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4484. auto se = detail::scope_exit([&] {
  4485. svr.stop();
  4486. t.join();
  4487. ASSERT_FALSE(svr.is_running());
  4488. });
  4489. svr.wait_until_ready();
  4490. // A connection that sends no ClientHello keeps its handshake in progress,
  4491. // once the server has had a moment to start it.
  4492. auto error = Error::Success;
  4493. auto sock = detail::create_client_socket(
  4494. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4495. /*connection_timeout_sec=*/5, 0,
  4496. /*read_timeout_sec=*/5, 0,
  4497. /*write_timeout_sec=*/5, 0, std::string(), error);
  4498. ASSERT_NE(INVALID_SOCKET, sock);
  4499. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4500. std::string cert_pem, key_pem;
  4501. read_file(SERVER_CERT_FILE, cert_pem);
  4502. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4503. auto update = std::async(std::launch::async, [&]() {
  4504. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4505. });
  4506. EXPECT_EQ(std::future_status::timeout,
  4507. update.wait_for(std::chrono::milliseconds(200)));
  4508. detail::close_socket(sock);
  4509. EXPECT_TRUE(update.get());
  4510. SSLClient cli(HOST, PORT);
  4511. cli.enable_server_certificate_verification(false);
  4512. auto res = cli.Get("/test");
  4513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4514. EXPECT_EQ(StatusCode::OK_200, res->status);
  4515. }
  4516. #endif
  4517. TEST(ErrorHandlerTest, ContentLength) {
  4518. Server svr;
  4519. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4520. res.status = StatusCode::OK_200;
  4521. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4522. "text/html"); // <= Content-Length still 13
  4523. });
  4524. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4525. res.set_content("Hello World!\n", "text/plain");
  4526. res.status = 524;
  4527. });
  4528. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4529. auto se = detail::scope_exit([&] {
  4530. svr.stop();
  4531. thread.join();
  4532. ASSERT_FALSE(svr.is_running());
  4533. });
  4534. svr.wait_until_ready();
  4535. {
  4536. Client cli(HOST, PORT);
  4537. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4539. EXPECT_EQ(StatusCode::OK_200, res->status);
  4540. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4541. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4542. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4543. }
  4544. }
  4545. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4546. TEST(ExceptionTest, WithoutExceptionHandler) {
  4547. Server svr;
  4548. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4549. throw std::runtime_error("exception...");
  4550. });
  4551. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4552. throw std::runtime_error("exception\r\n...");
  4553. });
  4554. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4555. auto se = detail::scope_exit([&] {
  4556. svr.stop();
  4557. listen_thread.join();
  4558. ASSERT_FALSE(svr.is_running());
  4559. });
  4560. svr.wait_until_ready();
  4561. Client cli("localhost", PORT);
  4562. {
  4563. auto res = cli.Get("/exception");
  4564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4565. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4566. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4567. }
  4568. {
  4569. auto res = cli.Get("/unknown");
  4570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4571. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4572. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4573. }
  4574. }
  4575. TEST(ExceptionTest, WithExceptionHandler) {
  4576. Server svr;
  4577. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4578. std::exception_ptr ep) {
  4579. EXPECT_FALSE(ep == nullptr);
  4580. try {
  4581. std::rethrow_exception(ep);
  4582. } catch (std::exception &e) {
  4583. EXPECT_EQ("abc", std::string(e.what()));
  4584. } catch (...) {}
  4585. res.status = StatusCode::InternalServerError_500;
  4586. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4587. "text/html"); // <= Content-Length still 13 at this point
  4588. });
  4589. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4590. res.set_content("Hello World!\n", "text/plain");
  4591. throw std::runtime_error("abc");
  4592. });
  4593. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4594. auto se = detail::scope_exit([&] {
  4595. svr.stop();
  4596. thread.join();
  4597. ASSERT_FALSE(svr.is_running());
  4598. });
  4599. svr.wait_until_ready();
  4600. for (size_t i = 0; i < 10; i++) {
  4601. Client cli(HOST, PORT);
  4602. for (size_t j = 0; j < 100; j++) {
  4603. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4605. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4606. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4607. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4608. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4609. }
  4610. cli.set_keep_alive(true);
  4611. for (size_t j = 0; j < 100; j++) {
  4612. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4614. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4615. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4616. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4617. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4618. }
  4619. }
  4620. }
  4621. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4622. Server svr;
  4623. svr.set_exception_handler(
  4624. [](const Request &, Response &res, std::exception_ptr) {
  4625. res.set_content("oops", "text/plain");
  4626. });
  4627. svr.Get("/throw", [](const Request &, Response &) {
  4628. throw std::runtime_error("throw");
  4629. });
  4630. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4631. res.status = StatusCode::Created_201;
  4632. throw std::runtime_error("created-then-throw");
  4633. });
  4634. auto port = svr.bind_to_any_port(HOST);
  4635. ASSERT_GT(port, 0);
  4636. thread t = thread([&] { svr.listen_after_bind(); });
  4637. auto se = detail::scope_exit([&] {
  4638. svr.stop();
  4639. t.join();
  4640. ASSERT_FALSE(svr.is_running());
  4641. });
  4642. svr.wait_until_ready();
  4643. Client cli(HOST, port);
  4644. for (auto path : {"/throw", "/created-then-throw"}) {
  4645. auto res = cli.Get(path);
  4646. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4647. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4648. }
  4649. }
  4650. TEST(ExceptionTest, AndErrorHandler) {
  4651. Server svr;
  4652. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4653. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4654. });
  4655. svr.set_exception_handler(
  4656. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4657. EXPECT_FALSE(ep == nullptr);
  4658. try {
  4659. std::rethrow_exception(ep);
  4660. } catch (std::exception &e) {
  4661. res.set_content(e.what(), "text/html");
  4662. } catch (...) {}
  4663. res.status = StatusCode::InternalServerError_500;
  4664. });
  4665. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4666. throw std::runtime_error("EXCEPTION");
  4667. });
  4668. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4669. res.set_content("ERROR", "text/html");
  4670. res.status = StatusCode::InternalServerError_500;
  4671. });
  4672. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4673. auto se = detail::scope_exit([&] {
  4674. svr.stop();
  4675. thread.join();
  4676. ASSERT_FALSE(svr.is_running());
  4677. });
  4678. svr.wait_until_ready();
  4679. Client cli(HOST, PORT);
  4680. {
  4681. auto res = cli.Get("/exception");
  4682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4683. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4684. EXPECT_EQ("EXCEPTION", res->body);
  4685. }
  4686. {
  4687. auto res = cli.Get("/error");
  4688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4689. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4690. EXPECT_EQ("ERROR", res->body);
  4691. }
  4692. {
  4693. auto res = cli.Get("/invalid");
  4694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4695. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4696. EXPECT_EQ("NOT_FOUND", res->body);
  4697. }
  4698. }
  4699. #endif
  4700. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4701. // An exception from a user callback outside process_request()'s try/catch
  4702. // used to unwind into the task queue - which does not catch - and terminate
  4703. // the process. Each test below runs the server on a single worker thread: a
  4704. // guard that catches the exception but still loses the thread would otherwise
  4705. // be hidden by a spare worker serving the follow-up request. Note that a
  4706. // regression here aborts the whole test binary rather than failing one test.
  4707. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4708. Server svr;
  4709. svr.new_task_queue = [] { return new ThreadPool(1); };
  4710. std::atomic<int> reported{0};
  4711. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4712. if (err == Error::UserCallbackException) { reported++; }
  4713. });
  4714. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4715. res.set_content_provider(
  4716. 1024, "text/plain",
  4717. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4718. sink.write("hello", 5);
  4719. throw std::runtime_error("from the content provider");
  4720. });
  4721. });
  4722. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4723. res.set_content("ok", "text/plain");
  4724. });
  4725. auto port = svr.bind_to_any_port(HOST);
  4726. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4727. auto se = detail::scope_exit([&] {
  4728. svr.stop();
  4729. listen_thread.join();
  4730. ASSERT_FALSE(svr.is_running());
  4731. });
  4732. svr.wait_until_ready();
  4733. {
  4734. Client cli(HOST, port);
  4735. cli.set_read_timeout(5, 0);
  4736. EXPECT_FALSE(cli.Get("/throw"));
  4737. }
  4738. EXPECT_TRUE(svr.is_running());
  4739. EXPECT_EQ(1, reported.load());
  4740. // A request on a fresh connection is still served.
  4741. {
  4742. Client cli(HOST, port);
  4743. auto res = cli.Get("/ok");
  4744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4745. EXPECT_EQ(StatusCode::OK_200, res->status);
  4746. EXPECT_EQ("ok", res->body);
  4747. }
  4748. }
  4749. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4750. Server svr;
  4751. svr.new_task_queue = [] { return new ThreadPool(1); };
  4752. std::atomic<bool> should_throw{true};
  4753. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4754. res.set_content("hi", "text/plain");
  4755. });
  4756. svr.set_post_routing_handler(
  4757. [&](const Request & /*req*/, Response & /*res*/) {
  4758. if (should_throw) {
  4759. throw std::runtime_error("from the post-routing handler");
  4760. }
  4761. });
  4762. auto port = svr.bind_to_any_port(HOST);
  4763. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4764. auto se = detail::scope_exit([&] {
  4765. svr.stop();
  4766. listen_thread.join();
  4767. ASSERT_FALSE(svr.is_running());
  4768. });
  4769. svr.wait_until_ready();
  4770. {
  4771. Client cli(HOST, port);
  4772. cli.set_read_timeout(5, 0);
  4773. EXPECT_FALSE(cli.Get("/hi"));
  4774. }
  4775. EXPECT_TRUE(svr.is_running());
  4776. should_throw = false;
  4777. {
  4778. Client cli(HOST, port);
  4779. auto res = cli.Get("/hi");
  4780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4781. EXPECT_EQ(StatusCode::OK_200, res->status);
  4782. EXPECT_EQ("hi", res->body);
  4783. }
  4784. }
  4785. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4786. // The guard reports the caught exception through the error logger, which is
  4787. // a user callback too. A logger that throws has to be contained as well, or
  4788. // the process would terminate from inside the catch.
  4789. Server svr;
  4790. svr.new_task_queue = [] { return new ThreadPool(1); };
  4791. std::atomic<int> reported{0};
  4792. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4793. if (err == Error::UserCallbackException) {
  4794. reported++;
  4795. throw std::runtime_error("from the error logger");
  4796. }
  4797. });
  4798. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4799. res.set_content_provider(
  4800. 1024, "text/plain",
  4801. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4802. sink.write("hello", 5);
  4803. throw std::runtime_error("from the content provider");
  4804. });
  4805. });
  4806. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4807. res.set_content("ok", "text/plain");
  4808. });
  4809. auto port = svr.bind_to_any_port(HOST);
  4810. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4811. auto se = detail::scope_exit([&] {
  4812. svr.stop();
  4813. listen_thread.join();
  4814. ASSERT_FALSE(svr.is_running());
  4815. });
  4816. svr.wait_until_ready();
  4817. {
  4818. Client cli(HOST, port);
  4819. cli.set_read_timeout(5, 0);
  4820. EXPECT_FALSE(cli.Get("/throw"));
  4821. }
  4822. EXPECT_TRUE(svr.is_running());
  4823. EXPECT_EQ(1, reported.load());
  4824. {
  4825. Client cli(HOST, port);
  4826. auto res = cli.Get("/ok");
  4827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4828. EXPECT_EQ(StatusCode::OK_200, res->status);
  4829. EXPECT_EQ("ok", res->body);
  4830. }
  4831. }
  4832. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4833. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4834. // so the exception unwinds through the ws::WebSocket object on its way to
  4835. // the guard. None of the HTTP cases above cross that.
  4836. Server svr;
  4837. svr.new_task_queue = [] { return new ThreadPool(1); };
  4838. std::atomic<int> reported{0};
  4839. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4840. if (err == Error::UserCallbackException) { reported++; }
  4841. });
  4842. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4843. throw std::runtime_error("from the WebSocket handler");
  4844. });
  4845. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4846. res.set_content("ok", "text/plain");
  4847. });
  4848. auto port = svr.bind_to_any_port(HOST);
  4849. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4850. auto se = detail::scope_exit([&] {
  4851. svr.stop();
  4852. listen_thread.join();
  4853. ASSERT_FALSE(svr.is_running());
  4854. });
  4855. svr.wait_until_ready();
  4856. {
  4857. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4858. "/ws");
  4859. auto res = client.connect();
  4860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4861. // The server dropped the connection instead of dying.
  4862. std::string msg;
  4863. EXPECT_FALSE(client.read(msg));
  4864. client.close();
  4865. }
  4866. EXPECT_TRUE(svr.is_running());
  4867. EXPECT_EQ(1, reported.load());
  4868. {
  4869. Client cli(HOST, port);
  4870. auto res = cli.Get("/ok");
  4871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4872. EXPECT_EQ(StatusCode::OK_200, res->status);
  4873. EXPECT_EQ("ok", res->body);
  4874. }
  4875. }
  4876. #ifdef CPPHTTPLIB_SSL_ENABLED
  4877. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4878. // SSLServer::process_and_close_socket() is a separate overload with its own
  4879. // guard, so it is exercised on its own.
  4880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4881. ASSERT_TRUE(svr.is_valid());
  4882. svr.new_task_queue = [] { return new ThreadPool(1); };
  4883. std::atomic<int> reported{0};
  4884. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4885. if (err == Error::UserCallbackException) { reported++; }
  4886. });
  4887. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4888. res.set_content_provider(
  4889. 1024, "text/plain",
  4890. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4891. sink.write("hello", 5);
  4892. throw std::runtime_error("from the content provider");
  4893. });
  4894. });
  4895. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4896. res.set_content("ok", "text/plain");
  4897. });
  4898. auto port = svr.bind_to_any_port(HOST);
  4899. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4900. auto se = detail::scope_exit([&] {
  4901. svr.stop();
  4902. listen_thread.join();
  4903. ASSERT_FALSE(svr.is_running());
  4904. });
  4905. svr.wait_until_ready();
  4906. {
  4907. SSLClient cli(HOST, port);
  4908. cli.enable_server_certificate_verification(false);
  4909. cli.set_read_timeout(5, 0);
  4910. EXPECT_FALSE(cli.Get("/throw"));
  4911. }
  4912. EXPECT_TRUE(svr.is_running());
  4913. EXPECT_EQ(1, reported.load());
  4914. {
  4915. SSLClient cli(HOST, port);
  4916. cli.enable_server_certificate_verification(false);
  4917. auto res = cli.Get("/ok");
  4918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4919. EXPECT_EQ(StatusCode::OK_200, res->status);
  4920. EXPECT_EQ("ok", res->body);
  4921. }
  4922. }
  4923. #endif
  4924. #endif
  4925. TEST(NoContentTest, ContentLength) {
  4926. Server svr;
  4927. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4928. res.status = StatusCode::NoContent_204;
  4929. });
  4930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4931. auto se = detail::scope_exit([&] {
  4932. svr.stop();
  4933. thread.join();
  4934. ASSERT_FALSE(svr.is_running());
  4935. });
  4936. svr.wait_until_ready();
  4937. {
  4938. Client cli(HOST, PORT);
  4939. auto res = cli.Get("/hi");
  4940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4941. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4942. // RFC 9110 8.6: none in a 204 response
  4943. EXPECT_FALSE(res->has_header("Content-Length"));
  4944. }
  4945. }
  4946. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4947. Server svr;
  4948. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4949. res.set_header("Content-Length", "5");
  4950. res.set_content("hello world", "text/plain");
  4951. });
  4952. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4953. // A body that reads as the last chunk, were it taken as chunked
  4954. res.set_header("Transfer-Encoding", "chunked");
  4955. res.set_content("0\r\n\r\n", "text/plain");
  4956. });
  4957. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4958. res.set_header("Content-Length", "2");
  4959. res.set_content_provider(5, "text/plain",
  4960. [](size_t offset, size_t length, DataSink &sink) {
  4961. sink.write(&"hello"[offset], length);
  4962. return true;
  4963. });
  4964. });
  4965. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4966. res.set_header("Content-Length", "1234");
  4967. });
  4968. thread t = thread([&] { svr.listen(HOST, PORT); });
  4969. auto se = detail::scope_exit([&] {
  4970. svr.stop();
  4971. t.join();
  4972. ASSERT_FALSE(svr.is_running());
  4973. });
  4974. svr.wait_until_ready();
  4975. Client cli(HOST, PORT);
  4976. cli.set_read_timeout(1, 0);
  4977. auto expect_body = [&](const Result &res, const std::string &body) {
  4978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4979. EXPECT_EQ(body, res->body);
  4980. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4981. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4982. };
  4983. Headers identity{{"Accept-Encoding", ""}};
  4984. expect_body(cli.Get("/body", identity), "hello world");
  4985. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4986. expect_body(cli.Get("/body",
  4987. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4988. "he");
  4989. expect_body(cli.Get("/provider", identity), "hello");
  4990. expect_body(cli.Get("/empty", identity), "");
  4991. // A HEAD response may give the length of the body a GET would get.
  4992. auto res = cli.Head("/empty");
  4993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4994. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4995. }
  4996. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4997. Server svr;
  4998. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4999. res.set_content("short", "text/plain");
  5000. });
  5001. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5002. res.body += " with a footer";
  5003. res.set_header("Transfer-Encoding", "chunked");
  5004. });
  5005. thread t = thread([&] { svr.listen(HOST, PORT); });
  5006. auto se = detail::scope_exit([&] {
  5007. svr.stop();
  5008. t.join();
  5009. ASSERT_FALSE(svr.is_running());
  5010. });
  5011. svr.wait_until_ready();
  5012. Client cli(HOST, PORT);
  5013. cli.set_read_timeout(1, 0);
  5014. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5016. EXPECT_EQ("short with a footer", res->body);
  5017. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5018. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5019. }
  5020. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5021. Server svr;
  5022. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5023. res.set_header("Content-Length", "3");
  5024. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5025. sink.write("abc", 3);
  5026. sink.done();
  5027. return true;
  5028. });
  5029. });
  5030. thread t = thread([&] { svr.listen(HOST, PORT); });
  5031. auto se = detail::scope_exit([&] {
  5032. svr.stop();
  5033. t.join();
  5034. ASSERT_FALSE(svr.is_running());
  5035. });
  5036. svr.wait_until_ready();
  5037. Client cli(HOST, PORT);
  5038. cli.set_keep_alive(true);
  5039. auto res = cli.Get("/");
  5040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5041. EXPECT_EQ("abc", res->body);
  5042. EXPECT_FALSE(res->has_header("Content-Length"));
  5043. EXPECT_EQ("close", res->get_header_value("Connection"));
  5044. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5045. // No body to delimit
  5046. auto head = cli.Head("/");
  5047. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5048. EXPECT_FALSE(head->has_header("Connection"));
  5049. }
  5050. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5051. #ifdef CPPHTTPLIB_SSL_ENABLED
  5052. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5053. ASSERT_TRUE(svr.is_valid());
  5054. #else
  5055. Server svr;
  5056. #endif
  5057. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5058. if (req.path == "/routing_handler") {
  5059. res.set_header("PRE_ROUTING", "on");
  5060. res.set_content("Routing Handler", "text/plain");
  5061. return httplib::Server::HandlerResponse::Handled;
  5062. }
  5063. return httplib::Server::HandlerResponse::Unhandled;
  5064. });
  5065. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5066. res.set_content("Error", "text/html");
  5067. });
  5068. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5069. if (req.path == "/routing_handler") {
  5070. res.set_header("POST_ROUTING", "on");
  5071. }
  5072. });
  5073. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5074. res.set_content("Hello World!\n", "text/plain");
  5075. });
  5076. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5077. auto se = detail::scope_exit([&] {
  5078. svr.stop();
  5079. thread.join();
  5080. ASSERT_FALSE(svr.is_running());
  5081. });
  5082. svr.wait_until_ready();
  5083. {
  5084. #ifdef CPPHTTPLIB_SSL_ENABLED
  5085. SSLClient cli(HOST, PORT);
  5086. cli.enable_server_certificate_verification(false);
  5087. #else
  5088. Client cli(HOST, PORT);
  5089. #endif
  5090. auto res = cli.Get("/routing_handler");
  5091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5092. EXPECT_EQ(StatusCode::OK_200, res->status);
  5093. EXPECT_EQ("Routing Handler", res->body);
  5094. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5095. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5096. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5097. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5098. }
  5099. {
  5100. #ifdef CPPHTTPLIB_SSL_ENABLED
  5101. SSLClient cli(HOST, PORT);
  5102. cli.enable_server_certificate_verification(false);
  5103. #else
  5104. Client cli(HOST, PORT);
  5105. #endif
  5106. auto res = cli.Get("/hi");
  5107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5108. EXPECT_EQ(StatusCode::OK_200, res->status);
  5109. EXPECT_EQ("Hello World!\n", res->body);
  5110. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5111. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5112. }
  5113. {
  5114. #ifdef CPPHTTPLIB_SSL_ENABLED
  5115. SSLClient cli(HOST, PORT);
  5116. cli.enable_server_certificate_verification(false);
  5117. #else
  5118. Client cli(HOST, PORT);
  5119. #endif
  5120. auto res = cli.Get("/aaa");
  5121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5123. EXPECT_EQ("Error", res->body);
  5124. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5125. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5126. }
  5127. }
  5128. TEST(RequestHandlerTest, PreRequestHandler) {
  5129. auto route_path = "/user/:user";
  5130. Server svr;
  5131. svr.Get("/hi", [](const Request &, Response &res) {
  5132. res.set_content("hi", "text/plain");
  5133. });
  5134. svr.Get(route_path, [](const Request &req, Response &res) {
  5135. res.set_content(req.path_params.at("user"), "text/plain");
  5136. });
  5137. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5138. if (req.matched_route == route_path) {
  5139. auto user = req.path_params.at("user");
  5140. if (user != "john") {
  5141. res.status = StatusCode::Forbidden_403;
  5142. res.set_content("error", "text/html");
  5143. return Server::HandlerResponse::Handled;
  5144. }
  5145. }
  5146. return Server::HandlerResponse::Unhandled;
  5147. });
  5148. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5149. auto se = detail::scope_exit([&] {
  5150. svr.stop();
  5151. thread.join();
  5152. ASSERT_FALSE(svr.is_running());
  5153. });
  5154. svr.wait_until_ready();
  5155. Client cli(HOST, PORT);
  5156. {
  5157. auto res = cli.Get("/hi");
  5158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5159. EXPECT_EQ(StatusCode::OK_200, res->status);
  5160. EXPECT_EQ("hi", res->body);
  5161. }
  5162. {
  5163. auto res = cli.Get("/user/john");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. EXPECT_EQ("john", res->body);
  5167. }
  5168. {
  5169. auto res = cli.Get("/user/invalid-user");
  5170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5171. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5172. EXPECT_EQ("error", res->body);
  5173. }
  5174. }
  5175. // The pre-request handler must run before the request body is read, so a
  5176. // rejected request never forces the server to buffer a (potentially large)
  5177. // body. Here the posted body is larger than the payload limit: if the body
  5178. // were read first the server would answer 413, but because the pre-request
  5179. // handler runs first it answers 403 and the body is never read.
  5180. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5181. Server svr;
  5182. svr.set_payload_max_length(8);
  5183. auto handler_ran = false;
  5184. svr.Post("/reject", [&](const Request &req, Response &res) {
  5185. handler_ran = true;
  5186. res.set_content(req.body, "text/plain");
  5187. });
  5188. svr.Post("/accept", [](const Request &req, Response &res) {
  5189. res.set_content(req.body, "text/plain");
  5190. });
  5191. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5192. if (req.matched_route == "/reject") {
  5193. res.status = StatusCode::Forbidden_403;
  5194. res.set_content("denied", "text/plain");
  5195. return Server::HandlerResponse::Handled;
  5196. }
  5197. return Server::HandlerResponse::Unhandled;
  5198. });
  5199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5200. auto se = detail::scope_exit([&] {
  5201. svr.stop();
  5202. thread.join();
  5203. ASSERT_FALSE(svr.is_running());
  5204. });
  5205. svr.wait_until_ready();
  5206. Client cli(HOST, PORT);
  5207. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5208. // rejects with 403 before the body is read, so 413 is never reached.
  5209. {
  5210. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5212. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5213. EXPECT_EQ("denied", res->body);
  5214. EXPECT_FALSE(handler_ran);
  5215. }
  5216. // An approved route still reads the body and enforces the payload limit.
  5217. {
  5218. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5220. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5221. }
  5222. }
  5223. TEST(UserDataTest, BasicOperations) {
  5224. httplib::UserData ud;
  5225. // Initially empty
  5226. EXPECT_FALSE(ud.has("key"));
  5227. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5228. // set and get
  5229. ud.set("key", 42);
  5230. EXPECT_TRUE(ud.has("key"));
  5231. auto *p = ud.get<int>("key");
  5232. ASSERT_NE(nullptr, p);
  5233. EXPECT_EQ(42, *p);
  5234. // Type mismatch → nullptr
  5235. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5236. // Overwrite with different type
  5237. ud.set("key", std::string("hello"));
  5238. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5239. auto *s = ud.get<std::string>("key");
  5240. ASSERT_NE(nullptr, s);
  5241. EXPECT_EQ("hello", *s);
  5242. // erase
  5243. ud.erase("key");
  5244. EXPECT_FALSE(ud.has("key"));
  5245. // clear
  5246. ud.set("a", 1);
  5247. ud.set("b", 2);
  5248. ud.clear();
  5249. EXPECT_FALSE(ud.has("a"));
  5250. EXPECT_FALSE(ud.has("b"));
  5251. }
  5252. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5253. struct AuthCtx {
  5254. std::string user_id;
  5255. };
  5256. Server svr;
  5257. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5258. res.user_data.set("auth", AuthCtx{"alice"});
  5259. return Server::HandlerResponse::Unhandled;
  5260. });
  5261. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5262. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5263. ASSERT_NE(nullptr, ctx);
  5264. res.set_content("Hello " + ctx->user_id, "text/plain");
  5265. });
  5266. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5267. auto se = detail::scope_exit([&] {
  5268. svr.stop();
  5269. thread.join();
  5270. ASSERT_FALSE(svr.is_running());
  5271. });
  5272. svr.wait_until_ready();
  5273. Client cli(HOST, PORT);
  5274. auto res = cli.Get("/me");
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. EXPECT_EQ(StatusCode::OK_200, res->status);
  5277. EXPECT_EQ("Hello alice", res->body);
  5278. }
  5279. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5280. struct RoleCtx {
  5281. std::string role;
  5282. };
  5283. Server svr;
  5284. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5285. res.user_data.set("role", RoleCtx{"admin"});
  5286. return Server::HandlerResponse::Unhandled;
  5287. });
  5288. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5289. auto *ctx = res.user_data.get<RoleCtx>("role");
  5290. ASSERT_NE(nullptr, ctx);
  5291. res.set_content(ctx->role, "text/plain");
  5292. });
  5293. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5294. auto se = detail::scope_exit([&] {
  5295. svr.stop();
  5296. thread.join();
  5297. ASSERT_FALSE(svr.is_running());
  5298. });
  5299. svr.wait_until_ready();
  5300. Client cli(HOST, PORT);
  5301. auto res = cli.Get("/role");
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. EXPECT_EQ(StatusCode::OK_200, res->status);
  5304. EXPECT_EQ("admin", res->body);
  5305. }
  5306. TEST(InvalidFormatTest, StatusCode) {
  5307. Server svr;
  5308. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5309. res.set_content("Hello World!\n", "text/plain");
  5310. res.status = 9999; // Status should be a three-digit code...
  5311. });
  5312. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5313. auto se = detail::scope_exit([&] {
  5314. svr.stop();
  5315. thread.join();
  5316. ASSERT_FALSE(svr.is_running());
  5317. });
  5318. svr.wait_until_ready();
  5319. {
  5320. Client cli(HOST, PORT);
  5321. auto res = cli.Get("/hi");
  5322. ASSERT_FALSE(res);
  5323. }
  5324. }
  5325. TEST(URLFragmentTest, WithFragment) {
  5326. Server svr;
  5327. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5328. EXPECT_TRUE(req.target == "/hi");
  5329. });
  5330. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5331. auto se = detail::scope_exit([&] {
  5332. svr.stop();
  5333. thread.join();
  5334. ASSERT_FALSE(svr.is_running());
  5335. });
  5336. svr.wait_until_ready();
  5337. {
  5338. Client cli(HOST, PORT);
  5339. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5340. EXPECT_TRUE(res);
  5341. EXPECT_EQ(StatusCode::OK_200, res->status);
  5342. res = cli.Get("/hi%23key1=val1=key2=val2");
  5343. EXPECT_TRUE(res);
  5344. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5345. }
  5346. }
  5347. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5348. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5349. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5350. Server svr;
  5351. std::vector<std::string> targets;
  5352. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5353. targets.push_back(req.target);
  5354. });
  5355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5356. auto se = detail::scope_exit([&] {
  5357. svr.stop();
  5358. thread.join();
  5359. ASSERT_FALSE(svr.is_running());
  5360. });
  5361. svr.wait_until_ready();
  5362. Client cli(HOST, PORT);
  5363. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5364. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5365. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5366. // A '?' after the '#' belongs to the fragment, not to the query.
  5367. Request req;
  5368. req.method = "GET";
  5369. req.path = "/hi#f?x=1";
  5370. req.params.emplace("a", "1");
  5371. Response res;
  5372. auto error = Error::Success;
  5373. EXPECT_TRUE(cli.send(req, res, error));
  5374. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5375. "/hi?a=1"}),
  5376. targets);
  5377. }
  5378. TEST(HeaderWriter, SetHeaderWriter) {
  5379. Server svr;
  5380. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5381. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5382. return detail::write_headers(strm, hdrs);
  5383. });
  5384. svr.Get("/hi", [](const Request &req, Response &res) {
  5385. auto it = req.headers.find("CustomClientHeader");
  5386. EXPECT_TRUE(it != req.headers.end());
  5387. EXPECT_EQ(it->second, "CustomClientValue");
  5388. res.set_content("Hello World!\n", "text/plain");
  5389. });
  5390. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5391. auto se = detail::scope_exit([&] {
  5392. svr.stop();
  5393. thread.join();
  5394. ASSERT_FALSE(svr.is_running());
  5395. });
  5396. svr.wait_until_ready();
  5397. {
  5398. Client cli(HOST, PORT);
  5399. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5400. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5401. return detail::write_headers(strm, hdrs);
  5402. });
  5403. auto res = cli.Get("/hi");
  5404. EXPECT_TRUE(res);
  5405. EXPECT_EQ(StatusCode::OK_200, res->status);
  5406. auto it = res->headers.find("CustomServerHeader");
  5407. EXPECT_TRUE(it != res->headers.end());
  5408. EXPECT_EQ(it->second, "CustomServerValue");
  5409. }
  5410. }
  5411. class ServerTest : public ::testing::Test {
  5412. protected:
  5413. ServerTest()
  5414. : cli_(HOST, PORT)
  5415. #ifdef CPPHTTPLIB_SSL_ENABLED
  5416. ,
  5417. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5418. #endif
  5419. {
  5420. #ifdef CPPHTTPLIB_SSL_ENABLED
  5421. cli_.enable_server_certificate_verification(false);
  5422. #endif
  5423. // Allow LARGE_DATA (100MB) responses
  5424. cli_.set_payload_max_length(200 * 1024 * 1024);
  5425. }
  5426. virtual void SetUp() {
  5427. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5428. svr_.set_payload_max_length(200 * 1024 * 1024);
  5429. svr_.set_mount_point("/", "./www");
  5430. svr_.set_mount_point("/mount", "./www2");
  5431. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5432. svr_.Get("/hi",
  5433. [&](const Request & /*req*/, Response &res) {
  5434. res.set_content("Hello World!", "text/plain");
  5435. })
  5436. .Get("/file_content",
  5437. [&](const Request & /*req*/, Response &res) {
  5438. res.set_file_content("./www/dir/test.html");
  5439. })
  5440. .Get("/file_content_with_content_type",
  5441. [&](const Request & /*req*/, Response &res) {
  5442. res.set_file_content("./www/file", "text/plain");
  5443. })
  5444. .Get("/invalid_file_content",
  5445. [&](const Request & /*req*/, Response &res) {
  5446. res.set_file_content("./www/dir/invalid_file_path");
  5447. })
  5448. .Get("/http_response_splitting",
  5449. [&](const Request & /*req*/, Response &res) {
  5450. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5451. EXPECT_EQ(0U, res.headers.size());
  5452. EXPECT_FALSE(res.has_header("a"));
  5453. res.set_header("a", "1\nSet-Cookie: a=1");
  5454. EXPECT_EQ(0U, res.headers.size());
  5455. EXPECT_FALSE(res.has_header("a"));
  5456. res.set_header("a", "1\rSet-Cookie: a=1");
  5457. EXPECT_EQ(0U, res.headers.size());
  5458. EXPECT_FALSE(res.has_header("a"));
  5459. res.set_header("a\r\nb", "0");
  5460. EXPECT_EQ(0U, res.headers.size());
  5461. EXPECT_FALSE(res.has_header("a"));
  5462. res.set_header("a\rb", "0");
  5463. EXPECT_EQ(0U, res.headers.size());
  5464. EXPECT_FALSE(res.has_header("a"));
  5465. res.set_header("a\nb", "0");
  5466. EXPECT_EQ(0U, res.headers.size());
  5467. EXPECT_FALSE(res.has_header("a"));
  5468. res.set_redirect("1\r\nSet-Cookie: a=1");
  5469. EXPECT_EQ(0U, res.headers.size());
  5470. EXPECT_FALSE(res.has_header("Location"));
  5471. })
  5472. .Get("/slow",
  5473. [&](const Request & /*req*/, Response &res) {
  5474. std::this_thread::sleep_for(std::chrono::seconds(4));
  5475. res.set_content("slow", "text/plain");
  5476. })
  5477. #if 0
  5478. .Post("/slowpost",
  5479. [&](const Request & /*req*/, Response &res) {
  5480. std::this_thread::sleep_for(std::chrono::seconds(2));
  5481. res.set_content("slow", "text/plain");
  5482. })
  5483. #endif
  5484. .Get("/remote_addr",
  5485. [&](const Request &req, Response &res) {
  5486. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5487. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5488. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5489. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5490. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5491. #endif
  5492. res.set_content(req.remote_addr, "text/plain");
  5493. })
  5494. .Get("/local_addr",
  5495. [&](const Request &req, Response &res) {
  5496. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5497. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5498. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5499. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5500. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5501. #endif
  5502. auto local_addr = req.local_addr;
  5503. auto local_port = std::to_string(req.local_port);
  5504. res.set_content(local_addr.append(":").append(local_port),
  5505. "text/plain");
  5506. })
  5507. .Get("/endwith%",
  5508. [&](const Request & /*req*/, Response &res) {
  5509. res.set_content("Hello World!", "text/plain");
  5510. })
  5511. .Get("/a\\+\\+b",
  5512. [&](const Request &req, Response &res) {
  5513. ASSERT_TRUE(req.has_param("a +b"));
  5514. auto val = req.get_param_value("a +b");
  5515. res.set_content(val, "text/plain");
  5516. })
  5517. .Get("/", [&](const Request & /*req*/,
  5518. Response &res) { res.set_redirect("/hi"); })
  5519. .Post("/1",
  5520. [](const Request & /*req*/, Response &res) {
  5521. res.set_redirect("/2", StatusCode::SeeOther_303);
  5522. })
  5523. .Get("/2",
  5524. [](const Request & /*req*/, Response &res) {
  5525. res.set_content("redirected.", "text/plain");
  5526. res.status = StatusCode::OK_200;
  5527. })
  5528. .Post("/person",
  5529. [&](const Request &req, Response &res) {
  5530. if (req.has_param("name") && req.has_param("note")) {
  5531. persons_[req.get_param_value("name")] =
  5532. req.get_param_value("note");
  5533. } else {
  5534. res.status = StatusCode::BadRequest_400;
  5535. }
  5536. })
  5537. .Put("/person",
  5538. [&](const Request &req, Response &res) {
  5539. if (req.has_param("name") && req.has_param("note")) {
  5540. persons_[req.get_param_value("name")] =
  5541. req.get_param_value("note");
  5542. } else {
  5543. res.status = StatusCode::BadRequest_400;
  5544. }
  5545. })
  5546. .Get("/person/(.*)",
  5547. [&](const Request &req, Response &res) {
  5548. string name = req.matches[1];
  5549. if (persons_.find(name) != persons_.end()) {
  5550. auto note = persons_[name];
  5551. res.set_content(note, "text/plain");
  5552. } else {
  5553. res.status = StatusCode::NotFound_404;
  5554. }
  5555. })
  5556. .Delete("/person",
  5557. [&](const Request &req, Response &res) {
  5558. if (req.has_param("name")) {
  5559. string name = req.get_param_value("name");
  5560. if (persons_.find(name) != persons_.end()) {
  5561. persons_.erase(name);
  5562. res.set_content("DELETED", "text/plain");
  5563. } else {
  5564. res.status = StatusCode::NotFound_404;
  5565. }
  5566. } else {
  5567. res.status = StatusCode::BadRequest_400;
  5568. }
  5569. })
  5570. .Post("/x-www-form-urlencoded-json",
  5571. [&](const Request &req, Response &res) {
  5572. auto json = req.get_param_value("json");
  5573. ASSERT_EQ(JSON_DATA, json);
  5574. res.set_content(json, "appliation/json");
  5575. res.status = StatusCode::OK_200;
  5576. })
  5577. .Get("/streamed-chunked",
  5578. [&](const Request & /*req*/, Response &res) {
  5579. res.set_chunked_content_provider(
  5580. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5581. sink.os << "123";
  5582. sink.os << "456";
  5583. sink.os << "789";
  5584. sink.done();
  5585. return true;
  5586. });
  5587. })
  5588. .Get("/streamed-chunked-with-prohibited-trailer",
  5589. [&](const Request & /*req*/, Response &res) {
  5590. auto i = new int(0);
  5591. // Declare both a prohibited trailer (Content-Length) and an
  5592. // allowed one
  5593. res.set_header("Trailer", "Content-Length, X-Allowed");
  5594. res.set_chunked_content_provider(
  5595. "text/plain",
  5596. [i](size_t /*offset*/, DataSink &sink) {
  5597. switch (*i) {
  5598. case 0: sink.os << "123"; break;
  5599. case 1: sink.os << "456"; break;
  5600. case 2: sink.os << "789"; break;
  5601. case 3: {
  5602. sink.done_with_trailer(
  5603. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5604. } break;
  5605. }
  5606. (*i)++;
  5607. return true;
  5608. },
  5609. [i](bool success) {
  5610. EXPECT_TRUE(success);
  5611. delete i;
  5612. });
  5613. })
  5614. .Get("/streamed-chunked2",
  5615. [&](const Request & /*req*/, Response &res) {
  5616. auto i = new int(0);
  5617. res.set_chunked_content_provider(
  5618. "text/plain",
  5619. [i](size_t /*offset*/, DataSink &sink) {
  5620. switch (*i) {
  5621. case 0: sink.os << "123"; break;
  5622. case 1: sink.os << "456"; break;
  5623. case 2: sink.os << "789"; break;
  5624. case 3: sink.done(); break;
  5625. }
  5626. (*i)++;
  5627. return true;
  5628. },
  5629. [i](bool success) {
  5630. EXPECT_TRUE(success);
  5631. delete i;
  5632. });
  5633. })
  5634. .Get("/streamed-chunked-with-trailer",
  5635. [&](const Request & /*req*/, Response &res) {
  5636. auto i = new int(0);
  5637. res.set_header("Trailer", "Dummy1, Dummy2");
  5638. res.set_chunked_content_provider(
  5639. "text/plain",
  5640. [i](size_t /*offset*/, DataSink &sink) {
  5641. switch (*i) {
  5642. case 0: sink.os << "123"; break;
  5643. case 1: sink.os << "456"; break;
  5644. case 2: sink.os << "789"; break;
  5645. case 3: {
  5646. sink.done_with_trailer(
  5647. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5648. } break;
  5649. }
  5650. (*i)++;
  5651. return true;
  5652. },
  5653. [i](bool success) {
  5654. EXPECT_TRUE(success);
  5655. delete i;
  5656. });
  5657. })
  5658. .Get("/streamed",
  5659. [&](const Request & /*req*/, Response &res) {
  5660. res.set_content_provider(
  5661. 6, "text/plain",
  5662. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5663. sink.os << (offset < 3 ? "a" : "b");
  5664. return true;
  5665. });
  5666. })
  5667. .Get("/streamed-without-length",
  5668. [&](const Request & /*req*/, Response &res) {
  5669. auto data = new std::string("abcdefg");
  5670. res.set_content_provider(
  5671. "text/plain",
  5672. [data](size_t offset, DataSink &sink) {
  5673. if (offset < data->size()) {
  5674. sink.os << data->substr(offset);
  5675. }
  5676. sink.done();
  5677. return true;
  5678. },
  5679. [data](bool success) {
  5680. EXPECT_TRUE(success);
  5681. delete data;
  5682. });
  5683. })
  5684. .Get("/streamed-with-range",
  5685. [&](const Request &req, Response &res) {
  5686. auto data = new std::string("abcdefg");
  5687. // An explicit status keeps the server from picking the 206 it
  5688. // would otherwise choose for a ranged request, so the response
  5689. // is not a partial representation.
  5690. auto status = req.get_param_value("status");
  5691. if (status == "200") {
  5692. res.status = StatusCode::OK_200;
  5693. } else if (status == "403") {
  5694. res.status = StatusCode::Forbidden_403;
  5695. }
  5696. res.set_content_provider(
  5697. data->size(), "text/plain",
  5698. [data](size_t offset, size_t length, DataSink &sink) {
  5699. size_t DATA_CHUNK_SIZE = 4;
  5700. const auto &d = *data;
  5701. auto out_len =
  5702. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5703. auto ret =
  5704. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5705. EXPECT_TRUE(ret);
  5706. return true;
  5707. },
  5708. [data, &req](bool success) {
  5709. EXPECT_EQ(success, !req.has_param("error"));
  5710. delete data;
  5711. });
  5712. })
  5713. .Get("/streamed-cancel",
  5714. [&](const Request & /*req*/, Response &res) {
  5715. res.set_content_provider(
  5716. size_t(-1), "text/plain",
  5717. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5718. sink.os << "data_chunk";
  5719. return true;
  5720. });
  5721. })
  5722. .Get("/regex-with-delimiter",
  5723. [&](const Request &req, Response & /*res*/) {
  5724. ASSERT_TRUE(req.has_param("key"));
  5725. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5726. })
  5727. .Get("/with-range",
  5728. [&](const Request & /*req*/, Response &res) {
  5729. res.set_content("abcdefg", "text/plain");
  5730. })
  5731. .Get("/test-start-time",
  5732. [&](const Request &req, Response & /*res*/) {
  5733. EXPECT_NE(req.start_time_,
  5734. std::chrono::steady_clock::time_point::min());
  5735. })
  5736. .Get("/with-range-customized-response",
  5737. [&](const Request & /*req*/, Response &res) {
  5738. res.status = StatusCode::BadRequest_400;
  5739. res.set_content(JSON_DATA, "application/json");
  5740. })
  5741. .Post("/chunked",
  5742. [&](const Request &req, Response & /*res*/) {
  5743. EXPECT_EQ(req.body, "dechunked post body");
  5744. })
  5745. .Post("/large-chunked",
  5746. [&](const Request &req, Response & /*res*/) {
  5747. std::string expected(6 * 30 * 1024u, 'a');
  5748. EXPECT_EQ(req.body, expected);
  5749. })
  5750. .Post("/multipart",
  5751. [&](const Request &req, Response & /*res*/) {
  5752. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5753. req.form.get_field_count("text2") +
  5754. req.form.get_field_count("file3") +
  5755. req.form.get_field_count("file4"));
  5756. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5757. req.form.get_file_count("file2"));
  5758. ASSERT_TRUE(!req.form.has_file("???"));
  5759. ASSERT_TRUE(!req.form.has_field("???"));
  5760. ASSERT_TRUE(req.body.empty());
  5761. {
  5762. const auto &text = req.form.get_field("text1");
  5763. EXPECT_EQ("text default", text);
  5764. }
  5765. {
  5766. const auto &text = req.form.get_field("text2");
  5767. EXPECT_EQ("aωb", text);
  5768. }
  5769. {
  5770. const auto &file = req.form.get_file("file1");
  5771. EXPECT_EQ("hello.txt", file.filename);
  5772. EXPECT_EQ("text/plain", file.content_type);
  5773. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5774. }
  5775. {
  5776. const auto &file = req.form.get_file("file2");
  5777. EXPECT_EQ("world.json", file.filename);
  5778. EXPECT_EQ("application/json", file.content_type);
  5779. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5780. }
  5781. {
  5782. const auto &text = req.form.get_field("file3");
  5783. EXPECT_EQ(0u, text.size());
  5784. }
  5785. {
  5786. const auto &text = req.form.get_field("file4");
  5787. EXPECT_EQ(0u, text.size());
  5788. }
  5789. })
  5790. .Post("/multipart/multi_file_values",
  5791. [&](const Request &req, Response & /*res*/) {
  5792. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5793. req.form.get_field_count("multi_text1"));
  5794. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5795. ASSERT_TRUE(!req.form.has_file("???"));
  5796. ASSERT_TRUE(!req.form.has_field("???"));
  5797. ASSERT_TRUE(req.body.empty());
  5798. {
  5799. const auto &text = req.form.get_field("text");
  5800. EXPECT_EQ("default text", text);
  5801. }
  5802. {
  5803. const auto &text1_values = req.form.get_fields("multi_text1");
  5804. EXPECT_EQ(2u, text1_values.size());
  5805. EXPECT_EQ("aaaaa", text1_values[0]);
  5806. EXPECT_EQ("bbbbb", text1_values[1]);
  5807. }
  5808. {
  5809. const auto &file1_values = req.form.get_files("multi_file1");
  5810. EXPECT_EQ(2u, file1_values.size());
  5811. auto file1 = file1_values[0];
  5812. EXPECT_EQ(file1.filename, "hello.txt");
  5813. EXPECT_EQ(file1.content_type, "text/plain");
  5814. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5815. auto file2 = file1_values[1];
  5816. EXPECT_EQ(file2.filename, "world.json");
  5817. EXPECT_EQ(file2.content_type, "application/json");
  5818. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5819. }
  5820. })
  5821. .Post("/empty",
  5822. [&](const Request &req, Response &res) {
  5823. EXPECT_EQ(req.body, "");
  5824. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5825. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5826. res.set_content("empty", "text/plain");
  5827. })
  5828. .Post("/empty-no-content-type",
  5829. [&](const Request &req, Response &res) {
  5830. EXPECT_EQ(req.body, "");
  5831. EXPECT_FALSE(req.has_header("Content-Type"));
  5832. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5833. res.set_content("empty-no-content-type", "text/plain");
  5834. })
  5835. .Post("/path-only",
  5836. [&](const Request &req, Response &res) {
  5837. EXPECT_EQ(req.body, "");
  5838. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5839. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5840. res.set_content("path-only", "text/plain");
  5841. })
  5842. .Post("/path-headers-only",
  5843. [&](const Request &req, Response &res) {
  5844. EXPECT_EQ(req.body, "");
  5845. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5846. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5847. EXPECT_EQ("world", req.get_header_value("hello"));
  5848. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5849. res.set_content("path-headers-only", "text/plain");
  5850. })
  5851. .Post("/post-large",
  5852. [&](const Request &req, Response &res) {
  5853. EXPECT_EQ(req.body, LARGE_DATA);
  5854. res.set_content(req.body, "text/plain");
  5855. })
  5856. .Post("/post-loopback",
  5857. [&](const Request &, Response &res,
  5858. ContentReader const &content_reader) {
  5859. std::string body;
  5860. content_reader([&](const char *data, size_t data_length) {
  5861. body.append(data, data_length);
  5862. return true;
  5863. });
  5864. res.set_content(body, "text/plain");
  5865. })
  5866. .Put("/put-loopback",
  5867. [&](const Request &, Response &res,
  5868. ContentReader const &content_reader) {
  5869. std::string body;
  5870. content_reader([&](const char *data, size_t data_length) {
  5871. body.append(data, data_length);
  5872. return true;
  5873. });
  5874. res.set_content(body, "text/plain");
  5875. })
  5876. .Patch("/patch-loopback",
  5877. [&](const Request &, Response &res,
  5878. ContentReader const &content_reader) {
  5879. std::string body;
  5880. content_reader([&](const char *data, size_t data_length) {
  5881. body.append(data, data_length);
  5882. return true;
  5883. });
  5884. res.set_content(body, "text/plain");
  5885. })
  5886. .Put("/empty-no-content-type",
  5887. [&](const Request &req, Response &res) {
  5888. EXPECT_EQ(req.body, "");
  5889. EXPECT_FALSE(req.has_header("Content-Type"));
  5890. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5891. res.set_content("empty-no-content-type", "text/plain");
  5892. })
  5893. .Put("/put",
  5894. [&](const Request &req, Response &res) {
  5895. EXPECT_EQ(req.body, "PUT");
  5896. res.set_content(req.body, "text/plain");
  5897. })
  5898. .Put("/put-large",
  5899. [&](const Request &req, Response &res) {
  5900. EXPECT_EQ(req.body, LARGE_DATA);
  5901. res.set_content(req.body, "text/plain");
  5902. })
  5903. .Patch("/patch",
  5904. [&](const Request &req, Response &res) {
  5905. EXPECT_EQ(req.body, "PATCH");
  5906. res.set_content(req.body, "text/plain");
  5907. })
  5908. .Delete("/delete",
  5909. [&](const Request & /*req*/, Response &res) {
  5910. res.set_content("DELETE", "text/plain");
  5911. })
  5912. .Delete("/delete-body",
  5913. [&](const Request &req, Response &res) {
  5914. EXPECT_EQ(req.body, "content");
  5915. res.set_content(req.body, "text/plain");
  5916. })
  5917. .Options(R"(\*)",
  5918. [&](const Request & /*req*/, Response &res) {
  5919. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5920. })
  5921. .CustomRoute("PROPFIND", "/dav/:id",
  5922. [&](const Request &req, Response &res) {
  5923. res.set_header("x-body-size",
  5924. std::to_string(req.body.size()));
  5925. res.set_header("x-matched-route", req.matched_route);
  5926. res.set_header("x-dav-id", req.path_params.at("id"));
  5927. res.status = StatusCode::MultiStatus_207;
  5928. res.set_content(req.body, "application/xml");
  5929. })
  5930. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5931. [&](const Request &req, Response &res) {
  5932. res.set_header("x-dav-match", req.matches[1]);
  5933. res.status = StatusCode::MultiStatus_207;
  5934. })
  5935. .CustomRoute("MKCOL", "/dav-mkcol",
  5936. [&](const Request &req, Response &res) {
  5937. EXPECT_TRUE(req.body.empty());
  5938. res.status = StatusCode::Created_201;
  5939. })
  5940. .CustomRoute(
  5941. "REPORT", "/dav-report",
  5942. [&](const Request & /*req*/, Response &res,
  5943. const ContentReader &content_reader) {
  5944. std::string body;
  5945. content_reader([&](const char *data, size_t data_length) {
  5946. body.append(data, data_length);
  5947. return true;
  5948. });
  5949. res.set_header("x-body-size", std::to_string(body.size()));
  5950. res.status = StatusCode::MultiStatus_207;
  5951. res.set_content(body, "application/xml");
  5952. })
  5953. .Get("/request-target",
  5954. [&](const Request &req, Response & /*res*/) {
  5955. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5956. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5957. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5958. })
  5959. .Get("/long-query-value",
  5960. [&](const Request &req, Response & /*res*/) {
  5961. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5962. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5963. })
  5964. .Get("/too-long-query-value",
  5965. [&](const Request &req, Response & /*res*/) {
  5966. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5967. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5968. })
  5969. .Get("/array-param",
  5970. [&](const Request &req, Response & /*res*/) {
  5971. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5972. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5973. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5974. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5975. })
  5976. .Get("/array-param-values",
  5977. [&](const Request &req, Response & /*res*/) {
  5978. auto values = req.get_param_values("array");
  5979. EXPECT_EQ(3u, values.size());
  5980. EXPECT_EQ("value1", values[0]);
  5981. EXPECT_EQ("value2", values[1]);
  5982. EXPECT_EQ("value3", values[2]);
  5983. auto empty = req.get_param_values("nonexistent");
  5984. EXPECT_TRUE(empty.empty());
  5985. })
  5986. .Post("/validate-no-multiple-headers",
  5987. [&](const Request &req, Response & /*res*/) {
  5988. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5989. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5990. })
  5991. .Post("/content_receiver",
  5992. [&](const Request &req, Response &res,
  5993. const ContentReader &content_reader) {
  5994. if (req.is_multipart_form_data()) {
  5995. std::vector<FormData> items;
  5996. content_reader(
  5997. [&](const FormData &file) {
  5998. items.push_back(file);
  5999. return true;
  6000. },
  6001. [&](const char *data, size_t data_length) {
  6002. items.back().content.append(data, data_length);
  6003. return true;
  6004. });
  6005. EXPECT_EQ(5u, items.size());
  6006. {
  6007. const auto &file = get_file_value(items, "text1");
  6008. EXPECT_TRUE(file.filename.empty());
  6009. EXPECT_EQ("text default", file.content);
  6010. }
  6011. {
  6012. const auto &file = get_file_value(items, "text2");
  6013. EXPECT_TRUE(file.filename.empty());
  6014. EXPECT_EQ("aωb", file.content);
  6015. }
  6016. {
  6017. const auto &file = get_file_value(items, "file1");
  6018. EXPECT_EQ("hello.txt", file.filename);
  6019. EXPECT_EQ("text/plain", file.content_type);
  6020. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6021. }
  6022. {
  6023. const auto &file = get_file_value(items, "file2");
  6024. EXPECT_EQ("world.json", file.filename);
  6025. EXPECT_EQ("application/json", file.content_type);
  6026. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6027. }
  6028. {
  6029. const auto &file = get_file_value(items, "file3");
  6030. EXPECT_TRUE(file.filename.empty());
  6031. EXPECT_EQ("application/octet-stream", file.content_type);
  6032. EXPECT_EQ(0u, file.content.size());
  6033. }
  6034. } else {
  6035. std::string body;
  6036. content_reader([&](const char *data, size_t data_length) {
  6037. EXPECT_EQ(7U, data_length);
  6038. body.append(data, data_length);
  6039. return true;
  6040. });
  6041. EXPECT_EQ(body, "content");
  6042. res.set_content(body, "text/plain");
  6043. }
  6044. })
  6045. .Put("/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. .Patch("/content_receiver",
  6057. [&](const Request & /*req*/, Response &res,
  6058. const ContentReader &content_reader) {
  6059. std::string body;
  6060. content_reader([&](const char *data, size_t data_length) {
  6061. body.append(data, data_length);
  6062. return true;
  6063. });
  6064. EXPECT_EQ(body, "content");
  6065. res.set_content(body, "text/plain");
  6066. })
  6067. .Post("/query-string-and-body",
  6068. [&](const Request &req, Response & /*res*/) {
  6069. ASSERT_TRUE(req.has_param("key"));
  6070. EXPECT_EQ(req.get_param_value("key"), "value");
  6071. EXPECT_EQ(req.body, "content");
  6072. })
  6073. .Get("/last-request",
  6074. [&](const Request &req, Response & /*res*/) {
  6075. EXPECT_EQ("close", req.get_header_value("Connection"));
  6076. })
  6077. .Get(R"(/redirect/(\d+))",
  6078. [&](const Request &req, Response &res) {
  6079. auto num = std::stoi(req.matches[1]) + 1;
  6080. std::string url = "/redirect/" + std::to_string(num);
  6081. res.set_redirect(url);
  6082. })
  6083. .Post("/binary",
  6084. [&](const Request &req, Response &res) {
  6085. EXPECT_EQ(4U, req.body.size());
  6086. EXPECT_EQ("application/octet-stream",
  6087. req.get_header_value("Content-Type"));
  6088. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6089. res.set_content(req.body, "application/octet-stream");
  6090. })
  6091. .Put("/binary",
  6092. [&](const Request &req, Response &res) {
  6093. EXPECT_EQ(4U, req.body.size());
  6094. EXPECT_EQ("application/octet-stream",
  6095. req.get_header_value("Content-Type"));
  6096. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6097. res.set_content(req.body, "application/octet-stream");
  6098. })
  6099. .Patch("/binary",
  6100. [&](const Request &req, Response &res) {
  6101. EXPECT_EQ(4U, req.body.size());
  6102. EXPECT_EQ("application/octet-stream",
  6103. req.get_header_value("Content-Type"));
  6104. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6105. res.set_content(req.body, "application/octet-stream");
  6106. })
  6107. .Delete("/binary",
  6108. [&](const Request &req, Response &res) {
  6109. EXPECT_EQ(4U, req.body.size());
  6110. EXPECT_EQ("application/octet-stream",
  6111. req.get_header_value("Content-Type"));
  6112. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6113. res.set_content(req.body, "application/octet-stream");
  6114. })
  6115. .Get("/issue1772",
  6116. [&](const Request & /*req*/, Response &res) {
  6117. res.status = 401;
  6118. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6119. })
  6120. .Delete("/issue609",
  6121. [](const httplib::Request &, httplib::Response &res,
  6122. const httplib::ContentReader &) {
  6123. res.set_content("ok", "text/plain");
  6124. })
  6125. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6126. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6127. .Get("/compress",
  6128. [&](const Request & /*req*/, Response &res) {
  6129. res.set_content(
  6130. "12345678901234567890123456789012345678901234567890123456789"
  6131. "01234567890123456789012345678901234567890",
  6132. "text/plain");
  6133. })
  6134. .Get("/compress-with-charset",
  6135. [&](const Request & /*req*/, Response &res) {
  6136. res.set_content(
  6137. "12345678901234567890123456789012345678901234567890123456789"
  6138. "01234567890123456789012345678901234567890",
  6139. "application/json; charset=utf-8");
  6140. })
  6141. .Get("/nocompress",
  6142. [&](const Request & /*req*/, Response &res) {
  6143. res.set_content(
  6144. "12345678901234567890123456789012345678901234567890123456789"
  6145. "01234567890123456789012345678901234567890",
  6146. "application/octet-stream");
  6147. })
  6148. .Post("/compress-multipart",
  6149. [&](const Request &req, Response & /*res*/) {
  6150. EXPECT_EQ(2u, req.form.fields.size());
  6151. ASSERT_TRUE(!req.form.has_field("???"));
  6152. {
  6153. const auto &text = req.form.get_field("key1");
  6154. EXPECT_EQ("test", text);
  6155. }
  6156. {
  6157. const auto &text = req.form.get_field("key2");
  6158. EXPECT_EQ("--abcdefg123", text);
  6159. }
  6160. })
  6161. #endif
  6162. ;
  6163. persons_["john"] = "programmer";
  6164. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6165. svr_.wait_until_ready();
  6166. }
  6167. virtual void TearDown() {
  6168. svr_.stop();
  6169. if (!request_threads_.empty()) {
  6170. std::this_thread::sleep_for(std::chrono::seconds(1));
  6171. for (auto &t : request_threads_) {
  6172. t.join();
  6173. }
  6174. }
  6175. t_.join();
  6176. }
  6177. map<string, string> persons_;
  6178. #ifdef CPPHTTPLIB_SSL_ENABLED
  6179. SSLClient cli_;
  6180. SSLServer svr_;
  6181. #else
  6182. Client cli_;
  6183. Server svr_;
  6184. #endif
  6185. thread t_;
  6186. std::vector<thread> request_threads_;
  6187. };
  6188. TEST_F(ServerTest, GetMethod200) {
  6189. auto res = cli_.Get("/hi");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ("HTTP/1.1", res->version);
  6192. EXPECT_EQ(StatusCode::OK_200, res->status);
  6193. EXPECT_EQ("OK", res->reason);
  6194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6195. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6196. EXPECT_EQ("Hello World!", res->body);
  6197. }
  6198. TEST_F(ServerTest, GetEmptyFile) {
  6199. auto res = cli_.Get("/empty_file");
  6200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6201. EXPECT_EQ(StatusCode::OK_200, res->status);
  6202. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6203. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6204. EXPECT_EQ("", res->body);
  6205. }
  6206. TEST_F(ServerTest, GetFileContent) {
  6207. auto res = cli_.Get("/file_content");
  6208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6209. EXPECT_EQ(StatusCode::OK_200, res->status);
  6210. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6211. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6212. EXPECT_EQ("test.html", res->body);
  6213. }
  6214. TEST_F(ServerTest, GetFileContentWithRange) {
  6215. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6218. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6219. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6220. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6221. EXPECT_EQ("est", res->body);
  6222. }
  6223. TEST_F(ServerTest, GetFileContentWithContentType) {
  6224. auto res = cli_.Get("/file_content_with_content_type");
  6225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6226. EXPECT_EQ(StatusCode::OK_200, res->status);
  6227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6228. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6229. EXPECT_EQ("file\n", res->body);
  6230. }
  6231. TEST_F(ServerTest, GetInvalidFileContent) {
  6232. auto res = cli_.Get("/invalid_file_content");
  6233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6234. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6235. }
  6236. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6237. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ("HTTP/1.1", res->version);
  6240. EXPECT_EQ(StatusCode::OK_200, res->status);
  6241. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6242. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6243. EXPECT_EQ("Hello World!", res->body);
  6244. }
  6245. TEST_F(ServerTest, GetMethod302) {
  6246. auto res = cli_.Get("/");
  6247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6248. EXPECT_EQ(StatusCode::Found_302, res->status);
  6249. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6250. }
  6251. TEST_F(ServerTest, GetMethod302Redirect) {
  6252. cli_.set_follow_location(true);
  6253. auto res = cli_.Get("/");
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::OK_200, res->status);
  6256. EXPECT_EQ("Hello World!", res->body);
  6257. EXPECT_EQ("/hi", res->location);
  6258. }
  6259. TEST_F(ServerTest, GetMethod404) {
  6260. auto res = cli_.Get("/invalid");
  6261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6262. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6263. }
  6264. TEST_F(ServerTest, HeadMethod200) {
  6265. auto res = cli_.Head("/hi");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. EXPECT_EQ(StatusCode::OK_200, res->status);
  6268. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6269. EXPECT_TRUE(res->body.empty());
  6270. }
  6271. TEST_F(ServerTest, HeadMethod200Static) {
  6272. auto res = cli_.Head("/mount/dir/index.html");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. EXPECT_EQ(StatusCode::OK_200, res->status);
  6275. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6276. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6277. EXPECT_TRUE(res->body.empty());
  6278. }
  6279. TEST_F(ServerTest, HeadMethod404) {
  6280. auto res = cli_.Head("/invalid");
  6281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6282. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6283. EXPECT_TRUE(res->body.empty());
  6284. }
  6285. TEST_F(ServerTest, GetMethodPersonJohn) {
  6286. auto res = cli_.Get("/person/john");
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. EXPECT_EQ(StatusCode::OK_200, res->status);
  6289. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6290. EXPECT_EQ("programmer", res->body);
  6291. }
  6292. TEST_F(ServerTest, PostMethod1) {
  6293. auto res = cli_.Get("/person/john1");
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6296. res = cli_.Post("/person", "name=john1&note=coder",
  6297. "application/x-www-form-urlencoded");
  6298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6299. ASSERT_EQ(StatusCode::OK_200, res->status);
  6300. res = cli_.Get("/person/john1");
  6301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6302. ASSERT_EQ(StatusCode::OK_200, res->status);
  6303. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6304. ASSERT_EQ("coder", res->body);
  6305. }
  6306. TEST_F(ServerTest, PostMethod2) {
  6307. auto res = cli_.Get("/person/john2");
  6308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6309. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6310. Params params;
  6311. params.emplace("name", "john2");
  6312. params.emplace("note", "coder");
  6313. res = cli_.Post("/person", params);
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. ASSERT_EQ(StatusCode::OK_200, res->status);
  6316. res = cli_.Get("/person/john2");
  6317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6318. ASSERT_EQ(StatusCode::OK_200, res->status);
  6319. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6320. ASSERT_EQ("coder", res->body);
  6321. }
  6322. TEST_F(ServerTest, PutMethod3) {
  6323. auto res = cli_.Get("/person/john3");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6326. Params params;
  6327. params.emplace("name", "john3");
  6328. params.emplace("note", "coder");
  6329. res = cli_.Put("/person", params);
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. ASSERT_EQ(StatusCode::OK_200, res->status);
  6332. res = cli_.Get("/person/john3");
  6333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6334. ASSERT_EQ(StatusCode::OK_200, res->status);
  6335. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6336. ASSERT_EQ("coder", res->body);
  6337. }
  6338. TEST_F(ServerTest, DeleteMethod1) {
  6339. auto res = cli_.Get("/person/john4");
  6340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6341. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6342. Params params;
  6343. params.emplace("name", "john4");
  6344. params.emplace("note", "coder");
  6345. res = cli_.Post("/person", params);
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. ASSERT_EQ(StatusCode::OK_200, res->status);
  6348. res = cli_.Get("/person/john4");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. ASSERT_EQ(StatusCode::OK_200, res->status);
  6351. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6352. ASSERT_EQ("coder", res->body);
  6353. Params delete_params;
  6354. delete_params.emplace("name", "john4");
  6355. res = cli_.Delete("/person", delete_params);
  6356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6357. ASSERT_EQ(StatusCode::OK_200, res->status);
  6358. ASSERT_EQ("DELETED", res->body);
  6359. res = cli_.Get("/person/john4");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6362. }
  6363. TEST_F(ServerTest, DeleteMethod2) {
  6364. auto res = cli_.Get("/person/john5");
  6365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6366. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6367. Params params;
  6368. params.emplace("name", "john5");
  6369. params.emplace("note", "developer");
  6370. res = cli_.Post("/person", params);
  6371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6372. ASSERT_EQ(StatusCode::OK_200, res->status);
  6373. res = cli_.Get("/person/john5");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. ASSERT_EQ(StatusCode::OK_200, res->status);
  6376. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6377. ASSERT_EQ("developer", res->body);
  6378. Params delete_params;
  6379. delete_params.emplace("name", "john5");
  6380. Headers headers;
  6381. headers.emplace("Custom-Header", "test-value");
  6382. res = cli_.Delete("/person", headers, delete_params);
  6383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6384. ASSERT_EQ(StatusCode::OK_200, res->status);
  6385. ASSERT_EQ("DELETED", res->body);
  6386. res = cli_.Get("/person/john5");
  6387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6388. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6389. }
  6390. TEST_F(ServerTest, DeleteMethod3) {
  6391. auto res = cli_.Get("/person/john6");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6394. Params params;
  6395. params.emplace("name", "john6");
  6396. params.emplace("note", "tester");
  6397. res = cli_.Post("/person", params);
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. res = cli_.Get("/person/john6");
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. ASSERT_EQ(StatusCode::OK_200, res->status);
  6403. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6404. ASSERT_EQ("tester", res->body);
  6405. Params delete_params;
  6406. delete_params.emplace("name", "john6");
  6407. Headers headers;
  6408. headers.emplace("Custom-Header", "test-value");
  6409. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. ASSERT_EQ(StatusCode::OK_200, res->status);
  6412. ASSERT_EQ("DELETED", res->body);
  6413. res = cli_.Get("/person/john6");
  6414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6415. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6416. }
  6417. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6418. Params params;
  6419. params.emplace("json", JSON_DATA);
  6420. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6422. ASSERT_EQ(StatusCode::OK_200, res->status);
  6423. ASSERT_EQ(JSON_DATA, res->body);
  6424. }
  6425. TEST_F(ServerTest, PostEmptyContent) {
  6426. auto res = cli_.Post("/empty", "", "text/plain");
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. ASSERT_EQ(StatusCode::OK_200, res->status);
  6429. ASSERT_EQ("empty", res->body);
  6430. }
  6431. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6432. auto res = cli_.Post("/empty-no-content-type");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. ASSERT_EQ(StatusCode::OK_200, res->status);
  6435. ASSERT_EQ("empty-no-content-type", res->body);
  6436. }
  6437. TEST_F(ServerTest, PostPathOnly) {
  6438. auto res = cli_.Post("/path-only");
  6439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6440. ASSERT_EQ(StatusCode::OK_200, res->status);
  6441. ASSERT_EQ("path-only", res->body);
  6442. }
  6443. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6444. auto res = cli_.Post("/path-headers-only",
  6445. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6447. ASSERT_EQ(StatusCode::OK_200, res->status);
  6448. ASSERT_EQ("path-headers-only", res->body);
  6449. }
  6450. TEST_F(ServerTest, PostLarge) {
  6451. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::OK_200, res->status);
  6454. EXPECT_EQ(LARGE_DATA, res->body);
  6455. }
  6456. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6457. auto res = cli_.Put("/empty-no-content-type");
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. ASSERT_EQ(StatusCode::OK_200, res->status);
  6460. ASSERT_EQ("empty-no-content-type", res->body);
  6461. }
  6462. TEST_F(ServerTest, GetMethodDir) {
  6463. auto res = cli_.Get("/dir/");
  6464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6465. EXPECT_EQ(StatusCode::OK_200, res->status);
  6466. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6467. auto body = R"(<html>
  6468. <head>
  6469. </head>
  6470. <body>
  6471. <a href="/dir/test.html">Test</a>
  6472. <a href="/hi">hi</a>
  6473. </body>
  6474. </html>
  6475. )";
  6476. EXPECT_EQ(body, res->body);
  6477. }
  6478. TEST_F(ServerTest, GetMethodDirTest) {
  6479. auto res = cli_.Get("/dir/test.html");
  6480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6481. EXPECT_EQ(StatusCode::OK_200, res->status);
  6482. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6483. EXPECT_EQ("test.html", res->body);
  6484. }
  6485. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6486. auto res = cli_.Get("/dir/../dir/test.html");
  6487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6489. }
  6490. TEST_F(ServerTest, GetMethodInvalidPath) {
  6491. auto res = cli_.Get("/dir/../test.html");
  6492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6493. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6494. }
  6495. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6496. auto res = cli_.Get("/../www/dir/test.html");
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6499. }
  6500. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6501. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6504. }
  6505. TEST_F(ServerTest, GetMethodDirMountTest) {
  6506. auto res = cli_.Get("/mount/dir/test.html");
  6507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6508. EXPECT_EQ(StatusCode::OK_200, res->status);
  6509. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6510. EXPECT_EQ("test.html", res->body);
  6511. }
  6512. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6513. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6516. }
  6517. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6518. auto res = cli_.Get("/mount/dir/../test.html");
  6519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6520. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6521. }
  6522. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6523. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6526. }
  6527. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6528. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6530. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6531. }
  6532. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6533. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6536. }
  6537. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6538. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6541. }
  6542. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6543. auto res = cli_.Get("/mount/dir");
  6544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6545. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6546. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6547. }
  6548. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6549. auto res = cli_.Get("//dir");
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6552. EXPECT_FALSE(res->has_header("Location"));
  6553. }
  6554. TEST_F(ServerTest, PostMethod303) {
  6555. auto res = cli_.Post("/1", "body", "text/plain");
  6556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6557. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6558. EXPECT_EQ("/2", res->get_header_value("Location"));
  6559. }
  6560. TEST_F(ServerTest, PostMethod303Redirect) {
  6561. cli_.set_follow_location(true);
  6562. auto res = cli_.Post("/1", "body", "text/plain");
  6563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6564. EXPECT_EQ(StatusCode::OK_200, res->status);
  6565. EXPECT_EQ("redirected.", res->body);
  6566. EXPECT_EQ("/2", res->location);
  6567. }
  6568. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6569. auto res = cli_.Get("/dir/test.abcde");
  6570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6571. EXPECT_EQ(StatusCode::OK_200, res->status);
  6572. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6573. EXPECT_EQ("abcde", res->body);
  6574. }
  6575. TEST_F(ServerTest, StaticFileRange) {
  6576. auto res =
  6577. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6580. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6581. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6582. EXPECT_EQ(true, res->has_header("Content-Range"));
  6583. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6584. EXPECT_EQ(std::string("cd"), res->body);
  6585. }
  6586. TEST_F(ServerTest, StaticFileRanges) {
  6587. auto res = cli_.Get("/dir/test.abcde",
  6588. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6591. EXPECT_TRUE(
  6592. res->get_header_value("Content-Type")
  6593. .find(
  6594. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6595. 0);
  6596. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6597. }
  6598. TEST_F(ServerTest, StaticFileRangeHead) {
  6599. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6601. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6602. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6603. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6604. EXPECT_EQ(true, res->has_header("Content-Range"));
  6605. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6606. }
  6607. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6608. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6611. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6612. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6613. EXPECT_EQ(true, res->has_header("Content-Range"));
  6614. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6615. res->get_header_value("Content-Range"));
  6616. EXPECT_EQ("LAST\n", res->body);
  6617. }
  6618. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6619. auto res =
  6620. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6622. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6623. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6624. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6625. EXPECT_EQ(true, res->has_header("Content-Range"));
  6626. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6627. }
  6628. TEST_F(ServerTest, StaticFileBigFile) {
  6629. auto res = cli_.Get("/dir/1MB.txt");
  6630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6631. EXPECT_EQ(StatusCode::OK_200, res->status);
  6632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6633. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6634. }
  6635. TEST_F(ServerTest, InvalidBaseDirMount) {
  6636. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6637. }
  6638. TEST_F(ServerTest, Binary) {
  6639. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6640. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6641. "application/octet-stream");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. ASSERT_EQ(StatusCode::OK_200, res->status);
  6644. ASSERT_EQ(4U, res->body.size());
  6645. res = cli_.Put("/binary", binary.data(), binary.size(),
  6646. "application/octet-stream");
  6647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6648. ASSERT_EQ(StatusCode::OK_200, res->status);
  6649. ASSERT_EQ(4U, res->body.size());
  6650. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6651. "application/octet-stream");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. ASSERT_EQ(StatusCode::OK_200, res->status);
  6654. ASSERT_EQ(4U, res->body.size());
  6655. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6656. "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. }
  6661. TEST_F(ServerTest, BinaryString) {
  6662. auto binary = std::string("\x00\x01\x02\x03", 4);
  6663. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6665. ASSERT_EQ(StatusCode::OK_200, res->status);
  6666. ASSERT_EQ(4U, res->body.size());
  6667. res = cli_.Put("/binary", binary, "application/octet-stream");
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. ASSERT_EQ(StatusCode::OK_200, res->status);
  6670. ASSERT_EQ(4U, res->body.size());
  6671. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. ASSERT_EQ(StatusCode::OK_200, res->status);
  6674. ASSERT_EQ(4U, res->body.size());
  6675. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6677. ASSERT_EQ(StatusCode::OK_200, res->status);
  6678. ASSERT_EQ(4U, res->body.size());
  6679. }
  6680. TEST_F(ServerTest, EmptyRequest) {
  6681. auto res = cli_.Get("");
  6682. ASSERT_TRUE(!res);
  6683. EXPECT_EQ(Error::Connection, res.error());
  6684. }
  6685. TEST_F(ServerTest, LongRequest) {
  6686. std::string request;
  6687. for (size_t i = 0; i < 545; i++) {
  6688. request += "/TooLongRequest";
  6689. }
  6690. request += "OK";
  6691. auto res = cli_.Get(request.c_str());
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6694. }
  6695. TEST_F(ServerTest, TooLongRequest) {
  6696. std::string request;
  6697. for (size_t i = 0; i < 546; i++) {
  6698. request += "/TooLongRequest";
  6699. }
  6700. request += "_NG";
  6701. auto start = std::chrono::high_resolution_clock::now();
  6702. cli_.set_keep_alive(true);
  6703. auto res = cli_.Get(request.c_str());
  6704. auto end = std::chrono::high_resolution_clock::now();
  6705. auto elapsed =
  6706. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6707. .count();
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6710. EXPECT_LE(elapsed, 1000);
  6711. EXPECT_EQ("close", res->get_header_value("Connection"));
  6712. EXPECT_FALSE(cli_.is_socket_open());
  6713. }
  6714. TEST_F(ServerTest, AlmostTooLongRequest) {
  6715. // test for #2046 - URI length check shouldn't include other content on req
  6716. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6717. // leading /, space, HTTP/1.1)
  6718. std::string request =
  6719. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6720. auto res = cli_.Get(request.c_str());
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6723. }
  6724. TEST_F(ServerTest, LongHeader) {
  6725. Request req;
  6726. req.method = "GET";
  6727. req.path = "/hi";
  6728. std::string host_and_port;
  6729. host_and_port += HOST;
  6730. host_and_port += ":";
  6731. host_and_port += std::to_string(PORT);
  6732. req.headers.emplace("Host", host_and_port.c_str());
  6733. req.headers.emplace("Accept", "*/*");
  6734. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6735. req.headers.emplace(
  6736. "Header-Name",
  6737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6763. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6764. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6765. "@@@@@@@@@@@@@@@@");
  6766. auto res = std::make_shared<Response>();
  6767. auto error = Error::Success;
  6768. auto ret = cli_.send(req, *res, error);
  6769. ASSERT_TRUE(ret);
  6770. EXPECT_EQ(StatusCode::OK_200, res->status);
  6771. }
  6772. TEST_F(ServerTest, LongQueryValue) {
  6773. auto start = std::chrono::high_resolution_clock::now();
  6774. cli_.set_keep_alive(true);
  6775. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6776. auto end = std::chrono::high_resolution_clock::now();
  6777. auto elapsed =
  6778. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6779. .count();
  6780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6781. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6782. EXPECT_LE(elapsed, 1000);
  6783. EXPECT_EQ("close", res->get_header_value("Connection"));
  6784. EXPECT_FALSE(cli_.is_socket_open());
  6785. }
  6786. TEST_F(ServerTest, TooLongQueryValue) {
  6787. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6788. ASSERT_FALSE(res);
  6789. EXPECT_EQ(Error::Read, res.error());
  6790. }
  6791. TEST_F(ServerTest, TooLongHeader) {
  6792. Request req;
  6793. req.method = "GET";
  6794. req.path = "/hi";
  6795. std::string host_and_port;
  6796. host_and_port += HOST;
  6797. host_and_port += ":";
  6798. host_and_port += std::to_string(PORT);
  6799. req.headers.emplace("Host", host_and_port.c_str());
  6800. req.headers.emplace("Accept", "*/*");
  6801. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6802. req.headers.emplace(
  6803. "Header-Name",
  6804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6832. "@@@@@@@@@@@@@@@@@");
  6833. auto res = std::make_shared<Response>();
  6834. auto error = Error::Success;
  6835. auto ret = cli_.send(req, *res, error);
  6836. ASSERT_TRUE(ret);
  6837. EXPECT_EQ(StatusCode::OK_200, res->status);
  6838. }
  6839. TEST_F(ServerTest, HeaderCountAtLimit) {
  6840. // Test with headers just under the 100 limit
  6841. httplib::Headers headers;
  6842. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6843. // This should keep us just under the 100 header limit
  6844. for (int i = 0; i < 95; i++) {
  6845. std::string name = "X-Test-Header-" + std::to_string(i);
  6846. std::string value = "value" + std::to_string(i);
  6847. headers.emplace(name, value);
  6848. }
  6849. // This should work fine as we're under the limit
  6850. auto res = cli_.Get("/hi", headers);
  6851. EXPECT_TRUE(res);
  6852. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6853. }
  6854. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6855. // Test with many headers to exceed the 100 limit
  6856. httplib::Headers headers;
  6857. // Add 150 headers to definitely exceed the 100 limit
  6858. for (int i = 0; i < 150; i++) {
  6859. std::string name = "X-Test-Header-" + std::to_string(i);
  6860. std::string value = "value" + std::to_string(i);
  6861. headers.emplace(name, value);
  6862. }
  6863. // This should fail due to exceeding header count limit
  6864. cli_.set_keep_alive(true);
  6865. auto res = cli_.Get("/hi", headers);
  6866. // The server should respond with 400 Bad Request
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6869. EXPECT_EQ("close", res->get_header_value("Connection"));
  6870. EXPECT_FALSE(cli_.is_socket_open());
  6871. }
  6872. TEST_F(ServerTest, PercentEncoding) {
  6873. auto res = cli_.Get("/e%6edwith%");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. }
  6877. TEST_F(ServerTest, PercentEncodingUnicode) {
  6878. auto res = cli_.Get("/e%u006edwith%");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. }
  6882. TEST_F(ServerTest, InvalidPercentEncoding) {
  6883. auto res = cli_.Get("/%endwith%");
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6886. }
  6887. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6888. auto res = cli_.Get("/%uendwith%");
  6889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6890. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6891. }
  6892. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6893. auto res = cli_.Get("/hello?aaa=bbb%");
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6896. }
  6897. TEST_F(ServerTest, PlusSignEncoding) {
  6898. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. EXPECT_EQ("a +b", res->body);
  6902. }
  6903. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6904. // This test simulates a potential DoS attack using many headers
  6905. // to verify our security fix prevents memory exhaustion
  6906. httplib::Headers attack_headers;
  6907. // Attempt to add many headers like an attacker would (200 headers to far
  6908. // exceed limit)
  6909. for (int i = 0; i < 200; i++) {
  6910. std::string name = "X-Attack-Header-" + std::to_string(i);
  6911. std::string value = "attack_payload_" + std::to_string(i);
  6912. attack_headers.emplace(name, value);
  6913. }
  6914. // Try to POST with excessive headers
  6915. cli_.set_keep_alive(true);
  6916. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6917. // Should either fail or return 400 Bad Request due to security limit
  6918. if (res) {
  6919. // If we get a response, it should be 400 Bad Request
  6920. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6921. EXPECT_EQ("close", res->get_header_value("Connection"));
  6922. }
  6923. EXPECT_FALSE(cli_.is_socket_open());
  6924. }
  6925. TEST_F(ServerTest, MultipartFormData) {
  6926. UploadFormDataItems items = {
  6927. {"text1", "text default", "", ""},
  6928. {"text2", "aωb", "", ""},
  6929. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6930. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6931. {"file3", "", "", "application/octet-stream"},
  6932. {"file4", "", "", " application/json tmp-string "}};
  6933. auto res = cli_.Post("/multipart", items);
  6934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6935. EXPECT_EQ(StatusCode::OK_200, res->status);
  6936. }
  6937. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6938. UploadFormDataItems items = {
  6939. {"text", "default text", "", ""},
  6940. {"multi_text1", "aaaaa", "", ""},
  6941. {"multi_text1", "bbbbb", "", ""},
  6942. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6943. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6944. "application/json"},
  6945. };
  6946. auto res = cli_.Post("/multipart/multi_file_values", items);
  6947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6948. EXPECT_EQ(StatusCode::OK_200, res->status);
  6949. }
  6950. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6951. auto res = cli_.Get("/hi");
  6952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6953. EXPECT_EQ(StatusCode::OK_200, res->status);
  6954. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6955. EXPECT_EQ("Hello World!", res->body);
  6956. }
  6957. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6958. Request req;
  6959. req.method = "POST";
  6960. req.path = "/chunked";
  6961. std::string host_and_port;
  6962. host_and_port += HOST;
  6963. host_and_port += ":";
  6964. host_and_port += std::to_string(PORT);
  6965. req.headers.emplace("Host", host_and_port.c_str());
  6966. req.headers.emplace("Accept", "*/*");
  6967. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6968. req.headers.emplace("Content-Type", "text/plain");
  6969. req.headers.emplace("Content-Length", "0");
  6970. req.headers.emplace(
  6971. "Transfer-Encoding",
  6972. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6973. // Client does not chunk, so make a chunked body manually.
  6974. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6975. auto res = std::make_shared<Response>();
  6976. auto error = Error::Success;
  6977. auto ret = cli_.send(req, *res, error);
  6978. ASSERT_TRUE(ret);
  6979. EXPECT_EQ(StatusCode::OK_200, res->status);
  6980. }
  6981. template <typename ClientT>
  6982. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6983. int expected_status) {
  6984. Request req;
  6985. req.method = "POST";
  6986. req.path = "/chunked";
  6987. std::string host_and_port;
  6988. host_and_port += HOST;
  6989. host_and_port += ":";
  6990. host_and_port += std::to_string(PORT);
  6991. req.headers.emplace("Host", host_and_port.c_str());
  6992. req.headers.emplace("Content-Length", "0");
  6993. req.headers.emplace("Transfer-Encoding", "chunked");
  6994. req.body = body;
  6995. auto res = std::make_shared<Response>();
  6996. auto error = Error::Success;
  6997. ASSERT_TRUE(cli.send(req, *res, error));
  6998. EXPECT_EQ(expected_status, res->status);
  6999. }
  7000. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7001. // rather than treat them as valid lengths.
  7002. template <typename ClientT>
  7003. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7004. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7005. }
  7006. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7007. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7008. }
  7009. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7010. expect_chunked_body_rejected(
  7011. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7012. }
  7013. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7014. // chunk-size line carries no CR, LF or other control character ahead of its
  7015. // terminator. Such a line must be refused rather than read as extension text.
  7016. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7017. expect_chunked_body_rejected(
  7018. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7019. }
  7020. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7021. expect_chunked_body_rejected(
  7022. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7023. }
  7024. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7025. expect_chunked_body_rejected(
  7026. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7027. }
  7028. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7029. // The literal stays split: a hex escape consumes every hex digit that
  7030. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7031. expect_chunked_body_rejected(
  7032. cli_, "4;a\x01"
  7033. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7034. }
  7035. // The bytes around chunk data are no payload, so they cannot ride on the
  7036. // payload limit
  7037. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7038. // Small enough that the whole request is sent before the server turns it
  7039. // down, yet past the limit by the last chunks
  7040. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7041. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7042. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7043. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7044. SCOPED_TRACE(size_line.substr(0, 2));
  7045. std::string body;
  7046. for (auto c : std::string("dechunked post body")) {
  7047. body += size_line + "\r\n" + c + "\r\n";
  7048. }
  7049. body += "0\r\n\r\n";
  7050. expect_chunked_body_rejected(cli_, body.c_str());
  7051. }
  7052. }
  7053. TEST_F(ServerTest, AcceptsChunkExtension) {
  7054. expect_chunked_body_status(cli_,
  7055. "4;name=value\r\ndech\r\n"
  7056. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7057. "0;last\r\n\r\n",
  7058. StatusCode::OK_200);
  7059. }
  7060. TEST_F(ServerTest, GetStreamed2) {
  7061. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7063. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7064. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7065. EXPECT_EQ(true, res->has_header("Content-Range"));
  7066. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7067. EXPECT_EQ(std::string("ab"), res->body);
  7068. }
  7069. TEST_F(ServerTest, GetStreamed) {
  7070. auto res = cli_.Get("/streamed");
  7071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7072. EXPECT_EQ(StatusCode::OK_200, res->status);
  7073. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7074. EXPECT_EQ(std::string("aaabbb"), res->body);
  7075. }
  7076. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7077. auto res = cli_.Get("/streamed-without-length",
  7078. Headers{make_range_header({{0, -1}})});
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ(false, res->has_header("Content-Length"));
  7082. EXPECT_EQ(false, res->has_header("Content-Range"));
  7083. EXPECT_EQ(std::string("abcdefg"), res->body);
  7084. }
  7085. TEST_F(ServerTest, GetStreamedWithRange1) {
  7086. auto res =
  7087. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7090. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7091. EXPECT_EQ(true, res->has_header("Content-Range"));
  7092. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7093. EXPECT_EQ(std::string("def"), res->body);
  7094. }
  7095. TEST_F(ServerTest, GetStreamedWithRange2) {
  7096. auto res =
  7097. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7099. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7100. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7101. EXPECT_EQ(true, res->has_header("Content-Range"));
  7102. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7103. EXPECT_EQ(std::string("bcdefg"), res->body);
  7104. }
  7105. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7106. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7108. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7109. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7110. EXPECT_EQ(true, res->has_header("Content-Range"));
  7111. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7112. EXPECT_EQ(std::string("efg"), res->body);
  7113. }
  7114. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7115. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7116. // the entire representation.
  7117. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7118. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7121. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7122. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7123. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7124. }
  7125. }
  7126. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7127. auto res =
  7128. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7130. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7131. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7132. EXPECT_EQ(false, res->has_header("Content-Range"));
  7133. EXPECT_EQ(0U, res->body.size());
  7134. }
  7135. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7136. // Only a 206 is served as a partial representation. Under any other status
  7137. // `apply_ranges()` reported the full content length, so the body must match
  7138. // that header, and the content provider must never be asked for an offset
  7139. // outside the representation.
  7140. auto check = [&](int status, const char *range) {
  7141. auto path =
  7142. std::string("/streamed-with-range?status=") + std::to_string(status);
  7143. auto ctx = path + " Range: " + range;
  7144. auto res = cli_.Get(path, Headers{{"Range", range}});
  7145. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7146. EXPECT_EQ(status, res->status) << ctx;
  7147. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7149. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7150. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7151. };
  7152. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7153. check(403, "bytes=3-5");
  7154. // The offset is far past the representation.
  7155. check(403, "bytes=100000-100200");
  7156. // `first_pos` is still -1 here, and the bounds asserts in
  7157. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7158. check(403, "bytes=-3");
  7159. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7160. // multipart branch would have written one that is empty.
  7161. check(403, "bytes=1-2, 4-5");
  7162. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7163. // covers the whole representation.
  7164. check(200, "bytes=3-5");
  7165. check(200, "bytes=1-2, 4-5");
  7166. }
  7167. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7168. auto res =
  7169. cli_.Get("/streamed-with-range",
  7170. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7171. "92233720368547758079223372036854775807"}});
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7174. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7175. EXPECT_EQ(false, res->has_header("Content-Range"));
  7176. EXPECT_EQ(0U, res->body.size());
  7177. }
  7178. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7179. auto res = cli_.Get(
  7180. "/with-range",
  7181. Headers{{"Range",
  7182. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7183. {"Accept-Encoding", ""}});
  7184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7185. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7186. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7187. EXPECT_EQ(true, res->has_header("Content-Range"));
  7188. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7189. EXPECT_EQ(std::string("abcdefg"), res->body);
  7190. }
  7191. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7192. auto res = cli_.Get("/with-range", Headers{
  7193. {"Range", "bytes=0-"},
  7194. {"Accept-Encoding", ""},
  7195. });
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7198. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7199. EXPECT_EQ(true, res->has_header("Content-Range"));
  7200. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7201. EXPECT_EQ(std::string("abcdefg"), res->body);
  7202. }
  7203. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7204. auto res = cli_.Get("/streamed-with-range",
  7205. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7207. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7208. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7209. EXPECT_EQ(false, res->has_header("Content-Range"));
  7210. EXPECT_EQ(267U, res->body.size());
  7211. // Check that both range contents are present
  7212. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7213. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7214. // Check that Content-Range headers are present for both ranges
  7215. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7216. std::string::npos);
  7217. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7218. std::string::npos);
  7219. }
  7220. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7221. Ranges ranges;
  7222. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7223. ranges.emplace_back(0, -1);
  7224. }
  7225. auto res = cli_.Get("/streamed-with-range?error",
  7226. Headers{{make_range_header(ranges)}});
  7227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7228. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7229. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7230. EXPECT_EQ(false, res->has_header("Content-Range"));
  7231. EXPECT_EQ(0U, res->body.size());
  7232. }
  7233. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7234. auto res = cli_.Get("/streamed-with-range",
  7235. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7237. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7238. EXPECT_EQ(5U, res->body.size());
  7239. // Check that overlapping ranges are coalesced into a single range
  7240. EXPECT_EQ("bcdef", res->body);
  7241. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7242. // Should be single range, not multipart
  7243. EXPECT_TRUE(res->has_header("Content-Range"));
  7244. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7245. }
  7246. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7247. auto res = cli_.Get("/streamed-with-range",
  7248. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7251. EXPECT_EQ(268U, res->body.size());
  7252. // Check that both range contents are present
  7253. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7254. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7255. // Check that Content-Range headers are present for both ranges
  7256. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7257. std::string::npos);
  7258. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7259. std::string::npos);
  7260. }
  7261. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7262. auto res = cli_.Get("/streamed-with-range",
  7263. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7265. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7266. EXPECT_EQ(269U, res->body.size());
  7267. // Check that both duplicate range contents are present
  7268. size_t first_abc = res->body.find("abc\r\n");
  7269. EXPECT_TRUE(first_abc != std::string::npos);
  7270. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7271. EXPECT_TRUE(second_abc != std::string::npos);
  7272. // Check that Content-Range headers are present for both ranges
  7273. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7274. EXPECT_TRUE(first_range != std::string::npos);
  7275. size_t second_range =
  7276. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7277. EXPECT_TRUE(second_range != std::string::npos);
  7278. }
  7279. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7280. auto res =
  7281. cli_.Get("/streamed-with-range?error",
  7282. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7285. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7286. EXPECT_EQ(false, res->has_header("Content-Range"));
  7287. EXPECT_EQ(0U, res->body.size());
  7288. }
  7289. TEST_F(ServerTest, GetStreamedEndless) {
  7290. uint64_t offset = 0;
  7291. auto res = cli_.Get("/streamed-cancel",
  7292. [&](const char * /*data*/, uint64_t data_length) {
  7293. if (offset < 100) {
  7294. offset += data_length;
  7295. return true;
  7296. }
  7297. return false;
  7298. });
  7299. ASSERT_TRUE(!res);
  7300. EXPECT_EQ(Error::Canceled, res.error());
  7301. }
  7302. TEST_F(ServerTest, ClientStop) {
  7303. std::atomic_size_t count{4};
  7304. std::vector<std::thread> threads;
  7305. for (auto i = count.load(); i != 0; --i) {
  7306. threads.emplace_back([&]() {
  7307. auto res = cli_.Get("/streamed-cancel",
  7308. [&](const char *, uint64_t) { return true; });
  7309. --count;
  7310. ASSERT_TRUE(!res);
  7311. EXPECT_TRUE(res.error() == Error::Canceled ||
  7312. res.error() == Error::Read || res.error() == Error::Write);
  7313. });
  7314. }
  7315. std::this_thread::sleep_for(std::chrono::seconds(2));
  7316. while (count != 0) {
  7317. cli_.stop();
  7318. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7319. }
  7320. for (auto &t : threads) {
  7321. t.join();
  7322. }
  7323. }
  7324. TEST_F(ServerTest, GetWithRange1) {
  7325. auto res = cli_.Get("/with-range", Headers{
  7326. make_range_header({{3, 5}}),
  7327. {"Accept-Encoding", ""},
  7328. });
  7329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7330. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7331. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7332. EXPECT_EQ(true, res->has_header("Content-Range"));
  7333. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7334. EXPECT_EQ(std::string("def"), res->body);
  7335. }
  7336. TEST_F(ServerTest, GetWithRange2) {
  7337. auto res = cli_.Get("/with-range", Headers{
  7338. make_range_header({{1, -1}}),
  7339. {"Accept-Encoding", ""},
  7340. });
  7341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7342. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7343. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7344. EXPECT_EQ(true, res->has_header("Content-Range"));
  7345. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7346. EXPECT_EQ(std::string("bcdefg"), res->body);
  7347. }
  7348. TEST_F(ServerTest, GetWithRange3) {
  7349. auto res = cli_.Get("/with-range", Headers{
  7350. make_range_header({{0, 0}}),
  7351. {"Accept-Encoding", ""},
  7352. });
  7353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7355. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7356. EXPECT_EQ(true, res->has_header("Content-Range"));
  7357. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7358. EXPECT_EQ(std::string("a"), res->body);
  7359. }
  7360. TEST_F(ServerTest, GetWithRange4) {
  7361. auto res = cli_.Get("/with-range", Headers{
  7362. make_range_header({{-1, 2}}),
  7363. {"Accept-Encoding", ""},
  7364. });
  7365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7366. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7367. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7368. EXPECT_EQ(true, res->has_header("Content-Range"));
  7369. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7370. EXPECT_EQ(std::string("fg"), res->body);
  7371. }
  7372. TEST_F(ServerTest, GetWithRange5) {
  7373. auto res = cli_.Get("/with-range", Headers{
  7374. make_range_header({{0, 5}}),
  7375. {"Accept-Encoding", ""},
  7376. });
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7379. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7380. EXPECT_EQ(true, res->has_header("Content-Range"));
  7381. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7382. EXPECT_EQ(std::string("abcdef"), res->body);
  7383. }
  7384. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7385. auto res =
  7386. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7388. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7389. }
  7390. TEST_F(ServerTest, GetWithRangeMultipart) {
  7391. auto res =
  7392. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7395. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7396. EXPECT_EQ(false, res->has_header("Content-Range"));
  7397. EXPECT_EQ(267U, res->body.size());
  7398. }
  7399. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7400. auto res = cli_.Get("/with-range",
  7401. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7403. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7404. }
  7405. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7406. auto res = cli_.Get("/with-range-customized-response",
  7407. Headers{{make_range_header({{1, 2}})}});
  7408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7409. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7410. EXPECT_EQ(true, res->has_header("Content-Length"));
  7411. EXPECT_EQ(false, res->has_header("Content-Range"));
  7412. EXPECT_EQ(JSON_DATA, res->body);
  7413. }
  7414. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7415. auto res = cli_.Get("/with-range-customized-response",
  7416. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7418. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7419. EXPECT_EQ(true, res->has_header("Content-Length"));
  7420. EXPECT_EQ(false, res->has_header("Content-Range"));
  7421. EXPECT_EQ(JSON_DATA, res->body);
  7422. }
  7423. TEST_F(ServerTest, Issue1772) {
  7424. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7427. }
  7428. TEST_F(ServerTest, Issue609) {
  7429. auto res = cli_.Delete("/issue609");
  7430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7431. EXPECT_EQ(StatusCode::OK_200, res->status);
  7432. EXPECT_EQ(std::string("ok"), res->body);
  7433. }
  7434. TEST_F(ServerTest, GetStreamedChunked) {
  7435. auto res = cli_.Get("/streamed-chunked");
  7436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7437. EXPECT_EQ(StatusCode::OK_200, res->status);
  7438. EXPECT_EQ(std::string("123456789"), res->body);
  7439. }
  7440. TEST_F(ServerTest, GetStreamedChunked2) {
  7441. auto res = cli_.Get("/streamed-chunked2");
  7442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7443. EXPECT_EQ(StatusCode::OK_200, res->status);
  7444. EXPECT_EQ(std::string("123456789"), res->body);
  7445. }
  7446. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7447. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::OK_200, res->status);
  7450. EXPECT_EQ(std::string("123456789"), res->body);
  7451. EXPECT_TRUE(res->has_header("Trailer"));
  7452. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7453. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7454. // Trailers are now stored separately from headers (security fix)
  7455. EXPECT_EQ(2U, res->trailers.size());
  7456. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7457. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7458. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7459. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7460. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7461. // Verify trailers are NOT in headers (security verification)
  7462. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7463. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7464. }
  7465. TEST_F(ServerTest, LargeChunkedPost) {
  7466. Request req;
  7467. req.method = "POST";
  7468. req.path = "/large-chunked";
  7469. std::string host_and_port;
  7470. host_and_port += HOST;
  7471. host_and_port += ":";
  7472. host_and_port += std::to_string(PORT);
  7473. req.headers.emplace("Host", host_and_port.c_str());
  7474. req.headers.emplace("Accept", "*/*");
  7475. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7476. req.headers.emplace("Content-Type", "text/plain");
  7477. req.headers.emplace("Content-Length", "0");
  7478. req.headers.emplace("Transfer-Encoding", "chunked");
  7479. std::string long_string(30 * 1024u, 'a');
  7480. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7481. // Attempt to make a large enough post to exceed OS buffers, to test that
  7482. // the server handles short reads if the full chunk data isn't available.
  7483. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7484. auto res = std::make_shared<Response>();
  7485. auto error = Error::Success;
  7486. auto ret = cli_.send(req, *res, error);
  7487. ASSERT_TRUE(ret);
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7491. auto res = cli_.Get("/remote_addr");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7495. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7496. }
  7497. TEST_F(ServerTest, GetMethodLocalAddr) {
  7498. auto res = cli_.Get("/local_addr");
  7499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7500. EXPECT_EQ(StatusCode::OK_200, res->status);
  7501. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7502. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7503. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7504. }
  7505. TEST_F(ServerTest, HTTPResponseSplitting) {
  7506. auto res = cli_.Get("/http_response_splitting");
  7507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. }
  7510. TEST_F(ServerTest, SlowRequest) {
  7511. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7512. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7513. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7514. }
  7515. #if 0
  7516. TEST_F(ServerTest, SlowPost) {
  7517. char buffer[64 * 1024];
  7518. memset(buffer, 0x42, sizeof(buffer));
  7519. auto res = cli_.Post(
  7520. "/slowpost", 64 * 1024 * 1024,
  7521. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7522. auto ret = sink.write(buffer, sizeof(buffer));
  7523. EXPECT_TRUE(ret);
  7524. return true;
  7525. },
  7526. "text/plain");
  7527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7528. EXPECT_EQ(StatusCode::OK_200, res->status);
  7529. }
  7530. TEST_F(ServerTest, SlowPostFail) {
  7531. char buffer[64 * 1024];
  7532. memset(buffer, 0x42, sizeof(buffer));
  7533. cli_.set_write_timeout(std::chrono::seconds(0));
  7534. auto res = cli_.Post(
  7535. "/slowpost", 64 * 1024 * 1024,
  7536. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7537. sink.write(buffer, sizeof(buffer));
  7538. return true;
  7539. },
  7540. "text/plain");
  7541. ASSERT_TRUE(!res);
  7542. EXPECT_EQ(Error::Write, res.error());
  7543. }
  7544. #endif
  7545. TEST_F(ServerTest, Put) {
  7546. auto res = cli_.Put("/put", "PUT", "text/plain");
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ(StatusCode::OK_200, res->status);
  7549. EXPECT_EQ("PUT", res->body);
  7550. }
  7551. TEST_F(ServerTest, PutWithContentProvider) {
  7552. auto res = cli_.Put(
  7553. "/put", 3,
  7554. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7555. sink.os << "PUT";
  7556. return true;
  7557. },
  7558. "text/plain");
  7559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7560. EXPECT_EQ(StatusCode::OK_200, res->status);
  7561. EXPECT_EQ("PUT", res->body);
  7562. }
  7563. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7564. auto res = cli_.Post(
  7565. "/post", 42,
  7566. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7567. return false;
  7568. },
  7569. "text/plain");
  7570. ASSERT_TRUE(!res);
  7571. EXPECT_EQ(Error::Canceled, res.error());
  7572. }
  7573. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7574. auto res = cli_.Put(
  7575. "/put",
  7576. [](size_t /*offset*/, DataSink &sink) {
  7577. sink.os << "PUT";
  7578. sink.done();
  7579. return true;
  7580. },
  7581. "text/plain");
  7582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7583. EXPECT_EQ(StatusCode::OK_200, res->status);
  7584. EXPECT_EQ("PUT", res->body);
  7585. }
  7586. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7587. auto res = cli_.Post(
  7588. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7589. "text/plain");
  7590. ASSERT_TRUE(!res);
  7591. EXPECT_EQ(Error::Canceled, res.error());
  7592. }
  7593. TEST_F(ServerTest, PostLoopBack) {
  7594. std::string body;
  7595. auto res = cli_.Post(
  7596. "/post-loopback", 9,
  7597. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7598. EXPECT_EQ(9u, length);
  7599. sink.write("123", 3);
  7600. sink.write("456", 3);
  7601. sink.write("789", 3);
  7602. return true;
  7603. },
  7604. "text/plain",
  7605. [&body](const char *data, size_t data_length) {
  7606. body.append(data, data_length);
  7607. return true;
  7608. });
  7609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7610. EXPECT_EQ(StatusCode::OK_200, res->status);
  7611. EXPECT_EQ("123456789", body);
  7612. }
  7613. TEST_F(ServerTest, PutLoopBack) {
  7614. std::string body;
  7615. auto res = cli_.Put(
  7616. "/put-loopback", 9,
  7617. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7618. EXPECT_EQ(9u, length);
  7619. sink.write("123", 3);
  7620. sink.write("456", 3);
  7621. sink.write("789", 3);
  7622. return true;
  7623. },
  7624. "text/plain",
  7625. [&body](const char *data, size_t data_length) {
  7626. body.append(data, data_length);
  7627. return true;
  7628. });
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_EQ(StatusCode::OK_200, res->status);
  7631. EXPECT_EQ("123456789", body);
  7632. }
  7633. TEST_F(ServerTest, PatchLoopBack) {
  7634. std::string body;
  7635. auto res = cli_.Patch(
  7636. "/patch-loopback", 9,
  7637. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7638. EXPECT_EQ(9u, length);
  7639. sink.write("123", 3);
  7640. sink.write("456", 3);
  7641. sink.write("789", 3);
  7642. return true;
  7643. },
  7644. "text/plain",
  7645. [&body](const char *data, size_t data_length) {
  7646. body.append(data, data_length);
  7647. return true;
  7648. });
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. EXPECT_EQ(StatusCode::OK_200, res->status);
  7651. EXPECT_EQ("123456789", body);
  7652. }
  7653. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7654. std::string body;
  7655. auto res = cli_.Post(
  7656. "/post-loopback",
  7657. [](size_t /*offset*/, DataSink &sink) {
  7658. sink.write("123", 3);
  7659. sink.write("456", 3);
  7660. sink.write("789", 3);
  7661. sink.done();
  7662. return true;
  7663. },
  7664. "text/plain",
  7665. [&body](const char *data, size_t data_length) {
  7666. body.append(data, data_length);
  7667. return true;
  7668. });
  7669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7670. EXPECT_EQ(StatusCode::OK_200, res->status);
  7671. EXPECT_EQ("123456789", body);
  7672. }
  7673. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7674. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7675. cli_.set_compress(true);
  7676. auto res = cli_.Put(
  7677. "/put", 3,
  7678. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7679. sink.os << "PUT";
  7680. return true;
  7681. },
  7682. "text/plain");
  7683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7684. EXPECT_EQ(StatusCode::OK_200, res->status);
  7685. EXPECT_EQ("PUT", res->body);
  7686. }
  7687. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7688. cli_.set_compress(true);
  7689. auto res = cli_.Post(
  7690. "/post", 42,
  7691. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7692. return false;
  7693. },
  7694. "text/plain");
  7695. ASSERT_TRUE(!res);
  7696. EXPECT_EQ(Error::Canceled, res.error());
  7697. }
  7698. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7699. cli_.set_compress(true);
  7700. auto res = cli_.Put(
  7701. "/put",
  7702. [](size_t /*offset*/, DataSink &sink) {
  7703. sink.os << "PUT";
  7704. sink.done();
  7705. return true;
  7706. },
  7707. "text/plain");
  7708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7709. EXPECT_EQ(StatusCode::OK_200, res->status);
  7710. EXPECT_EQ("PUT", res->body);
  7711. }
  7712. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7713. cli_.set_compress(true);
  7714. auto res = cli_.Post(
  7715. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7716. "text/plain");
  7717. ASSERT_TRUE(!res);
  7718. EXPECT_EQ(Error::Canceled, res.error());
  7719. }
  7720. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7721. cli_.set_compress(true);
  7722. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7724. EXPECT_EQ(StatusCode::OK_200, res->status);
  7725. EXPECT_EQ(LARGE_DATA, res->body);
  7726. }
  7727. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7728. #ifdef CPPHTTPLIB_SSL_ENABLED
  7729. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7730. Client cli(s.c_str());
  7731. cli.enable_server_certificate_verification(false);
  7732. #else
  7733. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7734. Client cli(s.c_str());
  7735. #endif
  7736. cli.set_compress(true);
  7737. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7739. EXPECT_EQ(StatusCode::OK_200, res->status);
  7740. EXPECT_EQ(LARGE_DATA, res->body);
  7741. // The compressed size should be less than a 10th of the original. May vary
  7742. // depending on the zlib library.
  7743. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7744. static_cast<uint64_t>(10 * 1024 * 1024));
  7745. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7746. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7747. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7748. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7749. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7750. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7751. #endif
  7752. }
  7753. TEST_F(ServerTest, PutContentWithDeflate) {
  7754. cli_.set_compress(false);
  7755. Headers headers;
  7756. headers.emplace("Content-Encoding", "deflate");
  7757. // PUT in deflate format:
  7758. auto res = cli_.Put("/put", headers,
  7759. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7761. EXPECT_EQ(StatusCode::OK_200, res->status);
  7762. EXPECT_EQ("PUT", res->body);
  7763. }
  7764. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7765. Headers headers;
  7766. headers.emplace("Accept-Encoding", "gzip, deflate");
  7767. auto res = cli_.Get("/streamed-chunked", headers);
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::OK_200, res->status);
  7770. EXPECT_EQ(std::string("123456789"), res->body);
  7771. }
  7772. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7773. Headers headers;
  7774. headers.emplace("Accept-Encoding", "gzip, deflate");
  7775. auto res = cli_.Get("/streamed-chunked2", headers);
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::OK_200, res->status);
  7778. EXPECT_EQ(std::string("123456789"), res->body);
  7779. }
  7780. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7781. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7783. EXPECT_EQ(StatusCode::OK_200, res->status);
  7784. }
  7785. TEST(GzipDecompressor, ChunkedDecompression) {
  7786. std::string data;
  7787. for (size_t i = 0; i < 32 * 1024; ++i) {
  7788. data.push_back(static_cast<char>('a' + i % 26));
  7789. }
  7790. std::string compressed_data;
  7791. {
  7792. httplib::detail::gzip_compressor compressor;
  7793. bool result = compressor.compress(
  7794. data.data(), data.size(),
  7795. /*last=*/true,
  7796. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7797. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7798. compressed_data_size);
  7799. return true;
  7800. });
  7801. ASSERT_TRUE(result);
  7802. }
  7803. std::string decompressed_data;
  7804. {
  7805. httplib::detail::gzip_decompressor decompressor;
  7806. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7807. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7808. size_t chunk_size = 130;
  7809. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7810. chunk_begin += chunk_size) {
  7811. size_t current_chunk_size =
  7812. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7813. bool result = decompressor.decompress(
  7814. compressed_data.data() + chunk_begin, current_chunk_size,
  7815. [&](const char *decompressed_data_chunk,
  7816. size_t decompressed_data_chunk_size) {
  7817. decompressed_data.insert(decompressed_data.size(),
  7818. decompressed_data_chunk,
  7819. decompressed_data_chunk_size);
  7820. return true;
  7821. });
  7822. ASSERT_TRUE(result);
  7823. }
  7824. }
  7825. ASSERT_EQ(data, decompressed_data);
  7826. }
  7827. TEST(GzipDecompressor, DeflateDecompression) {
  7828. std::string original_text = "Raw deflate without gzip";
  7829. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7830. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7831. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7832. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7833. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7834. std::string decompressed_data;
  7835. {
  7836. httplib::detail::gzip_decompressor decompressor;
  7837. bool result = decompressor.decompress(
  7838. compressed_data.data(), compressed_data.size(),
  7839. [&](const char *decompressed_data_chunk,
  7840. size_t decompressed_data_chunk_size) {
  7841. decompressed_data.insert(decompressed_data.size(),
  7842. decompressed_data_chunk,
  7843. decompressed_data_chunk_size);
  7844. return true;
  7845. });
  7846. ASSERT_TRUE(result);
  7847. }
  7848. ASSERT_EQ(original_text, decompressed_data);
  7849. }
  7850. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7851. std::string original_text = "Raw deflate without gzip";
  7852. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7853. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7854. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7855. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7856. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7857. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7858. std::string decompressed_data;
  7859. {
  7860. httplib::detail::gzip_decompressor decompressor;
  7861. bool result = decompressor.decompress(
  7862. compressed_data.data(), compressed_data.size(),
  7863. [&](const char *decompressed_data_chunk,
  7864. size_t decompressed_data_chunk_size) {
  7865. decompressed_data.insert(decompressed_data.size(),
  7866. decompressed_data_chunk,
  7867. decompressed_data_chunk_size);
  7868. return true;
  7869. });
  7870. ASSERT_TRUE(result);
  7871. }
  7872. ASSERT_EQ(original_text, decompressed_data);
  7873. }
  7874. #endif
  7875. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7876. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7877. Headers headers;
  7878. headers.emplace("Accept-Encoding", "br");
  7879. auto res = cli_.Get("/streamed-chunked", headers);
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ(std::string("123456789"), res->body);
  7883. }
  7884. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7885. Headers headers;
  7886. headers.emplace("Accept-Encoding", "br");
  7887. auto res = cli_.Get("/streamed-chunked2", headers);
  7888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7889. EXPECT_EQ(StatusCode::OK_200, res->status);
  7890. EXPECT_EQ(std::string("123456789"), res->body);
  7891. }
  7892. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7893. cli_.set_compress(true);
  7894. auto res = cli_.Put(
  7895. "/put", 3,
  7896. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7897. sink.os << "PUT";
  7898. return true;
  7899. },
  7900. "text/plain");
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. EXPECT_EQ("PUT", res->body);
  7904. }
  7905. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7906. cli_.set_compress(true);
  7907. auto res = cli_.Put(
  7908. "/put",
  7909. [](size_t /*offset*/, DataSink &sink) {
  7910. sink.os << "PUT";
  7911. sink.done();
  7912. return true;
  7913. },
  7914. "text/plain");
  7915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7916. EXPECT_EQ(StatusCode::OK_200, res->status);
  7917. EXPECT_EQ("PUT", res->body);
  7918. }
  7919. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7920. cli_.set_compress(true);
  7921. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. EXPECT_EQ(LARGE_DATA, res->body);
  7925. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7926. }
  7927. #endif
  7928. TEST_F(ServerTest, Patch) {
  7929. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7931. EXPECT_EQ(StatusCode::OK_200, res->status);
  7932. EXPECT_EQ("PATCH", res->body);
  7933. }
  7934. TEST_F(ServerTest, Delete) {
  7935. auto res = cli_.Delete("/delete");
  7936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7937. EXPECT_EQ(StatusCode::OK_200, res->status);
  7938. EXPECT_EQ("DELETE", res->body);
  7939. }
  7940. TEST_F(ServerTest, DeleteContentReceiver) {
  7941. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ(StatusCode::OK_200, res->status);
  7944. EXPECT_EQ("content", res->body);
  7945. }
  7946. TEST_F(ServerTest, Options) {
  7947. auto res = cli_.Options("*");
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ(StatusCode::OK_200, res->status);
  7950. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7951. EXPECT_TRUE(res->body.empty());
  7952. }
  7953. TEST_F(ServerTest, URL) {
  7954. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. }
  7958. TEST_F(ServerTest, ArrayParam) {
  7959. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7961. EXPECT_EQ(StatusCode::OK_200, res->status);
  7962. }
  7963. TEST_F(ServerTest, ArrayParamValues) {
  7964. auto res =
  7965. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_EQ(StatusCode::OK_200, res->status);
  7968. }
  7969. TEST_F(ServerTest, NoMultipleHeaders) {
  7970. Headers headers = {{"Content-Length", "5"}};
  7971. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7972. "text/plain");
  7973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7974. EXPECT_EQ(StatusCode::OK_200, res->status);
  7975. }
  7976. TEST_F(ServerTest, PostContentReceiver) {
  7977. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. ASSERT_EQ(StatusCode::OK_200, res->status);
  7980. ASSERT_EQ("content", res->body);
  7981. }
  7982. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7983. UploadFormDataItems items = {
  7984. {"text1", "text default", "", ""},
  7985. {"text2", "aωb", "", ""},
  7986. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7987. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7988. {"file3", "", "", "application/octet-stream"},
  7989. };
  7990. auto res = cli_.Post("/content_receiver", items);
  7991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7992. EXPECT_EQ(StatusCode::OK_200, res->status);
  7993. }
  7994. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7995. UploadFormDataItems items = {
  7996. {"text1", "text default", "", ""},
  7997. {"text2", "aωb", "", ""},
  7998. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7999. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8000. {"file3", "", "", "application/octet-stream"},
  8001. };
  8002. auto boundary = std::string("+++++");
  8003. std::string body;
  8004. for (const auto &item : items) {
  8005. body += "--" + boundary + "\r\n";
  8006. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8007. if (!item.filename.empty()) {
  8008. body += "; filename=\"" + item.filename + "\"";
  8009. }
  8010. body += "\r\n";
  8011. if (!item.content_type.empty()) {
  8012. body += "Content-Type: " + item.content_type + "\r\n";
  8013. }
  8014. body += "\r\n";
  8015. body += item.content + "\r\n";
  8016. }
  8017. body += "--" + boundary + "--\r\n";
  8018. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8019. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. }
  8023. TEST(MultipartFormDataTest, FieldEscaping) {
  8024. Server svr;
  8025. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8026. const ContentReader &content_reader) {
  8027. ASSERT_TRUE(req.is_multipart_form_data());
  8028. std::vector<FormData> received;
  8029. content_reader(
  8030. [&](const FormData &file) {
  8031. received.push_back(file);
  8032. return true;
  8033. },
  8034. [&](const char *data, size_t data_length) {
  8035. received.back().content.append(data, data_length);
  8036. return true;
  8037. });
  8038. // '"', CR and LF in names and filenames are escaped following the
  8039. // WHATWG HTML standard, so each part still parses as a single part
  8040. // with no injected headers. Content types get CR/LF escaped too,
  8041. // while '"' (legal there, e.g. quoted charset) is preserved.
  8042. ASSERT_EQ(4U, received.size());
  8043. EXPECT_EQ("na%22me", received[0].name);
  8044. EXPECT_EQ("quoted name", received[0].content);
  8045. EXPECT_EQ("file", received[1].name);
  8046. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8047. received[1].filename);
  8048. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8049. EXPECT_EQ("injected", received[1].content);
  8050. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8051. EXPECT_EQ("my%22file.txt", received[2].filename);
  8052. EXPECT_EQ("cr lf name", received[2].content);
  8053. EXPECT_EQ("typed", received[3].name);
  8054. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8055. received[3].content_type);
  8056. EXPECT_EQ("typed content", received[3].content);
  8057. });
  8058. auto port = svr.bind_to_any_port("localhost");
  8059. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8060. auto se = detail::scope_exit([&] {
  8061. svr.stop();
  8062. t.join();
  8063. ASSERT_FALSE(svr.is_running());
  8064. });
  8065. svr.wait_until_ready();
  8066. Client cli("localhost", port);
  8067. UploadFormDataItems items = {
  8068. {"na\"me", "quoted name", "", ""},
  8069. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8070. "application/octet-stream"},
  8071. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8072. {"typed", "typed content", "",
  8073. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8074. };
  8075. auto res = cli.Post("/post", items);
  8076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8077. EXPECT_EQ(StatusCode::OK_200, res->status);
  8078. }
  8079. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8080. const UploadFormDataItems items = {
  8081. {"name1", "Content 1", "", ""},
  8082. {"name2", "Content 2", "file2.txt", "text/plain"},
  8083. };
  8084. Server svr;
  8085. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8086. const ContentReader &content_reader) {
  8087. ASSERT_TRUE(req.is_multipart_form_data());
  8088. std::vector<FormData> received;
  8089. content_reader(
  8090. [&](const FormData &file) {
  8091. received.push_back(file);
  8092. return true;
  8093. },
  8094. [&](const char *data, size_t data_length) {
  8095. received.back().content.append(data, data_length);
  8096. return true;
  8097. });
  8098. ASSERT_EQ(2U, received.size());
  8099. EXPECT_EQ("name1", received[0].name);
  8100. EXPECT_EQ("Content 1", received[0].content);
  8101. EXPECT_EQ("name2", received[1].name);
  8102. EXPECT_EQ("Content 2", received[1].content);
  8103. EXPECT_EQ("file2.txt", received[1].filename);
  8104. EXPECT_EQ("text/plain", received[1].content_type);
  8105. });
  8106. auto port = svr.bind_to_any_port("localhost");
  8107. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8108. auto se = detail::scope_exit([&] {
  8109. svr.stop();
  8110. t.join();
  8111. ASSERT_FALSE(svr.is_running());
  8112. });
  8113. svr.wait_until_ready();
  8114. Client cli("localhost", port);
  8115. // Whole-body serialization with a generated boundary
  8116. {
  8117. MultipartFormDataWriter writer;
  8118. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8119. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8120. writer.content_type());
  8121. auto body = writer.serialize(items);
  8122. EXPECT_EQ(body.size(), writer.content_length(items));
  8123. auto res = cli.Post("/post", body, writer.content_type());
  8124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8125. EXPECT_EQ(StatusCode::OK_200, res->status);
  8126. }
  8127. // Per-part framing with a custom boundary via a content provider
  8128. {
  8129. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8130. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8131. MultipartFormDataWriter writer("custom-boundary_123");
  8132. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8133. std::string body;
  8134. for (const auto &item : items) {
  8135. body += writer.item_begin(item);
  8136. body += item.content;
  8137. body += MultipartFormDataWriter::item_end();
  8138. }
  8139. body += writer.finish();
  8140. EXPECT_EQ(body.size(), writer.content_length(items));
  8141. auto res = cli.Post(
  8142. "/post", body.size(),
  8143. [&](size_t offset, size_t length, DataSink &sink) {
  8144. sink.write(body.data() + offset, length);
  8145. return true;
  8146. },
  8147. writer.content_type());
  8148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8149. EXPECT_EQ(StatusCode::OK_200, res->status);
  8150. }
  8151. }
  8152. TEST_F(ServerTest, PostContentReceiverGzip) {
  8153. cli_.set_compress(true);
  8154. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8156. ASSERT_EQ(StatusCode::OK_200, res->status);
  8157. ASSERT_EQ("content", res->body);
  8158. }
  8159. TEST_F(ServerTest, PutContentReceiver) {
  8160. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8162. ASSERT_EQ(StatusCode::OK_200, res->status);
  8163. ASSERT_EQ("content", res->body);
  8164. }
  8165. TEST_F(ServerTest, PatchContentReceiver) {
  8166. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. ASSERT_EQ(StatusCode::OK_200, res->status);
  8169. ASSERT_EQ("content", res->body);
  8170. }
  8171. template <typename ClientType>
  8172. void TestWithHeadersAndContentReceiver(
  8173. ClientType &cli,
  8174. std::function<Result(ClientType &, const std::string &, const Headers &,
  8175. const std::string &, const std::string &,
  8176. ContentReceiver, DownloadProgress)>
  8177. request_func) {
  8178. Headers headers;
  8179. headers.emplace("X-Custom-Header", "test-value");
  8180. std::string received_body;
  8181. auto res = request_func(
  8182. cli, "/content_receiver", headers, "content", "application/json",
  8183. [&](const char *data, size_t data_length) {
  8184. received_body.append(data, data_length);
  8185. return true;
  8186. },
  8187. nullptr);
  8188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8189. EXPECT_EQ(StatusCode::OK_200, res->status);
  8190. EXPECT_EQ("content", received_body);
  8191. }
  8192. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8193. #ifdef CPPHTTPLIB_SSL_ENABLED
  8194. using ClientT = SSLClient;
  8195. #else
  8196. using ClientT = Client;
  8197. #endif
  8198. TestWithHeadersAndContentReceiver<ClientT>(
  8199. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8200. const std::string &body, const std::string &content_type,
  8201. ContentReceiver receiver, DownloadProgress progress) {
  8202. return cli.Post(path, headers, body, content_type, receiver, progress);
  8203. });
  8204. }
  8205. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8206. #ifdef CPPHTTPLIB_SSL_ENABLED
  8207. using ClientT = SSLClient;
  8208. #else
  8209. using ClientT = Client;
  8210. #endif
  8211. TestWithHeadersAndContentReceiver<ClientT>(
  8212. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8213. const std::string &body, const std::string &content_type,
  8214. ContentReceiver receiver, DownloadProgress progress) {
  8215. return cli.Put(path, headers, body, content_type, receiver, progress);
  8216. });
  8217. }
  8218. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8219. #ifdef CPPHTTPLIB_SSL_ENABLED
  8220. using ClientT = SSLClient;
  8221. #else
  8222. using ClientT = Client;
  8223. #endif
  8224. TestWithHeadersAndContentReceiver<ClientT>(
  8225. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8226. const std::string &body, const std::string &content_type,
  8227. ContentReceiver receiver, DownloadProgress progress) {
  8228. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8229. });
  8230. }
  8231. template <typename ClientType>
  8232. void TestWithHeadersAndContentReceiverWithProgress(
  8233. ClientType &cli,
  8234. std::function<Result(ClientType &, const std::string &, const Headers &,
  8235. const std::string &, const std::string &,
  8236. ContentReceiver, DownloadProgress)>
  8237. request_func) {
  8238. Headers headers;
  8239. headers.emplace("X-Test-Header", "progress-test");
  8240. std::string received_body;
  8241. auto progress_called = false;
  8242. auto res = request_func(
  8243. cli, "/content_receiver", headers, "content", "text/plain",
  8244. [&](const char *data, size_t data_length) {
  8245. received_body.append(data, data_length);
  8246. return true;
  8247. },
  8248. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8249. progress_called = true;
  8250. return true;
  8251. });
  8252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8253. EXPECT_EQ(StatusCode::OK_200, res->status);
  8254. EXPECT_EQ("content", received_body);
  8255. EXPECT_TRUE(progress_called);
  8256. }
  8257. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8258. #ifdef CPPHTTPLIB_SSL_ENABLED
  8259. using ClientT = SSLClient;
  8260. #else
  8261. using ClientT = Client;
  8262. #endif
  8263. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8264. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8265. const std::string &body, const std::string &content_type,
  8266. ContentReceiver receiver, DownloadProgress progress) {
  8267. return cli.Post(path, headers, body, content_type, receiver, progress);
  8268. });
  8269. }
  8270. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8271. #ifdef CPPHTTPLIB_SSL_ENABLED
  8272. using ClientT = SSLClient;
  8273. #else
  8274. using ClientT = Client;
  8275. #endif
  8276. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8277. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8278. const std::string &body, const std::string &content_type,
  8279. ContentReceiver receiver, DownloadProgress progress) {
  8280. return cli.Put(path, headers, body, content_type, receiver, progress);
  8281. });
  8282. }
  8283. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8284. #ifdef CPPHTTPLIB_SSL_ENABLED
  8285. using ClientT = SSLClient;
  8286. #else
  8287. using ClientT = Client;
  8288. #endif
  8289. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8290. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8291. const std::string &body, const std::string &content_type,
  8292. ContentReceiver receiver, DownloadProgress progress) {
  8293. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8294. });
  8295. }
  8296. template <typename ClientType>
  8297. void TestWithHeadersAndContentReceiverError(
  8298. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8299. const Headers &, const std::string &,
  8300. const std::string &, ContentReceiver)>
  8301. request_func) {
  8302. Headers headers;
  8303. headers.emplace("X-Error-Test", "true");
  8304. std::string received_body;
  8305. auto receiver_failed = false;
  8306. auto res =
  8307. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8308. [&](const char *data, size_t data_length) {
  8309. received_body.append(data, data_length);
  8310. receiver_failed = true;
  8311. return false;
  8312. });
  8313. ASSERT_FALSE(res);
  8314. EXPECT_TRUE(receiver_failed);
  8315. }
  8316. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8317. #ifdef CPPHTTPLIB_SSL_ENABLED
  8318. using ClientT = SSLClient;
  8319. #else
  8320. using ClientT = Client;
  8321. #endif
  8322. TestWithHeadersAndContentReceiverError<ClientT>(
  8323. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8324. const std::string &body, const std::string &content_type,
  8325. ContentReceiver receiver) {
  8326. return cli.Post(path, headers, body, content_type, receiver);
  8327. });
  8328. }
  8329. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8330. #ifdef CPPHTTPLIB_SSL_ENABLED
  8331. using ClientT = SSLClient;
  8332. #else
  8333. using ClientT = Client;
  8334. #endif
  8335. TestWithHeadersAndContentReceiverError<ClientT>(
  8336. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8337. const std::string &body, const std::string &content_type,
  8338. ContentReceiver receiver) {
  8339. return cli.Put(path, headers, body, content_type, receiver);
  8340. });
  8341. }
  8342. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8343. #ifdef CPPHTTPLIB_SSL_ENABLED
  8344. using ClientT = SSLClient;
  8345. #else
  8346. using ClientT = Client;
  8347. #endif
  8348. TestWithHeadersAndContentReceiverError<ClientT>(
  8349. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8350. const std::string &body, const std::string &content_type,
  8351. ContentReceiver receiver) {
  8352. return cli.Patch(path, headers, body, content_type, receiver);
  8353. });
  8354. }
  8355. TEST_F(ServerTest, PostQueryStringAndBody) {
  8356. auto res =
  8357. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8359. ASSERT_EQ(StatusCode::OK_200, res->status);
  8360. }
  8361. TEST_F(ServerTest, HTTP2Magic) {
  8362. Request req;
  8363. req.method = "PRI";
  8364. req.path = "*";
  8365. req.body = "SM";
  8366. auto res = std::make_shared<Response>();
  8367. auto error = Error::Success;
  8368. auto ret = cli_.send(req, *res, error);
  8369. ASSERT_TRUE(ret);
  8370. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8371. }
  8372. TEST_F(ServerTest, KeepAlive) {
  8373. auto res = cli_.Get("/hi");
  8374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8375. EXPECT_EQ(StatusCode::OK_200, res->status);
  8376. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8377. EXPECT_EQ("Hello World!", res->body);
  8378. res = cli_.Get("/hi");
  8379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8380. EXPECT_EQ(StatusCode::OK_200, res->status);
  8381. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8382. EXPECT_EQ("Hello World!", res->body);
  8383. res = cli_.Get("/hi");
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8387. EXPECT_EQ("Hello World!", res->body);
  8388. res = cli_.Get("/not-exist");
  8389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8390. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8391. res = cli_.Post("/empty", "", "text/plain");
  8392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8393. EXPECT_EQ(StatusCode::OK_200, res->status);
  8394. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8395. EXPECT_EQ("empty", res->body);
  8396. EXPECT_EQ("close", res->get_header_value("Connection"));
  8397. res = cli_.Post(
  8398. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8399. "text/plain");
  8400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8401. EXPECT_EQ(StatusCode::OK_200, res->status);
  8402. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8403. EXPECT_EQ("empty", res->body);
  8404. cli_.set_keep_alive(false);
  8405. res = cli_.Get("/last-request");
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_EQ(StatusCode::OK_200, res->status);
  8408. EXPECT_EQ("close", res->get_header_value("Connection"));
  8409. }
  8410. TEST_F(ServerTest, TooManyRedirect) {
  8411. cli_.set_follow_location(true);
  8412. auto res = cli_.Get("/redirect/0");
  8413. ASSERT_TRUE(!res);
  8414. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8415. }
  8416. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8417. Request req;
  8418. req.method = "FOOBAR";
  8419. req.path = "/hi";
  8420. cli_.set_keep_alive(true);
  8421. auto res = cli_.send(req);
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8424. EXPECT_EQ("close", res->get_header_value("Connection"));
  8425. EXPECT_FALSE(cli_.is_socket_open());
  8426. }
  8427. TEST_F(ServerTest, CustomRouteReadsBody) {
  8428. const std::string xml =
  8429. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8430. Request req;
  8431. req.method = "PROPFIND";
  8432. req.path = "/dav/dir";
  8433. req.set_header("Depth", "1");
  8434. req.body = xml;
  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(xml, res->body);
  8439. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8440. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8441. }
  8442. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8443. Request req;
  8444. req.method = "PROPFIND";
  8445. req.path = "/dav/42";
  8446. auto res = cli_.send(req);
  8447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8448. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8449. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8450. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8451. }
  8452. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8453. Request req;
  8454. req.method = "PROPFIND";
  8455. req.path = "/dav-re/123";
  8456. auto res = cli_.send(req);
  8457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8458. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8459. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8460. }
  8461. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8462. Request req;
  8463. req.method = "MKCOL";
  8464. req.path = "/dav-mkcol";
  8465. auto res = cli_.send(req);
  8466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8467. EXPECT_EQ(StatusCode::Created_201, res->status);
  8468. }
  8469. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8470. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8471. Request req;
  8472. req.method = "REPORT";
  8473. req.path = "/dav-report";
  8474. req.body = xml;
  8475. auto res = cli_.send(req);
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8478. EXPECT_EQ(xml, res->body);
  8479. }
  8480. // A content reader route must fire even when the request carries no body,
  8481. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8482. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8483. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8484. Request req;
  8485. req.method = "REPORT";
  8486. req.path = "/dav-report";
  8487. auto res = cli_.send(req);
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8490. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8491. }
  8492. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8493. Request req;
  8494. req.method = "PROPFIND";
  8495. req.path = "/not-dav";
  8496. auto res = cli_.send(req);
  8497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8499. }
  8500. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8501. Request req;
  8502. req.method = "UNLOCK";
  8503. req.path = "/dav/dir";
  8504. cli_.set_keep_alive(true);
  8505. auto res = cli_.send(req);
  8506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8507. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8508. EXPECT_EQ("close", res->get_header_value("Connection"));
  8509. EXPECT_FALSE(cli_.is_socket_open());
  8510. }
  8511. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8512. // The mount point serves this path, but only for GET and HEAD.
  8513. auto get_res = cli_.Get("/dir/index.html");
  8514. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8515. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8516. Request req;
  8517. req.method = "PROPFIND";
  8518. req.path = "/dir/index.html";
  8519. auto res = cli_.send(req);
  8520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8521. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8522. }
  8523. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8524. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8525. cli_.set_keep_alive(true);
  8526. for (auto i = 0; i < 2; i++) {
  8527. Request req;
  8528. req.method = "PROPFIND";
  8529. req.path = "/dav/dir";
  8530. req.body = xml;
  8531. auto res = cli_.send(req);
  8532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8533. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8534. EXPECT_EQ(xml, res->body);
  8535. EXPECT_TRUE(cli_.is_socket_open());
  8536. }
  8537. // A built-in method must still be served on the same connection.
  8538. cli_.set_keep_alive(false);
  8539. auto res = cli_.Get("/hi");
  8540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8541. EXPECT_EQ(StatusCode::OK_200, res->status);
  8542. EXPECT_EQ("close", res->get_header_value("Connection"));
  8543. }
  8544. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8545. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8546. Request req;
  8547. req.method = "PROPFIND";
  8548. req.path = "/dav/dir";
  8549. req.set_header("Expect", "100-continue");
  8550. req.body = xml;
  8551. auto res = cli_.send(req);
  8552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8553. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8554. EXPECT_EQ(xml, res->body);
  8555. }
  8556. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8557. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8558. TEST_F(ServerTest, Gzip) {
  8559. Headers headers;
  8560. headers.emplace("Accept-Encoding", "gzip, deflate");
  8561. auto res = cli_.Get("/compress", headers);
  8562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8563. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8564. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8565. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8566. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8567. "7890123456789012345678901234567890",
  8568. res->body);
  8569. EXPECT_EQ(StatusCode::OK_200, res->status);
  8570. }
  8571. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8572. Headers headers;
  8573. headers.emplace("Accept-Encoding", "gzip, deflate");
  8574. auto res = cli_.Get("/compress-with-charset", headers);
  8575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8576. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8577. EXPECT_EQ("application/json; charset=utf-8",
  8578. res->get_header_value("Content-Type"));
  8579. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8580. "7890123456789012345678901234567890",
  8581. res->body);
  8582. EXPECT_EQ(StatusCode::OK_200, res->status);
  8583. }
  8584. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8585. Headers headers;
  8586. headers.emplace("Accept-Encoding", "");
  8587. auto res = cli_.Get("/compress", headers);
  8588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8589. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8591. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8592. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8593. "7890123456789012345678901234567890",
  8594. res->body);
  8595. EXPECT_EQ(StatusCode::OK_200, res->status);
  8596. }
  8597. TEST_F(ServerTest, GzipWithContentReceiver) {
  8598. Headers headers;
  8599. headers.emplace("Accept-Encoding", "gzip, deflate");
  8600. std::string body;
  8601. auto res =
  8602. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8603. EXPECT_EQ(100U, data_length);
  8604. body.append(data, data_length);
  8605. return true;
  8606. });
  8607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8608. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8609. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8610. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8611. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8612. "7890123456789012345678901234567890",
  8613. body);
  8614. EXPECT_EQ(StatusCode::OK_200, res->status);
  8615. }
  8616. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8617. Headers headers;
  8618. headers.emplace("Accept-Encoding", "gzip, deflate");
  8619. cli_.set_decompress(false);
  8620. auto res = cli_.Get("/compress", headers);
  8621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8622. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8623. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8624. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8625. EXPECT_EQ(33U, res->body.size());
  8626. EXPECT_EQ(StatusCode::OK_200, res->status);
  8627. }
  8628. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8629. Headers headers;
  8630. headers.emplace("Accept-Encoding", "");
  8631. std::string body;
  8632. auto res =
  8633. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8634. EXPECT_EQ(100U, data_length);
  8635. body.append(data, data_length);
  8636. return true;
  8637. });
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8640. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8641. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8642. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8643. "7890123456789012345678901234567890",
  8644. body);
  8645. EXPECT_EQ(StatusCode::OK_200, res->status);
  8646. }
  8647. TEST_F(ServerTest, NoGzip) {
  8648. Headers headers;
  8649. headers.emplace("Accept-Encoding", "gzip, deflate");
  8650. auto res = cli_.Get("/nocompress", headers);
  8651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8652. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8653. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8654. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8655. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8656. "7890123456789012345678901234567890",
  8657. res->body);
  8658. EXPECT_EQ(StatusCode::OK_200, res->status);
  8659. }
  8660. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8661. Headers headers;
  8662. headers.emplace("Accept-Encoding", "gzip, deflate");
  8663. std::string body;
  8664. auto res = cli_.Get("/nocompress", headers,
  8665. [&](const char *data, size_t data_length) {
  8666. EXPECT_EQ(100U, data_length);
  8667. body.append(data, data_length);
  8668. return true;
  8669. });
  8670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8671. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8672. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8673. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8674. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8675. "7890123456789012345678901234567890",
  8676. body);
  8677. EXPECT_EQ(StatusCode::OK_200, res->status);
  8678. }
  8679. TEST_F(ServerTest, MultipartFormDataGzip) {
  8680. UploadFormDataItems items = {
  8681. {"key1", "test", "", ""},
  8682. {"key2", "--abcdefg123", "", ""},
  8683. };
  8684. cli_.set_compress(true);
  8685. auto res = cli_.Post("/compress-multipart", items);
  8686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8687. EXPECT_EQ(StatusCode::OK_200, res->status);
  8688. }
  8689. #endif
  8690. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8691. // Static file compression is opt-in, so these run their own server rather than
  8692. // flipping it on for the shared ServerTest fixture, which would silently
  8693. // rewrite what every other static file test is asserting.
  8694. class StaticFileCompressionTest : public ::testing::Test {
  8695. protected:
  8696. void TearDown() override {
  8697. if (t_.joinable()) {
  8698. svr_.stop();
  8699. t_.join();
  8700. }
  8701. }
  8702. int start(const std::function<void(Server &)> &configure = nullptr) {
  8703. // Serves the same tree as a directory of build-time compressed assets
  8704. // would be served: the mount point names the coding the files are already
  8705. // stored in. Registered before "/" so it is the one that matches.
  8706. svr_.set_mount_point("/pre-encoded", "./www",
  8707. {{"Content-Encoding", "gzip"}});
  8708. svr_.set_mount_point("/", "./www");
  8709. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8710. res.set_file_content("./www/dir/index.html", "text/html");
  8711. });
  8712. svr_.Get("/pre-encoded-file-content",
  8713. [](const Request & /*req*/, Response &res) {
  8714. res.set_header("Content-Encoding", "gzip");
  8715. res.set_file_content("./www/dir/index.html", "text/html");
  8716. });
  8717. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8718. res.set_content_provider(
  8719. 6, "text/plain",
  8720. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8721. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8722. return true;
  8723. });
  8724. });
  8725. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8726. res.set_content_provider(
  8727. 1000, "text/plain",
  8728. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8729. if (offset < 100) {
  8730. std::string data(100, 'A');
  8731. sink.write(data.data(), data.size());
  8732. return true;
  8733. }
  8734. std::this_thread::sleep_for(std::chrono::seconds(2));
  8735. std::string data(900, 'B');
  8736. sink.write(data.data(), data.size());
  8737. return true;
  8738. });
  8739. });
  8740. if (configure) { configure(svr_); }
  8741. auto port = svr_.bind_to_any_port(HOST);
  8742. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8743. svr_.wait_until_ready();
  8744. return port;
  8745. }
  8746. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8747. // Every file under ./www except 1MB.txt is smaller than the default
  8748. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8749. // it out of the way.
  8750. static void enable_without_floor(Server &svr) {
  8751. svr.set_static_file_compression(true);
  8752. svr.set_static_file_compression_min_length(0);
  8753. }
  8754. Server svr_;
  8755. std::thread t_;
  8756. };
  8757. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8758. auto port = start();
  8759. Client cli(HOST, port);
  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_FALSE(res->has_header("Content-Encoding"));
  8764. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8765. EXPECT_EQ(1048576U, res->body.size());
  8766. }
  8767. TEST_F(StaticFileCompressionTest, MountPoint) {
  8768. auto port = start(enable);
  8769. Client cli(HOST, port);
  8770. cli.set_decompress(false);
  8771. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8773. EXPECT_EQ(StatusCode::OK_200, res->status);
  8774. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8775. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8776. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8777. // The response stays self-delimiting: a length, not a chunked body.
  8778. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8779. EXPECT_EQ(std::to_string(res->body.size()),
  8780. res->get_header_value("Content-Length"));
  8781. EXPECT_LT(res->body.size(), 1048576U);
  8782. EXPECT_FALSE(res->body.empty());
  8783. }
  8784. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8785. auto port = start(enable);
  8786. Client cli(HOST, port);
  8787. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8789. EXPECT_EQ(StatusCode::OK_200, res->status);
  8790. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8791. EXPECT_EQ(1048576U, res->body.size());
  8792. }
  8793. TEST_F(StaticFileCompressionTest, FileContent) {
  8794. auto port = start(enable_without_floor);
  8795. Client cli(HOST, port);
  8796. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8798. EXPECT_EQ(StatusCode::OK_200, res->status);
  8799. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8800. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8801. EXPECT_EQ(104U, res->body.size());
  8802. }
  8803. // A handler that serves an already-encoded file names the coding itself. The
  8804. // file-backed path decided its coding from Accept-Encoding and the content
  8805. // type alone, so it compressed the stored bytes a second time and appended a
  8806. // second Content-Encoding field line.
  8807. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8808. auto port = start(enable_without_floor);
  8809. Client cli(HOST, port);
  8810. cli.set_decompress(false);
  8811. auto res = cli.Get("/pre-encoded-file-content",
  8812. Headers{{"Accept-Encoding", "gzip"}});
  8813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8814. EXPECT_EQ(StatusCode::OK_200, res->status);
  8815. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8816. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8817. // Vary belongs to a coding the server chose, and it chose none here.
  8818. EXPECT_FALSE(res->has_header("Vary"));
  8819. // The file travels exactly as it is stored on disk.
  8820. EXPECT_EQ(104U, res->body.size());
  8821. }
  8822. // The 1MB file clears the default floor, so this one runs the configuration a
  8823. // deployment would actually have.
  8824. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8825. auto port = start(enable);
  8826. Client cli(HOST, port);
  8827. cli.set_decompress(false);
  8828. auto res =
  8829. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8831. EXPECT_EQ(StatusCode::OK_200, res->status);
  8832. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8833. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8834. EXPECT_FALSE(res->has_header("Vary"));
  8835. EXPECT_EQ(1048576U, res->body.size());
  8836. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8837. }
  8838. TEST_F(StaticFileCompressionTest, Head) {
  8839. auto port = start(enable);
  8840. Client cli(HOST, port);
  8841. cli.set_decompress(false);
  8842. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8843. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8844. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8848. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8849. // HEAD still reports the size a GET would return.
  8850. EXPECT_EQ(get->get_header_value("Content-Length"),
  8851. res->get_header_value("Content-Length"));
  8852. EXPECT_TRUE(res->body.empty());
  8853. }
  8854. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8855. auto port = start(enable);
  8856. Client cli(HOST, port);
  8857. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8858. {"Accept-Encoding", "gzip"}});
  8859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8860. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8861. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8862. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8863. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8864. EXPECT_EQ("cd", res->body);
  8865. }
  8866. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8867. auto port = start(enable);
  8868. Client cli(HOST, port);
  8869. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8871. EXPECT_EQ(StatusCode::OK_200, res->status);
  8872. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8873. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8874. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8875. }
  8876. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8877. auto port = start(enable);
  8878. Client cli(HOST, port);
  8879. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8881. EXPECT_EQ(StatusCode::OK_200, res->status);
  8882. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8883. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8884. EXPECT_TRUE(res->body.empty());
  8885. }
  8886. TEST_F(StaticFileCompressionTest, MinLength) {
  8887. auto port = start(enable);
  8888. Client cli(HOST, port);
  8889. // 104 bytes, well under the default floor. Compressing it would add the
  8890. // gzip header and trailer to a body that already fits in one packet.
  8891. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8893. EXPECT_EQ(StatusCode::OK_200, res->status);
  8894. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8895. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8896. }
  8897. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8898. auto port = start([](Server &svr) {
  8899. svr.set_static_file_compression(true);
  8900. svr.set_static_file_compression_min_length(1);
  8901. });
  8902. Client cli(HOST, port);
  8903. cli.set_decompress(false);
  8904. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8906. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8907. // A 9-byte file comes back larger than it went in, because gzip's header and
  8908. // trailer outweigh anything deflate can save. That is the end of the range
  8909. // the floor exists to keep out.
  8910. EXPECT_GT(res->body.size(), 9U);
  8911. }
  8912. TEST_F(StaticFileCompressionTest, MaxLength) {
  8913. auto port = start([](Server &svr) {
  8914. svr.set_static_file_compression(true);
  8915. svr.set_static_file_compression_min_length(0);
  8916. svr.set_static_file_compression_max_length(1024);
  8917. });
  8918. Client cli(HOST, port);
  8919. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8920. // defines `small` as a macro on Windows.
  8921. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8922. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8923. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8924. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8925. // Under it: compressed.
  8926. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8927. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8928. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8929. }
  8930. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8931. auto port = start(enable_without_floor);
  8932. Client cli(HOST, port);
  8933. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8934. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8935. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8936. auto identity_etag = identity->get_header_value("ETag");
  8937. ASSERT_FALSE(identity_etag.empty());
  8938. auto gzipped =
  8939. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8940. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8941. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8942. auto gzip_etag = gzipped->get_header_value("ETag");
  8943. ASSERT_FALSE(gzip_etag.empty());
  8944. // Two representations, two validators.
  8945. EXPECT_NE(identity_etag, gzip_etag);
  8946. // Each one revalidates against the request that would produce it...
  8947. auto fresh =
  8948. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8949. {"If-None-Match", gzip_etag}});
  8950. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8951. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8952. auto fresh_identity =
  8953. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8954. {"If-None-Match", identity_etag}});
  8955. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8956. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8957. // ...and not against the other representation.
  8958. auto crossed =
  8959. cli.Get("/dir/index.html",
  8960. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8961. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8962. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8963. }
  8964. // The opt-in covers responses the server reads off disk itself. A caller's own
  8965. // known-length provider keeps its Content-Length and, more importantly, keeps
  8966. // delivering incrementally: routing it through a compressor would hold every
  8967. // write back until zlib's window filled.
  8968. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8969. auto port = start(enable);
  8970. Client cli(HOST, port);
  8971. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8973. EXPECT_EQ(StatusCode::OK_200, res->status);
  8974. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8975. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8976. EXPECT_EQ("aaabbb", res->body);
  8977. }
  8978. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8979. auto port = start(enable);
  8980. Client cli(HOST, port);
  8981. cli.set_read_timeout(1, 0);
  8982. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8983. Headers{{"Accept-Encoding", "gzip"}});
  8984. ASSERT_TRUE(handle.is_valid());
  8985. // The provider writes 100 bytes and then stalls for longer than the read
  8986. // timeout. Those first bytes have to arrive anyway: run the response through
  8987. // a compressor and zlib holds them until its window fills, so the read would
  8988. // come back empty instead.
  8989. char buf[256];
  8990. auto n = handle.read(buf, sizeof(buf));
  8991. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8992. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8993. }
  8994. #endif
  8995. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8996. TEST_F(ServerTest, Brotli) {
  8997. Headers headers;
  8998. headers.emplace("Accept-Encoding", "br");
  8999. auto res = cli_.Get("/compress", headers);
  9000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9001. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9002. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9003. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9004. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9005. "7890123456789012345678901234567890",
  9006. res->body);
  9007. EXPECT_EQ(StatusCode::OK_200, res->status);
  9008. }
  9009. #endif
  9010. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9011. TEST_F(ServerTest, Zstd) {
  9012. Headers headers;
  9013. headers.emplace("Accept-Encoding", "zstd");
  9014. auto res = cli_.Get("/compress", headers);
  9015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9016. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9017. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9018. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9019. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9020. "7890123456789012345678901234567890",
  9021. res->body);
  9022. EXPECT_EQ(StatusCode::OK_200, res->status);
  9023. }
  9024. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9025. Headers headers;
  9026. headers.emplace("Accept-Encoding", "");
  9027. auto res = cli_.Get("/compress", headers);
  9028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9029. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9031. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9032. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9033. "7890123456789012345678901234567890",
  9034. res->body);
  9035. EXPECT_EQ(StatusCode::OK_200, res->status);
  9036. }
  9037. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9038. Headers headers;
  9039. headers.emplace("Accept-Encoding", "zstd");
  9040. std::string body;
  9041. auto res =
  9042. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9043. EXPECT_EQ(100U, data_length);
  9044. body.append(data, data_length);
  9045. return true;
  9046. });
  9047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9048. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9049. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9050. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9051. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9052. "7890123456789012345678901234567890",
  9053. body);
  9054. EXPECT_EQ(StatusCode::OK_200, res->status);
  9055. }
  9056. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9057. Headers headers;
  9058. headers.emplace("Accept-Encoding", "zstd");
  9059. cli_.set_decompress(false);
  9060. auto res = cli_.Get("/compress", headers);
  9061. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9062. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9063. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9064. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9066. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9067. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9068. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. ASSERT_EQ(26U, res->body.size());
  9071. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9072. 0);
  9073. }
  9074. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9075. Headers headers;
  9076. headers.emplace("Accept-Encoding", "");
  9077. std::string body;
  9078. auto res =
  9079. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9080. EXPECT_EQ(100U, data_length);
  9081. body.append(data, data_length);
  9082. return true;
  9083. });
  9084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9085. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9086. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9087. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9088. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9089. "7890123456789012345678901234567890",
  9090. body);
  9091. EXPECT_EQ(StatusCode::OK_200, res->status);
  9092. }
  9093. TEST_F(ServerTest, NoZstd) {
  9094. Headers headers;
  9095. headers.emplace("Accept-Encoding", "zstd");
  9096. auto res = cli_.Get("/nocompress", headers);
  9097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9098. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9099. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9100. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9101. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9102. "7890123456789012345678901234567890",
  9103. res->body);
  9104. EXPECT_EQ(StatusCode::OK_200, res->status);
  9105. }
  9106. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9107. Headers headers;
  9108. headers.emplace("Accept-Encoding", "zstd");
  9109. std::string body;
  9110. auto res = cli_.Get("/nocompress", headers,
  9111. [&](const char *data, size_t data_length) {
  9112. EXPECT_EQ(100U, data_length);
  9113. body.append(data, data_length);
  9114. return true;
  9115. });
  9116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9117. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9118. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9119. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9120. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9121. "7890123456789012345678901234567890",
  9122. body);
  9123. EXPECT_EQ(StatusCode::OK_200, res->status);
  9124. }
  9125. // TODO: How to enable zstd ??
  9126. TEST_F(ServerTest, MultipartFormDataZstd) {
  9127. UploadFormDataItems items = {
  9128. {"key1", "test", "", ""},
  9129. {"key2", "--abcdefg123", "", ""},
  9130. };
  9131. Headers headers;
  9132. headers.emplace("Accept-Encoding", "zstd");
  9133. cli_.set_compress(true);
  9134. auto res = cli_.Post("/compress-multipart", headers, items);
  9135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. }
  9138. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9139. Headers headers;
  9140. headers.emplace("Accept-Encoding", "zstd");
  9141. cli_.set_compress(true);
  9142. auto res = cli_.Put(
  9143. "/put", headers, 3,
  9144. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9145. sink.os << "PUT";
  9146. return true;
  9147. },
  9148. "text/plain");
  9149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9150. EXPECT_EQ(StatusCode::OK_200, res->status);
  9151. EXPECT_EQ("PUT", res->body);
  9152. }
  9153. // Pre-compression logging tests
  9154. TEST_F(ServerTest, PreCompressionLogging) {
  9155. // Test data for compression (matches the actual /compress endpoint content)
  9156. const std::string test_content =
  9157. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9158. "3456789012345678901234567890";
  9159. // Variables to capture logging data
  9160. std::string pre_compression_body;
  9161. std::string pre_compression_content_type;
  9162. std::string pre_compression_content_encoding;
  9163. std::string post_compression_body;
  9164. std::string post_compression_content_type;
  9165. std::string post_compression_content_encoding;
  9166. // Set up pre-compression logger
  9167. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9168. const Response &res) {
  9169. pre_compression_body = res.body;
  9170. pre_compression_content_type = res.get_header_value("Content-Type");
  9171. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9172. });
  9173. // Set up post-compression logger
  9174. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9175. post_compression_body = res.body;
  9176. post_compression_content_type = res.get_header_value("Content-Type");
  9177. post_compression_content_encoding =
  9178. res.get_header_value("Content-Encoding");
  9179. });
  9180. // Test with gzip compression
  9181. Headers headers;
  9182. headers.emplace("Accept-Encoding", "gzip");
  9183. auto res = cli_.Get("/compress", headers);
  9184. // Verify response was compressed
  9185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9186. EXPECT_EQ(StatusCode::OK_200, res->status);
  9187. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9188. // Verify pre-compression logger captured uncompressed content
  9189. EXPECT_EQ(test_content, pre_compression_body);
  9190. EXPECT_EQ("text/plain", pre_compression_content_type);
  9191. EXPECT_TRUE(pre_compression_content_encoding
  9192. .empty()); // No encoding header before compression
  9193. // Verify post-compression logger captured compressed content
  9194. EXPECT_NE(test_content,
  9195. post_compression_body); // Should be different after compression
  9196. EXPECT_EQ("text/plain", post_compression_content_type);
  9197. EXPECT_EQ("gzip", post_compression_content_encoding);
  9198. // Verify compressed content is smaller
  9199. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9200. }
  9201. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9202. const std::string test_content =
  9203. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9204. "3456789012345678901234567890";
  9205. std::string pre_compression_body;
  9206. std::string post_compression_body;
  9207. svr_.set_pre_compression_logger(
  9208. [&](const Request & /*req*/, const Response &res) {
  9209. pre_compression_body = res.body;
  9210. });
  9211. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9212. post_compression_body = res.body;
  9213. });
  9214. Headers headers;
  9215. headers.emplace("Accept-Encoding", "br");
  9216. auto res = cli_.Get("/compress", headers);
  9217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9218. EXPECT_EQ(StatusCode::OK_200, res->status);
  9219. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9220. // Verify pre-compression content is uncompressed
  9221. EXPECT_EQ(test_content, pre_compression_body);
  9222. // Verify post-compression content is compressed
  9223. EXPECT_NE(test_content, post_compression_body);
  9224. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9225. }
  9226. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9227. const std::string test_content =
  9228. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9229. "3456789012345678901234567890";
  9230. std::string pre_compression_body;
  9231. std::string post_compression_body;
  9232. svr_.set_pre_compression_logger(
  9233. [&](const Request & /*req*/, const Response &res) {
  9234. pre_compression_body = res.body;
  9235. });
  9236. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9237. post_compression_body = res.body;
  9238. });
  9239. // Request without compression (use /nocompress endpoint)
  9240. Headers headers;
  9241. auto res = cli_.Get("/nocompress", headers);
  9242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9243. EXPECT_EQ(StatusCode::OK_200, res->status);
  9244. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9245. // Pre-compression logger should not be called when no compression is applied
  9246. EXPECT_TRUE(
  9247. pre_compression_body.empty()); // Pre-compression logger not called
  9248. EXPECT_EQ(
  9249. test_content,
  9250. post_compression_body); // Post-compression logger captures final content
  9251. }
  9252. TEST_F(ServerTest, LoggerSeesContentLength) {
  9253. size_t logged_content_length = 0;
  9254. std::string logged_content_length_header;
  9255. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9256. logged_content_length = res.content_length_;
  9257. logged_content_length_header = res.get_header_value("Content-Length");
  9258. });
  9259. auto res = cli_.Get("/nocompress");
  9260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9261. EXPECT_EQ(StatusCode::OK_200, res->status);
  9262. EXPECT_EQ(res->body.size(), logged_content_length);
  9263. EXPECT_EQ(std::to_string(logged_content_length),
  9264. logged_content_length_header);
  9265. }
  9266. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9267. const std::string test_content =
  9268. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9269. "3456789012345678901234567890";
  9270. std::string pre_compression_body;
  9271. bool pre_logger_called = false;
  9272. // Set only pre-compression logger
  9273. svr_.set_pre_compression_logger(
  9274. [&](const Request & /*req*/, const Response &res) {
  9275. pre_compression_body = res.body;
  9276. pre_logger_called = true;
  9277. });
  9278. Headers headers;
  9279. headers.emplace("Accept-Encoding", "gzip");
  9280. auto res = cli_.Get("/compress", headers);
  9281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9282. EXPECT_EQ(StatusCode::OK_200, res->status);
  9283. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9284. // Verify pre-compression logger was called
  9285. EXPECT_TRUE(pre_logger_called);
  9286. EXPECT_EQ(test_content, pre_compression_body);
  9287. }
  9288. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9289. {
  9290. // Test with Expect: 100-continue header - success case
  9291. // Server returns 100 Continue, client sends body, server returns 200 OK
  9292. Request req;
  9293. req.method = "POST";
  9294. req.path = "/post-large";
  9295. req.set_header("Expect", "100-continue");
  9296. req.body = LARGE_DATA;
  9297. Response res;
  9298. auto error = Error::Success;
  9299. cli_.set_keep_alive(true);
  9300. auto ret = cli_.send(req, res, error);
  9301. EXPECT_TRUE(ret);
  9302. EXPECT_EQ(StatusCode::OK_200, res.status);
  9303. EXPECT_EQ(LARGE_DATA, res.body);
  9304. }
  9305. {
  9306. // Test with Expect: 100-continue header - error case
  9307. // Client should not send the body when server returns an error
  9308. Request req;
  9309. req.method = "POST";
  9310. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9311. req.set_header("Expect", "100-continue");
  9312. req.body = LARGE_DATA;
  9313. Response res;
  9314. auto error = Error::Success;
  9315. auto start = std::chrono::high_resolution_clock::now();
  9316. cli_.set_keep_alive(true);
  9317. auto ret = cli_.send(req, res, error);
  9318. auto end = std::chrono::high_resolution_clock::now();
  9319. auto elapsed =
  9320. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9321. .count();
  9322. // With Expect: 100-continue, request completes successfully but with error
  9323. EXPECT_TRUE(ret);
  9324. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9325. EXPECT_EQ("close", res.get_header_value("Connection"));
  9326. EXPECT_FALSE(cli_.is_socket_open());
  9327. EXPECT_LE(elapsed, 2000);
  9328. }
  9329. {
  9330. // Send an extra GET request to ensure error recovery without hanging
  9331. Request req;
  9332. req.method = "GET";
  9333. req.path = "/hi";
  9334. auto start = std::chrono::high_resolution_clock::now();
  9335. auto res = cli_.send(req);
  9336. auto end = std::chrono::high_resolution_clock::now();
  9337. auto elapsed =
  9338. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9339. .count();
  9340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9341. EXPECT_EQ(StatusCode::OK_200, res->status);
  9342. EXPECT_EQ("Hello World!", res->body);
  9343. EXPECT_LE(elapsed, 500);
  9344. }
  9345. }
  9346. TEST(ZstdDecompressor, ChunkedDecompression) {
  9347. std::string data;
  9348. for (size_t i = 0; i < 32 * 1024; ++i) {
  9349. data.push_back(static_cast<char>('a' + i % 26));
  9350. }
  9351. std::string compressed_data;
  9352. {
  9353. httplib::detail::zstd_compressor compressor;
  9354. bool result = compressor.compress(
  9355. data.data(), data.size(),
  9356. /*last=*/true,
  9357. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9358. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9359. compressed_data_size);
  9360. return true;
  9361. });
  9362. ASSERT_TRUE(result);
  9363. }
  9364. std::string decompressed_data;
  9365. {
  9366. httplib::detail::zstd_decompressor decompressor;
  9367. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9368. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9369. size_t chunk_size = 130;
  9370. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9371. chunk_begin += chunk_size) {
  9372. size_t current_chunk_size =
  9373. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9374. bool result = decompressor.decompress(
  9375. compressed_data.data() + chunk_begin, current_chunk_size,
  9376. [&](const char *decompressed_data_chunk,
  9377. size_t decompressed_data_chunk_size) {
  9378. decompressed_data.insert(decompressed_data.size(),
  9379. decompressed_data_chunk,
  9380. decompressed_data_chunk_size);
  9381. return true;
  9382. });
  9383. ASSERT_TRUE(result);
  9384. }
  9385. }
  9386. ASSERT_EQ(data, decompressed_data);
  9387. }
  9388. TEST(ZstdDecompressor, Decompress) {
  9389. std::string original_text = "Compressed with ZSTD";
  9390. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9391. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9392. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9393. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9394. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9395. std::string decompressed_data;
  9396. {
  9397. httplib::detail::zstd_decompressor decompressor;
  9398. bool result = decompressor.decompress(
  9399. compressed_data.data(), compressed_data.size(),
  9400. [&](const char *decompressed_data_chunk,
  9401. size_t decompressed_data_chunk_size) {
  9402. decompressed_data.insert(decompressed_data.size(),
  9403. decompressed_data_chunk,
  9404. decompressed_data_chunk_size);
  9405. return true;
  9406. });
  9407. ASSERT_TRUE(result);
  9408. }
  9409. ASSERT_EQ(original_text, decompressed_data);
  9410. }
  9411. #endif
  9412. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9413. // separate chunks so that the server sees each part in its own read(). Used to
  9414. // place a read boundary at a specific offset of a request body.
  9415. static bool send_request_in_parts(time_t read_timeout_sec,
  9416. const std::vector<std::string> &parts,
  9417. std::string *resp = nullptr,
  9418. int port = PORT) {
  9419. auto error = Error::Success;
  9420. auto client_sock = detail::create_client_socket(
  9421. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9422. /*connection_timeout_sec=*/5, 0,
  9423. /*read_timeout_sec=*/5, 0,
  9424. /*write_timeout_sec=*/5, 0, std::string(), error);
  9425. if (client_sock == INVALID_SOCKET) { return false; }
  9426. auto ret = detail::process_client_socket(
  9427. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9428. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9429. for (size_t i = 0; i < parts.size(); i++) {
  9430. const auto &part = parts[i];
  9431. if (part.size() !=
  9432. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9433. return false;
  9434. }
  9435. if (i + 1 < parts.size()) {
  9436. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9437. }
  9438. }
  9439. char buf[512];
  9440. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9441. while (line_reader.getline()) {
  9442. if (resp) { *resp += line_reader.ptr(); }
  9443. }
  9444. return true;
  9445. });
  9446. detail::close_socket(client_sock);
  9447. return ret;
  9448. }
  9449. // Sends a raw request to a server listening at HOST:PORT.
  9450. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9451. std::string *resp = nullptr, int port = PORT) {
  9452. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9453. }
  9454. #ifdef CPPHTTPLIB_SSL_ENABLED
  9455. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9456. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9457. ASSERT_TRUE(svr.is_valid());
  9458. svr.set_read_timeout(1, 0);
  9459. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9460. auto se = detail::scope_exit([&] {
  9461. svr.stop();
  9462. t.join();
  9463. ASSERT_FALSE(svr.is_running());
  9464. });
  9465. svr.wait_until_ready();
  9466. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9467. // keeps each wait well within the read timeout. The server gives up a
  9468. // second in, so the bytes sent after that fail.
  9469. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9470. parts.resize(26, std::string(1, '\0'));
  9471. EXPECT_FALSE(send_request_in_parts(5, parts));
  9472. }
  9473. #endif
  9474. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9475. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9476. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9477. const std::vector<std::string> &parts,
  9478. std::string *resp = nullptr,
  9479. int port = PORT) {
  9480. auto error = Error::Success;
  9481. auto sock = detail::create_client_socket(
  9482. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9483. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9484. /*write_timeout_sec=*/5, 0, std::string(), error);
  9485. if (sock == INVALID_SOCKET) { return false; }
  9486. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9487. auto ctx = SSL_CTX_new(TLS_client_method());
  9488. auto ssl = SSL_new(ctx);
  9489. auto ssl_se = detail::scope_exit([&] {
  9490. SSL_free(ssl);
  9491. SSL_CTX_free(ctx);
  9492. });
  9493. SSL_set_fd(ssl, static_cast<int>(sock));
  9494. if (SSL_connect(ssl) != 1) { return false; }
  9495. for (size_t i = 0; i < parts.size(); i++) {
  9496. const auto &part = parts[i];
  9497. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9498. static_cast<int>(part.size())) {
  9499. return false;
  9500. }
  9501. if (i + 1 < parts.size()) {
  9502. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9503. }
  9504. }
  9505. char buf[512];
  9506. int n;
  9507. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9508. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9509. }
  9510. return true;
  9511. }
  9512. #endif
  9513. // The request line, then a header value a byte at a time.
  9514. static std::vector<std::string> slow_request_head_parts() {
  9515. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9516. parts.resize(26, "a");
  9517. parts.emplace_back("\r\n\r\n");
  9518. return parts;
  9519. }
  9520. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9521. // within the one-second read timeout. The server gives up a second in, before
  9522. // the head is complete.
  9523. static void
  9524. expect_slow_request_head_dropped(Server &svr,
  9525. const std::function<std::string()> &send) {
  9526. std::atomic<bool> handled(false);
  9527. svr.Get("/", [&](const Request &, Response &res) {
  9528. handled = true;
  9529. res.set_content("ok", "text/plain");
  9530. });
  9531. svr.set_read_timeout(1, 0);
  9532. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9533. auto se = detail::scope_exit([&] {
  9534. svr.stop();
  9535. t.join();
  9536. ASSERT_FALSE(svr.is_running());
  9537. });
  9538. svr.wait_until_ready();
  9539. auto resp = send();
  9540. EXPECT_FALSE(handled);
  9541. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9542. }
  9543. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9544. Server svr;
  9545. expect_slow_request_head_dropped(svr, [] {
  9546. std::string resp;
  9547. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9548. return resp;
  9549. });
  9550. }
  9551. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9552. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9554. ASSERT_TRUE(svr.is_valid());
  9555. expect_slow_request_head_dropped(svr, [] {
  9556. std::string resp;
  9557. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9558. return resp;
  9559. });
  9560. }
  9561. #endif
  9562. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9563. Server svr;
  9564. std::string header_value;
  9565. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9566. header_value = req.get_header_value("foo");
  9567. res.set_content("ok", "text/plain");
  9568. });
  9569. thread t = thread([&] { svr.listen(HOST, PORT); });
  9570. auto se = detail::scope_exit([&] {
  9571. svr.stop();
  9572. t.join();
  9573. ASSERT_FALSE(svr.is_running());
  9574. });
  9575. svr.wait_until_ready();
  9576. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9577. // like characters are not treated the same - use vertical tab and escape.
  9578. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9579. "foo: \t \v bar \x1B\t \r\n"
  9580. "Connection: close\r\n"
  9581. "\r\n";
  9582. std::string res;
  9583. ASSERT_TRUE(send_request(5, req, &res));
  9584. EXPECT_EQ(header_value, "");
  9585. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9586. }
  9587. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9588. Server svr;
  9589. std::string received;
  9590. svr.Get("/order", [&](const Request &req, Response &res) {
  9591. received = entries_to_string(req.headers);
  9592. res.set_content("ok", "text/plain");
  9593. });
  9594. auto port = svr.bind_to_any_port(HOST);
  9595. thread t = thread([&] { svr.listen_after_bind(); });
  9596. auto se = detail::scope_exit([&] {
  9597. svr.stop();
  9598. t.join();
  9599. ASSERT_FALSE(svr.is_running());
  9600. });
  9601. svr.wait_until_ready();
  9602. const std::string req = "GET /order HTTP/1.1\r\n"
  9603. "Host: localhost\r\n"
  9604. "X-First: 1\r\n"
  9605. "X-Dup: a\r\n"
  9606. "X-Second: 2\r\n"
  9607. "X-Dup: b\r\n"
  9608. "Connection: close\r\n"
  9609. "\r\n";
  9610. std::string res;
  9611. ASSERT_TRUE(send_request(5, req, &res, port));
  9612. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9613. EXPECT_EQ(
  9614. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9615. received);
  9616. }
  9617. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9618. Server svr;
  9619. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9620. res.set_header("Set-Cookie", "first=1");
  9621. res.set_header("X-Between", "y");
  9622. res.set_header("Set-Cookie", "second=2");
  9623. res.set_content("ok", "text/plain");
  9624. });
  9625. auto port = svr.bind_to_any_port(HOST);
  9626. thread t = thread([&] { svr.listen_after_bind(); });
  9627. auto se = detail::scope_exit([&] {
  9628. svr.stop();
  9629. t.join();
  9630. ASSERT_FALSE(svr.is_running());
  9631. });
  9632. svr.wait_until_ready();
  9633. Client cli(HOST, port);
  9634. auto res = cli.Get("/cookies");
  9635. ASSERT_TRUE(res);
  9636. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9637. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9638. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9639. }
  9640. // A stream may send a byte at a time with a small extension on each chunk,
  9641. // however long it runs
  9642. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9643. Server svr;
  9644. svr.Post("/count", [](const Request &req, Response &res) {
  9645. res.set_content(std::to_string(req.body.size()), "text/plain");
  9646. });
  9647. auto port = svr.bind_to_any_port(HOST);
  9648. ASSERT_LT(0, port);
  9649. thread t = thread([&] { svr.listen_after_bind(); });
  9650. auto se = detail::scope_exit([&] {
  9651. svr.stop();
  9652. t.join();
  9653. ASSERT_FALSE(svr.is_running());
  9654. });
  9655. svr.wait_until_ready();
  9656. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9657. "\r\nTransfer-Encoding: chunked\r\n"
  9658. "Connection: close\r\n\r\n";
  9659. for (auto i = 0; i < 4096; i++) {
  9660. req += "1;a=b\r\nx\r\n";
  9661. }
  9662. req += "0\r\n\r\n";
  9663. std::string res;
  9664. ASSERT_TRUE(send_request(5, req, &res, port));
  9665. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9666. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9667. }
  9668. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9669. Server svr;
  9670. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9671. auto i = new int(0);
  9672. res.set_header("Trailer", "X-Safe, X-Reflected");
  9673. res.set_chunked_content_provider(
  9674. "text/plain",
  9675. [i](size_t /*offset*/, DataSink &sink) {
  9676. if (*i == 0) {
  9677. sink.os << "body";
  9678. } else {
  9679. Headers trailer;
  9680. // A valid trailer that must survive.
  9681. trailer.emplace("X-Safe", "safe");
  9682. // Attacker-controlled value carrying CR/LF (response splitting).
  9683. trailer.emplace("X-Reflected",
  9684. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9685. // Attacker-controlled name carrying CR/LF.
  9686. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9687. sink.done_with_trailer(trailer);
  9688. }
  9689. (*i)++;
  9690. return true;
  9691. },
  9692. [i](bool /*success*/) { delete i; });
  9693. });
  9694. thread t = thread([&] { svr.listen(HOST, PORT); });
  9695. auto se = detail::scope_exit([&] {
  9696. svr.stop();
  9697. t.join();
  9698. ASSERT_FALSE(svr.is_running());
  9699. });
  9700. svr.wait_until_ready();
  9701. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9702. "Host: " + HOST +
  9703. "\r\n"
  9704. "Connection: close\r\n"
  9705. "\r\n";
  9706. std::string res;
  9707. ASSERT_TRUE(send_request(5, req, &res));
  9708. // The injected fields must not appear anywhere in the raw response.
  9709. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9710. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9711. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9712. // Invalid trailers are dropped entirely, matching set_header().
  9713. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9714. // The valid trailer still passes through.
  9715. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9716. }
  9717. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9718. // A custom header writer gets only the fields the default one writes
  9719. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9720. std::string s;
  9721. for (const auto &h : hdrs) {
  9722. s += h.first + ": " + h.second + "\r\n";
  9723. }
  9724. s += "\r\n";
  9725. return strm.write(s.data(), s.size());
  9726. };
  9727. for (auto custom_writer : {false, true}) {
  9728. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9729. Server svr;
  9730. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9731. svr.set_post_routing_handler([](const Request &, Response &res) {
  9732. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9733. });
  9734. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9735. // res.headers is a public field an application can populate directly,
  9736. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9737. // A valid header that must survive.
  9738. res.headers.emplace("X-Safe", "safe");
  9739. // Attacker-controlled value carrying CR/LF (response splitting).
  9740. res.headers.emplace("X-Reflected",
  9741. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9742. // Attacker-controlled name carrying CR/LF.
  9743. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9744. res.set_content("body", "text/plain");
  9745. });
  9746. thread t = thread([&] { svr.listen(HOST, PORT); });
  9747. auto se = detail::scope_exit([&] {
  9748. svr.stop();
  9749. t.join();
  9750. ASSERT_FALSE(svr.is_running());
  9751. });
  9752. svr.wait_until_ready();
  9753. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9754. "Host: " + HOST +
  9755. "\r\n"
  9756. "Connection: close\r\n"
  9757. "\r\n";
  9758. std::string res;
  9759. ASSERT_TRUE(send_request(5, req, &res));
  9760. // The injected fields must not appear anywhere in the raw response.
  9761. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9762. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9763. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9764. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9765. // Invalid headers are dropped entirely, matching set_header().
  9766. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9767. // The valid header still passes through.
  9768. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9769. }
  9770. }
  9771. // Forward declaration: in split builds split.py strips `inline` and moves the
  9772. // definition into httplib.cc, so detail::write_request_line is not visible from
  9773. // the public httplib.h. Re-declaring it here lets the tests link against the
  9774. // symbol in both header-only and split builds.
  9775. namespace httplib {
  9776. namespace detail {
  9777. ssize_t write_request_line(Stream &strm, const std::string &method,
  9778. const std::string &path);
  9779. } // namespace detail
  9780. } // namespace httplib
  9781. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9782. // A well-formed target is written verbatim.
  9783. {
  9784. detail::BufferStream strm;
  9785. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9786. EXPECT_GT(n, 0);
  9787. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9788. }
  9789. // A target carrying CR/LF, SP or other control octets must be rejected
  9790. // before anything reaches the wire, otherwise it splits the request line and
  9791. // injects a header or a whole request.
  9792. const std::string evil_targets[] = {
  9793. "/a\r\nInjected: pwned",
  9794. "/a\rInjected",
  9795. "/a\nInjected",
  9796. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9797. "/a b",
  9798. "/a\tb",
  9799. "/a\x7f",
  9800. };
  9801. for (const auto &evil : evil_targets) {
  9802. detail::BufferStream strm;
  9803. auto n = detail::write_request_line(strm, "GET", evil);
  9804. EXPECT_LT(n, 0);
  9805. EXPECT_TRUE(strm.get_buffer().empty());
  9806. }
  9807. }
  9808. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9809. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9810. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9811. // target reaches write_request. The client must fail cleanly with
  9812. // Error::Write instead of putting a request-line-less, header-injecting
  9813. // request on the wire.
  9814. Server svr;
  9815. svr.Get("/a", [](const Request &, Response &res) {
  9816. res.set_content("ok", "text/plain");
  9817. });
  9818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9819. auto se = detail::scope_exit([&] {
  9820. svr.stop();
  9821. thread.join();
  9822. ASSERT_FALSE(svr.is_running());
  9823. });
  9824. svr.wait_until_ready();
  9825. {
  9826. Client cli(HOST, PORT);
  9827. cli.set_path_encode(false);
  9828. // The request is rejected before anything is written, so the connection
  9829. // stays silent and the subsequent response read would otherwise block for
  9830. // the full default read timeout. Shorten it -- the assertion is on the
  9831. // error, not the timeout.
  9832. cli.set_read_timeout(1, 0);
  9833. auto res = cli.Get("/a\r\nInjected: pwned");
  9834. EXPECT_FALSE(res);
  9835. EXPECT_EQ(Error::Write, res.error());
  9836. }
  9837. }
  9838. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9839. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9840. // including extension methods.
  9841. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9842. for (const auto &method : good_methods) {
  9843. detail::BufferStream strm;
  9844. auto n = detail::write_request_line(strm, method, "/");
  9845. EXPECT_GT(n, 0);
  9846. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9847. }
  9848. // A method carrying CR/LF would split the request line and smuggle a whole
  9849. // request ahead of the real one. A space or an empty method corrupts the
  9850. // request line. All must be rejected before anything reaches the wire.
  9851. const std::string evil_methods[] = {
  9852. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9853. "GET\r\nInjected: pwned",
  9854. "GET\r",
  9855. "GET\n",
  9856. "GE T",
  9857. "",
  9858. };
  9859. for (const auto &evil : evil_methods) {
  9860. detail::BufferStream strm;
  9861. auto n = detail::write_request_line(strm, evil, "/");
  9862. EXPECT_LT(n, 0);
  9863. EXPECT_TRUE(strm.get_buffer().empty());
  9864. }
  9865. }
  9866. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9867. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9868. // through Client::send must fail with Error::Write and no request, neither
  9869. // the smuggled one nor the real one, may reach the server.
  9870. Server svr;
  9871. std::atomic<int> request_count(0);
  9872. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9873. request_count++;
  9874. res.status = StatusCode::OK_200;
  9875. return Server::HandlerResponse::Handled;
  9876. });
  9877. auto port = svr.bind_to_any_port(HOST);
  9878. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9879. auto se = detail::scope_exit([&] {
  9880. svr.stop();
  9881. thread.join();
  9882. ASSERT_FALSE(svr.is_running());
  9883. });
  9884. svr.wait_until_ready();
  9885. {
  9886. Client cli(HOST, port);
  9887. const std::string evil_methods[] = {
  9888. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9889. "GE T",
  9890. "",
  9891. };
  9892. for (const auto &evil : evil_methods) {
  9893. Request req;
  9894. req.method = evil;
  9895. req.path = "/";
  9896. auto res = cli.send(req);
  9897. EXPECT_FALSE(res);
  9898. EXPECT_EQ(Error::Write, res.error());
  9899. }
  9900. auto handle =
  9901. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9902. EXPECT_FALSE(handle.is_valid());
  9903. EXPECT_EQ(Error::Write, handle.error);
  9904. // A valid request on the same client still goes through.
  9905. auto res = cli.Get("/");
  9906. ASSERT_TRUE(res);
  9907. EXPECT_EQ(StatusCode::OK_200, res->status);
  9908. }
  9909. EXPECT_EQ(1, request_count.load());
  9910. }
  9911. // Sends a raw request and verifies that there isn't a crash or exception.
  9912. static void test_raw_request(const std::string &req,
  9913. std::string *out = nullptr) {
  9914. Server svr;
  9915. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9916. res.set_content("ok", "text/plain");
  9917. });
  9918. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9919. res.set_content("ok", "text/plain");
  9920. });
  9921. svr.Get("/header_field_value_check",
  9922. [&](const Request & /*req*/, Response &res) {
  9923. res.set_content("ok", "text/plain");
  9924. });
  9925. svr.CustomRoute("PROPFIND", "/dav",
  9926. [&](const Request & /*req*/, Response &res) {
  9927. res.status = StatusCode::MultiStatus_207;
  9928. });
  9929. // Server read timeout must be longer than the client read timeout for the
  9930. // bug to reproduce, probably to force the server to process a request
  9931. // without a trailing blank line.
  9932. const time_t client_read_timeout_sec = 1;
  9933. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9934. bool listen_thread_ok = false;
  9935. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9936. auto se = detail::scope_exit([&] {
  9937. svr.stop();
  9938. t.join();
  9939. ASSERT_FALSE(svr.is_running());
  9940. EXPECT_TRUE(listen_thread_ok);
  9941. });
  9942. svr.wait_until_ready();
  9943. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9944. }
  9945. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9946. // A certain header line causes an exception if the header property is parsed
  9947. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9948. test_raw_request(
  9949. "GET /hi HTTP/1.1\r\n"
  9950. " : "
  9951. " "
  9952. " ");
  9953. }
  9954. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9955. // A certain header line causes an exception if the header property *name* is
  9956. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9957. // greedy matcher and requires backtracking when there are a lot of ":"
  9958. // characters.
  9959. // This occurs with libc++ but not libstdc++.
  9960. test_raw_request(
  9961. "GET /hi HTTP/1.1\r\n"
  9962. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9963. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9964. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9965. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9966. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9967. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9968. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9969. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9970. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9971. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9972. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9973. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9974. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9975. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9976. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9977. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9978. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9979. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9980. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9981. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9982. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9983. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9984. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9985. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9986. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9987. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9988. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9989. "&&&%%%");
  9990. }
  9991. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9992. // Make sure this doesn't crash the server.
  9993. // In a previous version of the header line regex, the "\r" rendered the line
  9994. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9995. // a new position where the leading white space ended and the field value
  9996. // began.
  9997. // The crash occurs with libc++ but not libstdc++.
  9998. test_raw_request("GET /hi HTTP/1.1\r\n"
  9999. "a:" +
  10000. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10001. "\r\n"
  10002. "\r\n");
  10003. }
  10004. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10005. const char *rejected[] = {
  10006. // RFC 9112 §3: one SP between the parts, and nothing else
  10007. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10008. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10009. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10010. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10011. // A request-target has no fragment
  10012. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10013. // An HTTP/1.1 request needs a Host
  10014. "GET /hi HTTP/1.1\r\n\r\n",
  10015. };
  10016. for (auto request : rejected) {
  10017. std::string out;
  10018. test_raw_request(request, &out);
  10019. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10020. }
  10021. std::string out;
  10022. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10023. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10024. }
  10025. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10026. // RFC 9112 §6.1
  10027. const char *requests[] = {
  10028. "PUT /put_hi HTTP/1.1\r\n"
  10029. "Host: localhost\r\n"
  10030. "Content-Length: 0\r\n"
  10031. "Transfer-Encoding: chunked\r\n"
  10032. "\r\n"
  10033. "0\r\n\r\n",
  10034. "PUT /put_hi HTTP/1.0\r\n"
  10035. "Connection: keep-alive\r\n"
  10036. "Transfer-Encoding: chunked\r\n"
  10037. "\r\n"
  10038. "0\r\n\r\n",
  10039. };
  10040. for (auto request : requests) {
  10041. std::string out;
  10042. test_raw_request(request, &out);
  10043. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10044. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10045. }
  10046. }
  10047. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10048. std::string out;
  10049. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10050. "Content-Type: text/plain\r\n"
  10051. "Transfer-Encoding: chunked\r\n"
  10052. "\r\n"
  10053. "nothex\r\n",
  10054. &out);
  10055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10056. }
  10057. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10058. std::string out;
  10059. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10060. "Content-Type: text/plain\r\n"
  10061. "Transfer-Encoding: chunked\r\n"
  10062. "\r\n"
  10063. "3\r\n"
  10064. "xyz\r\n"
  10065. "NaN\r\n",
  10066. &out);
  10067. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10068. }
  10069. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10070. std::string out;
  10071. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10072. "Content-Type: text/plain\r\n"
  10073. "Transfer-Encoding: chunked\r\n"
  10074. "\r\n"
  10075. // Length is too large for 64 bits.
  10076. "1ffffffffffffffff\r\n"
  10077. "xyz\r\n",
  10078. &out);
  10079. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10080. }
  10081. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10082. test_raw_request("GET /hi HTTP/1.1\r\n"
  10083. "Content-Type: text/plain\r\n\r");
  10084. }
  10085. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10086. std::string out;
  10087. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10088. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10089. }
  10090. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10091. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10092. std::string out;
  10093. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10094. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10095. }
  10096. }
  10097. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10098. std::string out;
  10099. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10100. "Host: localhost\r\n"
  10101. "Connection: close\r\n\r\n",
  10102. &out);
  10103. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10104. }
  10105. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10106. Server svr;
  10107. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10108. EXPECT_TRUE(!req.remote_addr.empty());
  10109. });
  10110. thread t = thread([&] { svr.listen(HOST, PORT); });
  10111. auto se = detail::scope_exit([&] {
  10112. svr.stop();
  10113. t.join();
  10114. ASSERT_FALSE(svr.is_running());
  10115. });
  10116. svr.wait_until_ready();
  10117. // Send an invalid request line to trigger Bad Request
  10118. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10119. std::string out;
  10120. ASSERT_TRUE(send_request(5, bad_req, &out));
  10121. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10122. }
  10123. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10124. // answered right away rather than blocking on a read that waits for EOF.
  10125. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10126. std::string out;
  10127. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10128. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10129. }
  10130. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10131. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10132. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10133. for (const auto *method : methods) {
  10134. Server svr;
  10135. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10136. EXPECT_FALSE(svr.is_valid()) << method;
  10137. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10138. }
  10139. }
  10140. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10141. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10142. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10143. for (const auto *method : methods) {
  10144. Server svr;
  10145. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10146. EXPECT_FALSE(svr.is_valid()) << method;
  10147. }
  10148. }
  10149. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10150. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10151. "COPY", "MOVE", "LOCK",
  10152. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10153. Server svr;
  10154. for (const auto *method : methods) {
  10155. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10156. }
  10157. EXPECT_TRUE(svr.is_valid());
  10158. }
  10159. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10160. Server svr;
  10161. svr.CustomRoute("POST", "/x",
  10162. [](const Request &, Response &, const ContentReader &) {});
  10163. EXPECT_FALSE(svr.is_valid());
  10164. }
  10165. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10166. Server svr;
  10167. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10168. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10169. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10170. EXPECT_FALSE(svr.is_valid());
  10171. }
  10172. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10173. Server svr;
  10174. auto captured = Error::Success;
  10175. svr.set_error_logger(
  10176. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10177. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10178. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10179. }
  10180. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10181. std::string out;
  10182. std::string request(
  10183. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10184. test_raw_request(request, &out);
  10185. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10186. }
  10187. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10188. std::string out;
  10189. std::string request(
  10190. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10191. test_raw_request(request, &out);
  10192. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10193. }
  10194. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10195. std::string out;
  10196. std::string request(
  10197. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10198. test_raw_request(request, &out);
  10199. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10200. }
  10201. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10202. std::string out;
  10203. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10204. "Host: localhost\r\n"
  10205. "Test: \r\n\r\n",
  10206. &out);
  10207. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10208. }
  10209. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10210. Server svr;
  10211. std::string x_custom;
  10212. std::string cookie;
  10213. std::string xff;
  10214. std::string x_unicode;
  10215. std::string x_iis;
  10216. svr.Get("/check", [&](const Request &req, Response &res) {
  10217. x_custom = req.get_header_value("X-Custom");
  10218. cookie = req.get_header_value("Cookie");
  10219. xff = req.get_header_value("X-Forwarded-For");
  10220. x_unicode = req.get_header_value("X-Unicode");
  10221. x_iis = req.get_header_value("X-IIS");
  10222. res.set_content("ok", "text/plain");
  10223. });
  10224. thread t = thread([&] { svr.listen(HOST, PORT); });
  10225. auto se = detail::scope_exit([&] {
  10226. svr.stop();
  10227. t.join();
  10228. ASSERT_FALSE(svr.is_running());
  10229. });
  10230. svr.wait_until_ready();
  10231. const std::string req = "GET /check HTTP/1.1\r\n"
  10232. "Host: localhost\r\n"
  10233. "X-Custom: a%0D%0AInjected: b\r\n"
  10234. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10235. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10236. "X-Unicode: %E3%81%82\r\n"
  10237. "X-IIS: %u00E9\r\n"
  10238. "Connection: close\r\n"
  10239. "\r\n";
  10240. std::string res;
  10241. ASSERT_TRUE(send_request(5, req, &res));
  10242. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10243. // Every value must be returned verbatim (wire form), with no decoding.
  10244. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10245. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10246. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10247. EXPECT_EQ("%E3%81%82", x_unicode);
  10248. EXPECT_EQ("%u00E9", x_iis);
  10249. }
  10250. // Applications that previously relied on automatic percent-decoding can
  10251. // reproduce the old behavior by explicitly calling decode_path_component()
  10252. // or, for RFC 3986 conformance, decode_uri_component().
  10253. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10254. Server svr;
  10255. std::string decoded;
  10256. svr.Get("/check", [&](const Request &req, Response &res) {
  10257. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10258. res.set_content("ok", "text/plain");
  10259. });
  10260. thread t = thread([&] { svr.listen(HOST, PORT); });
  10261. auto se = detail::scope_exit([&] {
  10262. svr.stop();
  10263. t.join();
  10264. ASSERT_FALSE(svr.is_running());
  10265. });
  10266. svr.wait_until_ready();
  10267. const std::string req = "GET /check HTTP/1.1\r\n"
  10268. "Host: localhost\r\n"
  10269. "X-Custom: hello%20world\r\n"
  10270. "Connection: close\r\n"
  10271. "\r\n";
  10272. std::string res;
  10273. ASSERT_TRUE(send_request(5, req, &res));
  10274. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10275. EXPECT_EQ("hello world", decoded);
  10276. }
  10277. // Regression test for #2033. Browsers send Referer values that include
  10278. // percent-encoded characters such as %0A inside the URL. Decoding the
  10279. // header value would either trip the post-decode CR/LF/NUL guard (the
  10280. // original bug, returning 400) or, after that guard was relaxed, silently
  10281. // store a literal LF — both unacceptable. The wire form must round-trip.
  10282. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10283. Server svr;
  10284. std::string referer;
  10285. svr.Get("/check", [&](const Request &req, Response &res) {
  10286. referer = req.get_header_value("Referer");
  10287. res.set_content("ok", "text/plain");
  10288. });
  10289. thread t = thread([&] { svr.listen(HOST, PORT); });
  10290. auto se = detail::scope_exit([&] {
  10291. svr.stop();
  10292. t.join();
  10293. ASSERT_FALSE(svr.is_running());
  10294. });
  10295. svr.wait_until_ready();
  10296. const std::string req = "GET /check HTTP/1.1\r\n"
  10297. "Host: localhost\r\n"
  10298. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10299. "Connection: close\r\n"
  10300. "\r\n";
  10301. std::string res;
  10302. ASSERT_TRUE(send_request(5, req, &res));
  10303. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10304. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10305. }
  10306. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10307. Server svr;
  10308. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10309. res.set_header("Cache-Control", "no-cache");
  10310. res.set_chunked_content_provider(
  10311. "text/event-stream", [](size_t offset, DataSink &sink) {
  10312. std::string s = "data:";
  10313. s += std::to_string(offset);
  10314. s += "\n\n";
  10315. auto ret = sink.write(s.data(), s.size());
  10316. EXPECT_TRUE(ret);
  10317. std::this_thread::sleep_for(std::chrono::seconds(1));
  10318. return true;
  10319. });
  10320. });
  10321. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10322. svr.wait_until_ready();
  10323. Client client(HOST, PORT);
  10324. const Headers headers = {{"Accept", "text/event-stream"}};
  10325. auto get_thread = std::thread([&client, &headers]() {
  10326. auto res = client.Get(
  10327. "/events", headers,
  10328. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10329. });
  10330. auto se = detail::scope_exit([&] {
  10331. svr.stop();
  10332. get_thread.join();
  10333. listen_thread.join();
  10334. ASSERT_FALSE(svr.is_running());
  10335. });
  10336. // Give GET time to get a few messages.
  10337. std::this_thread::sleep_for(std::chrono::seconds(2));
  10338. }
  10339. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10340. httplib::Server svr;
  10341. svr.Post("/hi",
  10342. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10343. res.status = StatusCode::OK_200;
  10344. });
  10345. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10346. svr.wait_until_ready();
  10347. Client cli(HOST, PORT);
  10348. auto res = cli.Post("/hi", "data", "text/plain");
  10349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10350. EXPECT_EQ(StatusCode::OK_200, res->status);
  10351. svr.stop();
  10352. thread.join();
  10353. ASSERT_FALSE(svr.is_running());
  10354. res = cli.Post("/hi", "data", "text/plain");
  10355. ASSERT_FALSE(res);
  10356. }
  10357. TEST(ServerStopTest, ListenFailure) {
  10358. Server svr;
  10359. auto t = thread([&]() {
  10360. auto ret = svr.listen("????", PORT);
  10361. EXPECT_FALSE(ret);
  10362. });
  10363. svr.wait_until_ready();
  10364. svr.stop();
  10365. t.join();
  10366. }
  10367. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10368. TEST(ServerStopTest, Decommision) {
  10369. Server svr;
  10370. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10371. for (int i = 0; i < 4; i++) {
  10372. auto is_even = !(i % 2);
  10373. std::thread t{[&] {
  10374. try {
  10375. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10376. if (is_even) {
  10377. throw std::runtime_error("Some thing that happens to go wrong.");
  10378. }
  10379. svr.listen(HOST, PORT);
  10380. } catch (...) { svr.decommission(); }
  10381. }};
  10382. svr.wait_until_ready();
  10383. // Server is up
  10384. {
  10385. Client cli(HOST, PORT);
  10386. auto res = cli.Get("/hi");
  10387. if (is_even) {
  10388. EXPECT_FALSE(res);
  10389. } else {
  10390. EXPECT_TRUE(res);
  10391. EXPECT_EQ("hi...", res->body);
  10392. }
  10393. }
  10394. svr.stop();
  10395. t.join();
  10396. // Server is down...
  10397. {
  10398. Client cli(HOST, PORT);
  10399. auto res = cli.Get("/hi");
  10400. EXPECT_FALSE(res);
  10401. }
  10402. }
  10403. }
  10404. #endif
  10405. // Helper function for string body upload progress tests
  10406. template <typename SetupHandler, typename ClientCall>
  10407. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10408. ClientCall &&client_call,
  10409. const string &body) {
  10410. Server svr;
  10411. setup_handler(svr);
  10412. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10413. auto se = detail::scope_exit([&] {
  10414. svr.stop();
  10415. t.join();
  10416. });
  10417. svr.wait_until_ready();
  10418. Client cli(HOST, PORT);
  10419. vector<uint64_t> progress_values;
  10420. bool progress_called = false;
  10421. auto res =
  10422. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10423. progress_values.push_back(current);
  10424. progress_called = true;
  10425. return true;
  10426. });
  10427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10428. EXPECT_EQ(200, res->status);
  10429. EXPECT_TRUE(progress_called);
  10430. }
  10431. TEST(UploadProgressTest, PostStringBodyBasic) {
  10432. TestStringBodyUploadProgress(
  10433. [](Server &svr) {
  10434. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10435. res.set_content("received", "text/plain");
  10436. });
  10437. },
  10438. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10439. return cli.Post("/test", body, "text/plain", progress_callback);
  10440. },
  10441. "test data for upload progress");
  10442. }
  10443. TEST(UploadProgressTest, PutStringBodyBasic) {
  10444. TestStringBodyUploadProgress(
  10445. [](Server &svr) {
  10446. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10447. res.set_content("put received", "text/plain");
  10448. });
  10449. },
  10450. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10451. return cli.Put("/test", body, "text/plain", progress_callback);
  10452. },
  10453. "put test data for upload progress");
  10454. }
  10455. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10456. TestStringBodyUploadProgress(
  10457. [](Server &svr) {
  10458. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10459. res.set_content("patch received", "text/plain");
  10460. });
  10461. },
  10462. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10463. return cli.Patch("/test", body, "text/plain", progress_callback);
  10464. },
  10465. "patch test data for upload progress");
  10466. }
  10467. // Helper function for content provider upload progress tests
  10468. template <typename SetupHandler, typename ClientCall>
  10469. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10470. ClientCall &&client_call) {
  10471. Server svr;
  10472. setup_handler(svr);
  10473. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10474. auto se = detail::scope_exit([&] {
  10475. svr.stop();
  10476. t.join();
  10477. });
  10478. svr.wait_until_ready();
  10479. Client cli(HOST, PORT);
  10480. vector<uint64_t> progress_values;
  10481. auto res =
  10482. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10483. progress_values.push_back(current);
  10484. return true;
  10485. });
  10486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10487. EXPECT_EQ(200, res->status);
  10488. EXPECT_FALSE(progress_values.empty());
  10489. }
  10490. TEST(UploadProgressTest, PostContentProviderProgress) {
  10491. TestContentProviderUploadProgress(
  10492. [](Server &svr) {
  10493. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10494. res.set_content("provider received", "text/plain");
  10495. });
  10496. },
  10497. [](Client &cli, UploadProgress progress_callback) {
  10498. return cli.Post(
  10499. "/test", 9,
  10500. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10501. sink.os << "test data";
  10502. return true;
  10503. },
  10504. "text/plain", progress_callback);
  10505. });
  10506. }
  10507. // Helper function for multipart upload progress tests
  10508. template <typename SetupHandler, typename ClientCall>
  10509. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10510. ClientCall &&client_call,
  10511. const string &endpoint) {
  10512. Server svr;
  10513. setup_handler(svr);
  10514. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10515. auto se = detail::scope_exit([&] {
  10516. svr.stop();
  10517. t.join();
  10518. });
  10519. svr.wait_until_ready();
  10520. Client cli(HOST, PORT);
  10521. vector<uint64_t> progress_values;
  10522. UploadFormDataItems items = {
  10523. {"field1", "value1", "", ""},
  10524. {"field2", "longer value for progress tracking test", "", ""},
  10525. {"file1", "file content data for upload progress", "test.txt",
  10526. "text/plain"}};
  10527. auto res = client_call(cli, endpoint, items,
  10528. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10529. progress_values.push_back(current);
  10530. return true;
  10531. });
  10532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10533. EXPECT_EQ(200, res->status);
  10534. EXPECT_FALSE(progress_values.empty());
  10535. }
  10536. TEST(UploadProgressTest, PostMultipartProgress) {
  10537. TestMultipartUploadProgress(
  10538. [](Server &svr) {
  10539. svr.Post("/multipart", [](const Request &req, Response &res) {
  10540. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10541. res.set_content("multipart received", "text/plain");
  10542. });
  10543. },
  10544. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10545. UploadProgress progress_callback) {
  10546. return cli.Post(endpoint, items, progress_callback);
  10547. },
  10548. "/multipart");
  10549. }
  10550. // Helper function for basic download progress tests
  10551. template <typename SetupHandler, typename ClientCall>
  10552. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10553. ClientCall &&client_call, const string &endpoint,
  10554. size_t expected_content_size) {
  10555. Server svr;
  10556. setup_handler(svr);
  10557. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10558. auto se = detail::scope_exit([&] {
  10559. svr.stop();
  10560. t.join();
  10561. });
  10562. svr.wait_until_ready();
  10563. Client cli(HOST, PORT);
  10564. vector<uint64_t> progress_values;
  10565. auto res = client_call(cli, endpoint,
  10566. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10567. progress_values.push_back(current);
  10568. return true;
  10569. });
  10570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10571. EXPECT_EQ(200, res->status);
  10572. EXPECT_FALSE(progress_values.empty());
  10573. EXPECT_EQ(expected_content_size, res->body.size());
  10574. }
  10575. TEST(DownloadProgressTest, GetBasic) {
  10576. TestBasicDownloadProgress(
  10577. [](Server &svr) {
  10578. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10579. string content(1000, 'D');
  10580. res.set_content(content, "text/plain");
  10581. });
  10582. },
  10583. [](Client &cli, const string &endpoint,
  10584. DownloadProgress progress_callback) {
  10585. return cli.Get(endpoint, progress_callback);
  10586. },
  10587. "/download", 1000u);
  10588. }
  10589. // Helper function for content receiver download progress tests
  10590. template <typename SetupHandler, typename ClientCall>
  10591. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10592. ClientCall &&client_call,
  10593. const string &endpoint,
  10594. size_t expected_content_size) {
  10595. Server svr;
  10596. setup_handler(svr);
  10597. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10598. auto se = detail::scope_exit([&] {
  10599. svr.stop();
  10600. t.join();
  10601. });
  10602. svr.wait_until_ready();
  10603. Client cli(HOST, PORT);
  10604. vector<uint64_t> progress_values;
  10605. string received_body;
  10606. auto res = client_call(
  10607. cli, endpoint,
  10608. [&](const char *data, size_t data_length) -> bool {
  10609. received_body.append(data, data_length);
  10610. return true;
  10611. },
  10612. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10613. progress_values.push_back(current);
  10614. return true;
  10615. });
  10616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10617. EXPECT_EQ(200, res->status);
  10618. EXPECT_FALSE(progress_values.empty());
  10619. EXPECT_EQ(expected_content_size, received_body.size());
  10620. EXPECT_TRUE(res->body.empty());
  10621. }
  10622. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10623. TestContentReceiverDownloadProgress(
  10624. [](Server &svr) {
  10625. svr.Get("/download-receiver",
  10626. [](const Request & /*req*/, Response &res) {
  10627. string content(2000, 'R');
  10628. res.set_content(content, "text/plain");
  10629. });
  10630. },
  10631. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10632. DownloadProgress progress_callback) {
  10633. return cli.Get(endpoint, content_receiver, progress_callback);
  10634. },
  10635. "/download-receiver", 2000u);
  10636. }
  10637. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10638. // A provider reaching a pass with nothing to hand over - an empty buffer
  10639. // popped off a queue, say - must not be taken to mean the body is finished.
  10640. // It used to end the loop with the terminating chunk unwritten while the
  10641. // server still considered the response complete, so the peer waited for an
  10642. // end that never arrived.
  10643. Server svr;
  10644. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10645. auto step = std::make_shared<int>(0);
  10646. res.set_chunked_content_provider("text/plain",
  10647. [step](size_t /*offset*/, DataSink &sink) {
  10648. switch ((*step)++) {
  10649. case 0: sink.write("", 0); break;
  10650. case 1: sink.write("hello", 5); break;
  10651. default: sink.done(); break;
  10652. }
  10653. return true;
  10654. });
  10655. });
  10656. auto port = svr.bind_to_any_port(HOST);
  10657. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10658. auto listen_se = detail::scope_exit([&] {
  10659. svr.stop();
  10660. listen_thread.join();
  10661. ASSERT_FALSE(svr.is_running());
  10662. });
  10663. svr.wait_until_ready();
  10664. Client cli(HOST, port);
  10665. // Without the fix the body is never terminated, so bound the wait rather
  10666. // than letting the test hang on the default read timeout.
  10667. cli.set_read_timeout(5, 0);
  10668. auto res = cli.Get("/stream");
  10669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10670. EXPECT_EQ(StatusCode::OK_200, res->status);
  10671. EXPECT_EQ("hello", res->body);
  10672. }
  10673. TEST(StreamingTest, NoContentLengthStreaming) {
  10674. Server svr;
  10675. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10676. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10677. if (offset < 6) {
  10678. sink.os << (offset < 3 ? "a" : "b");
  10679. } else {
  10680. sink.done();
  10681. }
  10682. return true;
  10683. });
  10684. });
  10685. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10686. auto listen_se = detail::scope_exit([&] {
  10687. svr.stop();
  10688. listen_thread.join();
  10689. ASSERT_FALSE(svr.is_running());
  10690. });
  10691. svr.wait_until_ready();
  10692. Client client(HOST, PORT);
  10693. auto get_thread = std::thread([&client]() {
  10694. std::string s;
  10695. auto res =
  10696. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10697. s += std::string(data, len);
  10698. return true;
  10699. });
  10700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10701. EXPECT_EQ(StatusCode::OK_200, res->status);
  10702. EXPECT_EQ("aaabbb", s);
  10703. });
  10704. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10705. // Give GET time to get a few messages.
  10706. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10707. }
  10708. TEST(MountTest, Unmount) {
  10709. Server svr;
  10710. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10711. auto se = detail::scope_exit([&] {
  10712. svr.stop();
  10713. listen_thread.join();
  10714. ASSERT_FALSE(svr.is_running());
  10715. });
  10716. svr.wait_until_ready();
  10717. Client cli("localhost", PORT);
  10718. svr.set_mount_point("/mount2", "./www2");
  10719. auto res = cli.Get("/");
  10720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10721. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10722. res = cli.Get("/mount2/dir/test.html");
  10723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10724. EXPECT_EQ(StatusCode::OK_200, res->status);
  10725. svr.set_mount_point("/", "./www");
  10726. res = cli.Get("/dir/");
  10727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10728. EXPECT_EQ(StatusCode::OK_200, res->status);
  10729. svr.remove_mount_point("/");
  10730. res = cli.Get("/dir/");
  10731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10732. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10733. svr.remove_mount_point("/mount2");
  10734. res = cli.Get("/mount2/dir/test.html");
  10735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10736. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10737. }
  10738. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10739. Server svr;
  10740. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10741. svr.Get("/api/hello", [](const Request &, Response &res) {
  10742. res.set_content("api", "text/plain");
  10743. });
  10744. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10745. auto se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. listen_thread.join();
  10748. ASSERT_FALSE(svr.is_running());
  10749. });
  10750. svr.wait_until_ready();
  10751. Client cli(HOST, PORT);
  10752. auto res = cli.Get("/dir/test.html");
  10753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10754. EXPECT_EQ(StatusCode::OK_200, res->status);
  10755. res = cli.Get("/api/hello");
  10756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10757. EXPECT_EQ(StatusCode::OK_200, res->status);
  10758. EXPECT_EQ("api", res->body);
  10759. }
  10760. TEST(MountTest, PathSegmentBoundary) {
  10761. Server svr;
  10762. svr.set_mount_point("/mount2", "./www2");
  10763. svr.set_mount_point("/", "./www");
  10764. auto port = svr.bind_to_any_port(HOST);
  10765. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10766. auto se = detail::scope_exit([&] {
  10767. svr.stop();
  10768. listen_thread.join();
  10769. ASSERT_FALSE(svr.is_running());
  10770. });
  10771. svr.wait_until_ready();
  10772. Client cli(HOST, port);
  10773. auto res = cli.Get("/mount2/dir/test.html");
  10774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10775. EXPECT_EQ(StatusCode::OK_200, res->status);
  10776. // "/mount2" must not match part-way through a path segment.
  10777. res = cli.Get("/mount2dir/test.html");
  10778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10779. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10780. // A mount point ending in '/' keeps matching every path below it.
  10781. res = cli.Get("/dir/test.html");
  10782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10783. EXPECT_EQ(StatusCode::OK_200, res->status);
  10784. }
  10785. TEST(MountTest, Redicect) {
  10786. Server svr;
  10787. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10788. auto se = detail::scope_exit([&] {
  10789. svr.stop();
  10790. listen_thread.join();
  10791. ASSERT_FALSE(svr.is_running());
  10792. });
  10793. svr.set_mount_point("/", "./www");
  10794. svr.wait_until_ready();
  10795. Client cli("localhost", PORT);
  10796. auto res = cli.Get("/dir/");
  10797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10798. EXPECT_EQ(StatusCode::OK_200, res->status);
  10799. res = cli.Get("/dir");
  10800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10801. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10802. res = cli.Get("/file");
  10803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10804. EXPECT_EQ(StatusCode::OK_200, res->status);
  10805. res = cli.Get("/file/");
  10806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10807. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10808. cli.set_follow_location(true);
  10809. res = cli.Get("/dir");
  10810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10811. EXPECT_EQ(StatusCode::OK_200, res->status);
  10812. }
  10813. TEST(MountTest, MultibytesPathName) {
  10814. Server svr;
  10815. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10816. auto se = detail::scope_exit([&] {
  10817. svr.stop();
  10818. listen_thread.join();
  10819. ASSERT_FALSE(svr.is_running());
  10820. });
  10821. svr.set_mount_point("/", "./www");
  10822. svr.wait_until_ready();
  10823. Client cli("localhost", PORT);
  10824. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10826. EXPECT_EQ(StatusCode::OK_200, res->status);
  10827. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10828. }
  10829. // A mount point serves no path with an empty segment or one ending in '.' or
  10830. // a space, so a guard in the pre-routing handler sees the path of every file
  10831. // that is served
  10832. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10833. Server svr;
  10834. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10835. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10836. if (req.path == "/dir/test.html") {
  10837. res.status = StatusCode::Unauthorized_401;
  10838. return Server::HandlerResponse::Handled;
  10839. }
  10840. return Server::HandlerResponse::Unhandled;
  10841. });
  10842. auto port = svr.bind_to_any_port(HOST);
  10843. ASSERT_LT(0, port);
  10844. thread t = thread([&] { svr.listen_after_bind(); });
  10845. auto se = detail::scope_exit([&] {
  10846. svr.stop();
  10847. t.join();
  10848. ASSERT_FALSE(svr.is_running());
  10849. });
  10850. svr.wait_until_ready();
  10851. Client cli(HOST, port);
  10852. for (auto path :
  10853. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10854. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10855. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  10856. "/dir/test.html%3A%3A$DATA"}) {
  10857. SCOPED_TRACE(path);
  10858. auto res = cli.Get(path);
  10859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10861. }
  10862. }
  10863. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10864. Server svr;
  10865. svr.set_mount_point("/", "./www");
  10866. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10867. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10868. auto port = svr.bind_to_any_port(HOST);
  10869. ASSERT_GT(port, 0);
  10870. thread t = thread([&] { svr.listen_after_bind(); });
  10871. auto se = detail::scope_exit([&] {
  10872. svr.stop();
  10873. t.join();
  10874. ASSERT_FALSE(svr.is_running());
  10875. });
  10876. svr.wait_until_ready();
  10877. Client cli(HOST, port);
  10878. auto res = cli.Get("/dir/test.abcde");
  10879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10880. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10881. res = cli.Get("/dir/test.html");
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10884. }
  10885. #ifdef _WIN32
  10886. // Issue #2435: mmap::open() must succeed even when another handle holds
  10887. // the file open for writing (e.g. an active log file).
  10888. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10889. const char *path = "mmap_concurrent_writer_test.txt";
  10890. const char *content = "hello";
  10891. {
  10892. std::ofstream f(path, std::ios::binary);
  10893. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10894. }
  10895. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10896. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10897. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10898. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10899. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10900. detail::mmap m(path);
  10901. ASSERT_TRUE(m.is_open());
  10902. EXPECT_EQ(strlen(content), m.size());
  10903. char buf[8];
  10904. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10905. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10906. }
  10907. #endif
  10908. #ifndef _WIN32
  10909. // A directory or a device has no size to serve.
  10910. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10911. const char *path = "./mmap_not_regular_test_dir";
  10912. ASSERT_EQ(0, ::mkdir(path, 0755));
  10913. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10914. for (auto p : {path, "/dev/null"}) {
  10915. detail::mmap m(p);
  10916. EXPECT_FALSE(m.is_open()) << p;
  10917. EXPECT_EQ(0U, m.size()) << p;
  10918. }
  10919. Server svr;
  10920. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10921. res.set_file_content("/dev/null");
  10922. });
  10923. auto port = svr.bind_to_any_port(HOST);
  10924. thread t = thread([&] { svr.listen_after_bind(); });
  10925. auto se = detail::scope_exit([&] {
  10926. svr.stop();
  10927. t.join();
  10928. });
  10929. svr.wait_until_ready();
  10930. auto res = Client(HOST, port).Get("/null");
  10931. ASSERT_TRUE(res);
  10932. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10933. }
  10934. #endif
  10935. #ifdef __linux__
  10936. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10937. TEST(MmapTest, FileIsNotMapped) {
  10938. const char *path = "mmap_not_mapped_test.txt";
  10939. {
  10940. std::ofstream f(path, std::ios::binary);
  10941. f << "hello";
  10942. }
  10943. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10944. detail::mmap m(path);
  10945. ASSERT_TRUE(m.is_open());
  10946. std::ifstream maps("/proc/self/maps");
  10947. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10948. std::istreambuf_iterator<char>());
  10949. EXPECT_EQ(std::string::npos, mappings.find(path));
  10950. }
  10951. #endif
  10952. TEST(KeepAliveTest, ReadTimeout) {
  10953. Server svr;
  10954. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10955. std::this_thread::sleep_for(std::chrono::seconds(2));
  10956. res.set_content("a", "text/plain");
  10957. });
  10958. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10959. res.set_content("b", "text/plain");
  10960. });
  10961. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10962. auto se = detail::scope_exit([&] {
  10963. svr.stop();
  10964. listen_thread.join();
  10965. ASSERT_FALSE(svr.is_running());
  10966. });
  10967. svr.wait_until_ready();
  10968. Client cli("localhost", PORT);
  10969. cli.set_keep_alive(true);
  10970. cli.set_read_timeout(std::chrono::seconds(1));
  10971. auto resa = cli.Get("/a");
  10972. ASSERT_FALSE(resa);
  10973. EXPECT_EQ(Error::Read, resa.error());
  10974. auto resb = cli.Get("/b");
  10975. ASSERT_TRUE(resb);
  10976. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10977. EXPECT_EQ("b", resb->body);
  10978. }
  10979. TEST(KeepAliveTest, MaxCount) {
  10980. size_t keep_alive_max_count = 3;
  10981. Server svr;
  10982. svr.set_keep_alive_max_count(keep_alive_max_count);
  10983. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10984. res.set_content("Hello World!", "text/plain");
  10985. });
  10986. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10987. auto se = detail::scope_exit([&] {
  10988. svr.stop();
  10989. listen_thread.join();
  10990. ASSERT_FALSE(svr.is_running());
  10991. });
  10992. svr.wait_until_ready();
  10993. Client cli(HOST, PORT);
  10994. cli.set_keep_alive(true);
  10995. for (size_t i = 0; i < 5; i++) {
  10996. auto result = cli.Get("/hi");
  10997. ASSERT_TRUE(result);
  10998. EXPECT_EQ(StatusCode::OK_200, result->status);
  10999. if (i == keep_alive_max_count - 1) {
  11000. EXPECT_EQ("close", result->get_header_value("Connection"));
  11001. } else {
  11002. EXPECT_FALSE(result->has_header("Connection"));
  11003. }
  11004. }
  11005. }
  11006. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11007. // can pull the next one into the server's buffer. The server must serve it
  11008. // without waiting for the socket to become readable again. The keep-alive
  11009. // timeout outlasts the client's read timeout, so a request left waiting for it
  11010. // shows up as a missing response.
  11011. static void serve_pipelining_routes(Server &svr,
  11012. const std::function<void(int)> &client) {
  11013. svr.set_keep_alive_timeout(5);
  11014. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11015. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11016. });
  11017. svr.Post("/echo", [](const Request &req, Response &res) {
  11018. res.set_content("echo " + req.body, "text/plain");
  11019. });
  11020. auto port = svr.bind_to_any_port(HOST);
  11021. thread t = thread([&] { svr.listen_after_bind(); });
  11022. auto se = detail::scope_exit([&] {
  11023. svr.stop();
  11024. t.join();
  11025. });
  11026. svr.wait_until_ready();
  11027. client(port);
  11028. }
  11029. static std::string
  11030. send_pipelined_requests(const std::vector<std::string> &parts) {
  11031. Server svr;
  11032. std::string res;
  11033. serve_pipelining_routes(svr, [&](int port) {
  11034. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11035. });
  11036. return res;
  11037. }
  11038. static void expect_in_order(const std::string &res,
  11039. const std::vector<std::string> &bodies) {
  11040. size_t pos = 0;
  11041. for (const auto &body : bodies) {
  11042. pos = res.find(body, pos);
  11043. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11044. pos += body.size();
  11045. }
  11046. }
  11047. TEST(KeepAliveTest, PipelinedRequests) {
  11048. auto res = send_pipelined_requests(
  11049. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11050. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11051. "Content-Length: 4\r\n\r\nbody"
  11052. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11053. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11054. }
  11055. // The second request starts in the server's buffer and ends on the socket.
  11056. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11057. auto res =
  11058. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11059. "GET /hi/2 HTTP/1.1\r\nHo",
  11060. "st: localhost\r\nConnection: close\r\n\r\n"});
  11061. expect_in_order(res, {"hi 1", "hi 2"});
  11062. }
  11063. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11064. // CRLF after a body does not turn into a 400 for the next request.
  11065. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11066. auto res = send_pipelined_requests(
  11067. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11068. "Content-Length: 4\r\n\r\nbody\r\n"
  11069. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11070. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11071. expect_in_order(res, {"echo body", "hi 2"});
  11072. }
  11073. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11074. // must not be served as the next request.
  11075. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11076. auto res = send_pipelined_requests(
  11077. {"INVALID REQUEST LINE\r\n\r\n"
  11078. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11079. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11080. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11081. }
  11082. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11083. // Over TLS, the next request is held by the TLS library as already decrypted
  11084. // data rather than on the socket.
  11085. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11087. std::string res;
  11088. serve_pipelining_routes(svr, [&](int port) {
  11089. // One part, so all three requests arrive in one TLS record
  11090. EXPECT_TRUE(send_ssl_request_in_parts(
  11091. 2,
  11092. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11093. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11094. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11095. &res, port));
  11096. });
  11097. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11098. }
  11099. #endif
  11100. TEST(KeepAliveTest, Issue1041) {
  11101. Server svr;
  11102. svr.set_keep_alive_timeout(3);
  11103. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11104. res.set_content("Hello World!", "text/plain");
  11105. });
  11106. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11107. auto se = detail::scope_exit([&] {
  11108. svr.stop();
  11109. listen_thread.join();
  11110. ASSERT_FALSE(svr.is_running());
  11111. });
  11112. svr.wait_until_ready();
  11113. Client cli(HOST, PORT);
  11114. cli.set_keep_alive(true);
  11115. auto result = cli.Get("/hi");
  11116. ASSERT_TRUE(result);
  11117. EXPECT_EQ(StatusCode::OK_200, result->status);
  11118. std::this_thread::sleep_for(std::chrono::seconds(5));
  11119. result = cli.Get("/hi");
  11120. ASSERT_TRUE(result);
  11121. EXPECT_EQ(StatusCode::OK_200, result->status);
  11122. }
  11123. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11124. Server svr;
  11125. svr.set_keep_alive_max_count(0);
  11126. std::set<int> remote_ports;
  11127. svr.Get("/hi", [&](const Request &req, Response &res) {
  11128. remote_ports.insert(req.remote_port);
  11129. res.set_content("hi", "text/plain");
  11130. });
  11131. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11132. auto se = detail::scope_exit([&] {
  11133. svr.stop();
  11134. listen_thread.join();
  11135. ASSERT_FALSE(svr.is_running());
  11136. });
  11137. svr.wait_until_ready();
  11138. Client cli(HOST, PORT);
  11139. cli.set_keep_alive(true);
  11140. for (int i = 0; i < 3; i++) {
  11141. auto res = cli.Get("/hi");
  11142. ASSERT_TRUE(res);
  11143. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11144. }
  11145. // All three over one connection
  11146. EXPECT_EQ(1u, remote_ports.size());
  11147. }
  11148. TEST(KeepAliveTest, Issue1959) {
  11149. Server svr;
  11150. svr.set_keep_alive_timeout(5);
  11151. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11152. res.set_content("a", "text/plain");
  11153. });
  11154. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11155. auto se = detail::scope_exit([&] {
  11156. if (!svr.is_running()) return;
  11157. svr.stop();
  11158. listen_thread.join();
  11159. ASSERT_FALSE(svr.is_running());
  11160. });
  11161. svr.wait_until_ready();
  11162. Client cli("localhost", PORT);
  11163. cli.set_keep_alive(true);
  11164. using namespace std::chrono;
  11165. auto start = steady_clock::now();
  11166. cli.Get("/a");
  11167. svr.stop();
  11168. listen_thread.join();
  11169. auto end = steady_clock::now();
  11170. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11171. EXPECT_LT(elapsed, 5000);
  11172. }
  11173. #ifdef CPPHTTPLIB_SSL_ENABLED
  11174. TEST(KeepAliveTest, SSLClientReconnection) {
  11175. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11176. ASSERT_TRUE(svr.is_valid());
  11177. svr.set_keep_alive_timeout(1);
  11178. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11179. res.set_content("Hello World!", "text/plain");
  11180. });
  11181. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11182. auto se = detail::scope_exit([&] {
  11183. svr.stop();
  11184. listen_thread.join();
  11185. ASSERT_FALSE(svr.is_running());
  11186. });
  11187. svr.wait_until_ready();
  11188. SSLClient cli(HOST, PORT);
  11189. cli.enable_server_certificate_verification(false);
  11190. cli.set_keep_alive(true);
  11191. auto result = cli.Get("/hi");
  11192. ASSERT_TRUE(result);
  11193. EXPECT_EQ(StatusCode::OK_200, result->status);
  11194. result = cli.Get("/hi");
  11195. ASSERT_TRUE(result);
  11196. EXPECT_EQ(StatusCode::OK_200, result->status);
  11197. std::this_thread::sleep_for(std::chrono::seconds(2));
  11198. // Recoonect
  11199. result = cli.Get("/hi");
  11200. ASSERT_TRUE(result);
  11201. EXPECT_EQ(StatusCode::OK_200, result->status);
  11202. result = cli.Get("/hi");
  11203. ASSERT_TRUE(result);
  11204. EXPECT_EQ(StatusCode::OK_200, result->status);
  11205. }
  11206. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11207. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11208. ASSERT_TRUE(svr.is_valid());
  11209. svr.set_keep_alive_timeout(1);
  11210. std::string content = "reconnect";
  11211. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11212. res.set_content("Hello World!", "text/plain");
  11213. });
  11214. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11215. auto se = detail::scope_exit([&] {
  11216. svr.stop();
  11217. listen_thread.join();
  11218. ASSERT_FALSE(svr.is_running());
  11219. });
  11220. svr.wait_until_ready();
  11221. SSLClient cli(HOST, PORT);
  11222. cli.enable_server_certificate_verification(false);
  11223. cli.set_keep_alive(true);
  11224. auto 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. std::this_thread::sleep_for(std::chrono::seconds(2));
  11234. // Recoonect
  11235. result = cli.Post(
  11236. "/hi", content.size(),
  11237. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11238. sink.write(content.c_str(), content.size());
  11239. return true;
  11240. },
  11241. "text/plain");
  11242. ASSERT_TRUE(result);
  11243. EXPECT_EQ(200, result->status);
  11244. result = cli.Post(
  11245. "/hi", content.size(),
  11246. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11247. sink.write(content.c_str(), content.size());
  11248. return true;
  11249. },
  11250. "text/plain");
  11251. ASSERT_TRUE(result);
  11252. EXPECT_EQ(200, result->status);
  11253. }
  11254. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11255. using namespace httplib::tls;
  11256. {
  11257. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11258. ASSERT_TRUE(svr.is_valid());
  11259. svr.Get("/sni", [&](const Request &req, Response &res) {
  11260. std::string expected = req.sni();
  11261. EXPECT_EQ(expected, req.get_param_value("expected"));
  11262. res.set_content("ok", "text/plain");
  11263. });
  11264. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11265. auto se = detail::scope_exit([&] {
  11266. svr.stop();
  11267. listen_thread.join();
  11268. ASSERT_FALSE(svr.is_running());
  11269. });
  11270. svr.wait_until_ready();
  11271. {
  11272. SSLClient cli("localhost", PORT);
  11273. cli.enable_server_certificate_verification(false);
  11274. auto res = cli.Get("/sni?expected=localhost");
  11275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11276. }
  11277. {
  11278. SSLClient cli("::1", PORT);
  11279. cli.enable_server_certificate_verification(false);
  11280. auto res = cli.Get("/sni?expected=");
  11281. // NOTE: This may fail if the server is listening on IPv4 only
  11282. // (e.g., when localhost resolves to 127.0.0.1 only)
  11283. if (res) {
  11284. EXPECT_EQ(StatusCode::OK_200, res->status);
  11285. } else {
  11286. EXPECT_EQ(Error::Connection, res.error());
  11287. }
  11288. }
  11289. }
  11290. }
  11291. // The SNI of a failed handshake does not reach the next connection that the
  11292. // same worker thread serves
  11293. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11295. ASSERT_TRUE(svr.is_valid());
  11296. svr.new_task_queue = [] { return new ThreadPool(1); };
  11297. svr.Get("/sni", [](const Request &req, Response &res) {
  11298. res.set_content(req.sni(), "text/plain");
  11299. });
  11300. auto port = svr.bind_to_any_port("127.0.0.1");
  11301. ASSERT_LT(0, port);
  11302. thread t = thread([&] { svr.listen_after_bind(); });
  11303. auto se = detail::scope_exit([&] {
  11304. svr.stop();
  11305. t.join();
  11306. ASSERT_FALSE(svr.is_running());
  11307. });
  11308. svr.wait_until_ready();
  11309. {
  11310. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11311. SSLClient cli("localhost", port);
  11312. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11313. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11314. auto res = cli.Get("/sni");
  11315. ASSERT_FALSE(res);
  11316. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11317. }
  11318. // An IP host sends no SNI (RFC 6066)
  11319. SSLClient cli("127.0.0.1", port);
  11320. cli.enable_server_certificate_verification(false);
  11321. auto res = cli.Get("/sni");
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. EXPECT_EQ("", res->body);
  11324. }
  11325. #endif
  11326. TEST(ClientProblemDetectionTest, ContentProvider) {
  11327. Server svr;
  11328. size_t content_length = 1024 * 1024;
  11329. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11330. res.set_content_provider(
  11331. content_length, "text/plain",
  11332. [&](size_t offset, size_t length, DataSink &sink) {
  11333. auto out_len = std::min(length, static_cast<size_t>(1024));
  11334. std::string out(out_len, '@');
  11335. sink.write(out.data(), out_len);
  11336. return offset < 4096;
  11337. },
  11338. [](bool success) { ASSERT_FALSE(success); });
  11339. });
  11340. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11341. res.set_content_provider(
  11342. 0, "text/plain",
  11343. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11344. EXPECT_TRUE(false);
  11345. return true;
  11346. },
  11347. [](bool success) { ASSERT_FALSE(success); });
  11348. });
  11349. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11350. auto se = detail::scope_exit([&] {
  11351. svr.stop();
  11352. listen_thread.join();
  11353. ASSERT_FALSE(svr.is_running());
  11354. });
  11355. svr.wait_until_ready();
  11356. Client cli("localhost", PORT);
  11357. {
  11358. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11359. size_t /*data_length*/) { return false; });
  11360. ASSERT_FALSE(res);
  11361. }
  11362. {
  11363. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11364. size_t /*data_length*/) { return false; });
  11365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11366. }
  11367. }
  11368. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11369. // A provider that reports success without writing anything and without
  11370. // calling done() used to be handed the same offset and length again on every
  11371. // pass, so it spun for as long as the peer stayed connected.
  11372. Server svr;
  11373. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11374. res.set_content("ok", "text/plain");
  11375. });
  11376. auto port = svr.bind_to_any_port(HOST);
  11377. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11378. auto se = detail::scope_exit([&] {
  11379. svr.stop();
  11380. listen_thread.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. std::atomic<int> call_count{0};
  11385. Client cli(HOST, port);
  11386. auto res = cli.Post(
  11387. "/", 1024,
  11388. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11389. // Give up after enough passes to show the spin, so that losing the
  11390. // check below fails this test instead of hanging it.
  11391. return ++call_count < 100;
  11392. },
  11393. "text/plain");
  11394. ASSERT_FALSE(res);
  11395. EXPECT_EQ(Error::Write, res.error());
  11396. EXPECT_EQ(1, call_count.load());
  11397. }
  11398. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11399. // A writer only has to assign `write`. The other three used to be left as
  11400. // empty std::functions, so a provider calling one threw
  11401. // std::bad_function_call out of the thread running it and took the whole
  11402. // process down.
  11403. DataSink sink;
  11404. std::string written;
  11405. sink.write = [&](const char *data, size_t data_len) {
  11406. written.append(data, data_len);
  11407. return true;
  11408. };
  11409. EXPECT_TRUE(sink.is_writable());
  11410. sink.done();
  11411. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11412. EXPECT_TRUE(written.empty());
  11413. }
  11414. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11415. // A sink that cannot carry trailers still has to finish.
  11416. DataSink sink;
  11417. auto done_count = 0;
  11418. sink.done = [&]() { done_count++; };
  11419. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11420. EXPECT_EQ(1, done_count);
  11421. }
  11422. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11423. Server svr;
  11424. const std::string body(4096, 'x');
  11425. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11426. res.set_content_provider(body.size(), "text/plain",
  11427. [&](size_t offset, size_t length, DataSink &sink) {
  11428. sink.write(body.data() + offset, length);
  11429. sink.done();
  11430. return true;
  11431. });
  11432. });
  11433. auto port = svr.bind_to_any_port(HOST);
  11434. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11435. auto se = detail::scope_exit([&] {
  11436. svr.stop();
  11437. listen_thread.join();
  11438. ASSERT_FALSE(svr.is_running());
  11439. });
  11440. svr.wait_until_ready();
  11441. Client cli(HOST, port);
  11442. auto res = cli.Get("/");
  11443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11444. EXPECT_EQ(StatusCode::OK_200, res->status);
  11445. EXPECT_EQ(body, res->body);
  11446. }
  11447. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11448. Server svr;
  11449. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11450. res.set_content_provider(
  11451. 1024, "text/plain",
  11452. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11453. sink.write("hello", 5);
  11454. sink.done(); // short of the 1024 bytes the response promised
  11455. return true;
  11456. });
  11457. });
  11458. auto port = svr.bind_to_any_port(HOST);
  11459. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11460. auto se = detail::scope_exit([&] {
  11461. svr.stop();
  11462. listen_thread.join();
  11463. ASSERT_FALSE(svr.is_running());
  11464. });
  11465. svr.wait_until_ready();
  11466. Client cli(HOST, port);
  11467. cli.set_read_timeout(5, 0);
  11468. // The response is short of its Content-Length, so the client cannot read a
  11469. // complete body. What matters is that this returns at all: a no-op done()
  11470. // would leave the writer looping over a provider that never makes progress.
  11471. auto res = cli.Get("/");
  11472. EXPECT_FALSE(res);
  11473. }
  11474. // Read as the next response by a peer that sees it after a framed body.
  11475. static const std::string smuggled_response =
  11476. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11477. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11478. Server svr;
  11479. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11480. res.set_content_provider(
  11481. 5, "text/plain",
  11482. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11483. auto data = "AAAAA" + smuggled_response;
  11484. sink.write(data.data(), data.size());
  11485. return true;
  11486. });
  11487. });
  11488. thread t = thread([&] { svr.listen(HOST, PORT); });
  11489. auto se = detail::scope_exit([&] {
  11490. svr.stop();
  11491. t.join();
  11492. ASSERT_FALSE(svr.is_running());
  11493. });
  11494. svr.wait_until_ready();
  11495. std::string resp;
  11496. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11497. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11498. resp.clear();
  11499. ASSERT_TRUE(send_request(
  11500. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11501. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11502. }
  11503. TEST(NoContentTest, BodyIsNotSent) {
  11504. Server svr;
  11505. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11506. res.status = StatusCode::NoContent_204;
  11507. res.set_content(smuggled_response, "text/plain");
  11508. });
  11509. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11510. res.status = StatusCode::NotModified_304;
  11511. res.set_chunked_content_provider(
  11512. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11513. sink.write(smuggled_response.data(), smuggled_response.size());
  11514. sink.done();
  11515. return true;
  11516. });
  11517. });
  11518. thread t = thread([&] { svr.listen(HOST, PORT); });
  11519. auto se = detail::scope_exit([&] {
  11520. svr.stop();
  11521. t.join();
  11522. ASSERT_FALSE(svr.is_running());
  11523. });
  11524. svr.wait_until_ready();
  11525. for (auto path : {"/204", "/304"}) {
  11526. std::string resp;
  11527. ASSERT_TRUE(send_request(
  11528. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11529. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11530. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11531. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11532. }
  11533. }
  11534. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11535. Server svr;
  11536. std::atomic<bool> smuggled(false);
  11537. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11538. res.set_content("ok", "text/plain");
  11539. });
  11540. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11541. smuggled = true;
  11542. });
  11543. auto port = svr.bind_to_any_port(HOST);
  11544. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11545. auto se = detail::scope_exit([&] {
  11546. svr.stop();
  11547. listen_thread.join();
  11548. ASSERT_FALSE(svr.is_running());
  11549. });
  11550. svr.wait_until_ready();
  11551. // What follows the body would be read as the next request.
  11552. Client cli(HOST, port);
  11553. auto res = cli.Post(
  11554. "/", 5,
  11555. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11556. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11557. sink.write(data.data(), data.size());
  11558. return true;
  11559. },
  11560. "text/plain");
  11561. ASSERT_FALSE(res);
  11562. EXPECT_EQ(Error::Write, res.error());
  11563. EXPECT_FALSE(smuggled);
  11564. }
  11565. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11566. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11567. // The compressed path builds the whole body before connecting, so this
  11568. // fails client-side and never reaches a server.
  11569. Client cli(HOST, PORT);
  11570. cli.set_compress(true);
  11571. auto res = cli.Post(
  11572. "/", 1024,
  11573. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11574. sink.write("hello", 5);
  11575. sink.done(); // short of the 1024 bytes the request announced
  11576. return true;
  11577. },
  11578. "text/plain");
  11579. ASSERT_FALSE(res);
  11580. EXPECT_EQ(Error::Write, res.error());
  11581. }
  11582. #endif
  11583. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11584. Server svr;
  11585. svr.set_error_handler([](Request const &, Response &res) -> void {
  11586. res.set_chunked_content_provider(
  11587. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11588. sink.os << "hello";
  11589. sink.os << "world";
  11590. sink.done();
  11591. return true;
  11592. });
  11593. });
  11594. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11595. auto se = detail::scope_exit([&] {
  11596. svr.stop();
  11597. listen_thread.join();
  11598. ASSERT_FALSE(svr.is_running());
  11599. });
  11600. svr.wait_until_ready();
  11601. Client cli("localhost", PORT);
  11602. auto res = cli.Get("/");
  11603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11604. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11605. EXPECT_EQ("helloworld", res->body);
  11606. }
  11607. // A body set after a content provider must replace it, not be sent through it.
  11608. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11609. Server svr;
  11610. svr.set_mount_point("/", "./www");
  11611. svr.set_file_request_handler([](const Request &req, Response &res) {
  11612. if (req.path == "/dir/test.html") {
  11613. res.status = StatusCode::Forbidden_403;
  11614. res.set_content(std::string(5000, 'D'), "text/plain");
  11615. } else if (req.path == "/file") {
  11616. res.status = StatusCode::Forbidden_403;
  11617. res.body = "Denied";
  11618. }
  11619. });
  11620. auto port = svr.bind_to_any_port(HOST);
  11621. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11622. auto se = detail::scope_exit([&] {
  11623. svr.stop();
  11624. t.join();
  11625. ASSERT_FALSE(svr.is_running());
  11626. });
  11627. svr.wait_until_ready();
  11628. Client cli(HOST, port);
  11629. {
  11630. auto res = cli.Get("/dir/test.html");
  11631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11632. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11633. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11634. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11635. }
  11636. {
  11637. auto res = cli.Get("/file");
  11638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11639. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11640. EXPECT_EQ("Denied", res->body);
  11641. }
  11642. {
  11643. auto res = cli.Get("/dir/index.html");
  11644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11645. EXPECT_EQ(StatusCode::OK_200, res->status);
  11646. EXPECT_EQ(0U, res->body.find("<html>"));
  11647. }
  11648. }
  11649. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11650. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11651. Server svr;
  11652. std::vector<bool> released;
  11653. std::mutex released_mutex;
  11654. auto releaser = [&](bool success) {
  11655. std::lock_guard<std::mutex> guard(released_mutex);
  11656. released.push_back(success);
  11657. };
  11658. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11659. return sink.write(&"hello"[offset], length);
  11660. };
  11661. svr.Get("/sized", [&](const Request &, Response &res) {
  11662. res.status = StatusCode::NotFound_404;
  11663. res.set_content_provider(5, "text/plain", provider, releaser);
  11664. });
  11665. svr.Get("/chunked", [&](const Request &, Response &res) {
  11666. res.status = StatusCode::ServiceUnavailable_503;
  11667. res.set_chunked_content_provider(
  11668. "text/plain",
  11669. [](size_t, DataSink &sink) {
  11670. sink.os << "chunk";
  11671. sink.done();
  11672. return true;
  11673. },
  11674. releaser);
  11675. });
  11676. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11677. res.set_content_provider(5, "text/plain", provider, releaser);
  11678. throw std::runtime_error("after the provider");
  11679. });
  11680. svr.set_error_handler([](const Request &req, Response &res) {
  11681. // Leave the exception handler's content to it.
  11682. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11683. res.set_content(std::string(1000, 'E'), "text/html");
  11684. return Server::HandlerResponse::Handled;
  11685. });
  11686. svr.set_exception_handler(
  11687. [](const Request &, Response &res, std::exception_ptr) {
  11688. res.status = StatusCode::InternalServerError_500;
  11689. res.set_content(std::string(1000, 'X'), "text/html");
  11690. });
  11691. auto port = svr.bind_to_any_port(HOST);
  11692. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11693. auto se = detail::scope_exit([&] {
  11694. svr.stop();
  11695. t.join();
  11696. ASSERT_FALSE(svr.is_running());
  11697. });
  11698. svr.wait_until_ready();
  11699. Client cli(HOST, port);
  11700. {
  11701. auto res = cli.Get("/sized");
  11702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11703. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11704. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11705. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11706. }
  11707. {
  11708. auto res = cli.Get("/chunked");
  11709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11710. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11711. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11712. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11713. }
  11714. {
  11715. auto res = cli.Get("/throw");
  11716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11717. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11718. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11719. }
  11720. std::lock_guard<std::mutex> guard(released_mutex);
  11721. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11722. }
  11723. #endif
  11724. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11725. Server svr;
  11726. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11727. return sink.write(&"abc"[offset], length);
  11728. };
  11729. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11730. res.set_file_content("./www/dir/test.html");
  11731. res.set_content("body", "text/plain");
  11732. });
  11733. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11734. res.set_content(std::string(100, 'B'), "text/plain");
  11735. res.set_file_content("./www/dir/test.html");
  11736. });
  11737. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11738. res.set_content(std::string(100, 'B'), "text/plain");
  11739. res.set_content_provider(3, "text/x-provider", abc);
  11740. });
  11741. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11742. res.set_content_provider(3, "text/x-provider", abc);
  11743. res.set_content(std::string(100, 'B'), "text/plain");
  11744. });
  11745. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11746. res.set_content_provider(3, "text/x-provider", abc);
  11747. res.set_file_content("./www/dir/test.html", "text/x-file");
  11748. });
  11749. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11750. res.set_file_content("./www/dir/test.html");
  11751. res.set_header("Content-Type", "text/x-handler");
  11752. });
  11753. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11754. res.set_content_provider(3, "text/plain", abc);
  11755. res.body = "direct";
  11756. });
  11757. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11758. res.set_file_content("./www/dir/test.html");
  11759. res.body = "direct";
  11760. });
  11761. auto port = svr.bind_to_any_port(HOST);
  11762. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11763. auto se = detail::scope_exit([&] {
  11764. svr.stop();
  11765. t.join();
  11766. ASSERT_FALSE(svr.is_running());
  11767. });
  11768. svr.wait_until_ready();
  11769. Client cli(HOST, port);
  11770. auto expect_body = [&](const char *path, const std::string &body,
  11771. const std::string &type) {
  11772. // Uncompressed, so Content-Length can be compared with the body.
  11773. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11774. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11775. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11776. EXPECT_EQ(body, res->body) << path;
  11777. EXPECT_EQ(std::to_string(body.size()),
  11778. res->get_header_value("Content-Length"))
  11779. << path;
  11780. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11781. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11782. };
  11783. expect_body("/file-then-body", "body", "text/plain");
  11784. expect_body("/body-then-file", "test.html", "text/html");
  11785. expect_body("/body-then-provider", "abc", "text/x-provider");
  11786. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11787. expect_body("/provider-then-file", "test.html", "text/x-file");
  11788. expect_body("/file-then-header", "test.html", "text/x-handler");
  11789. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11790. expect_body("/file-then-direct-body", "direct", "text/plain");
  11791. // Ranges are checked against the body, not the dropped provider.
  11792. {
  11793. auto res = cli.Get("/provider-then-direct-body",
  11794. Headers{{make_range_header({{1, 2}})}});
  11795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11797. EXPECT_EQ("ir", res->body);
  11798. }
  11799. {
  11800. auto res = cli.Get("/file-then-direct-body",
  11801. Headers{{make_range_header({{7, 8}})}});
  11802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11803. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11804. }
  11805. }
  11806. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11807. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11808. const char *path = "./truncated_while_served.txt";
  11809. const size_t size = 32 * 1024 * 1024;
  11810. {
  11811. std::ofstream f(path, std::ios::binary);
  11812. f << std::string(size, 'x');
  11813. }
  11814. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11815. // Over TLS, where the bytes are encrypted in this process rather than
  11816. // copied by send().
  11817. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11818. svr.Get("/file", [&](const Request &, Response &res) {
  11819. res.set_file_content(path, "text/plain");
  11820. });
  11821. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11822. auto se = detail::scope_exit([&] {
  11823. svr.stop();
  11824. thread.join();
  11825. ASSERT_FALSE(svr.is_running());
  11826. });
  11827. svr.wait_until_ready();
  11828. // The file shrinks once the first bytes are in, as a rewrite in place
  11829. // would, and reading the mapping past its new end used to raise SIGBUS.
  11830. SSLClient cli(HOST, PORT);
  11831. cli.enable_server_certificate_verification(false);
  11832. size_t received = 0;
  11833. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11834. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11835. received += len;
  11836. return true;
  11837. });
  11838. EXPECT_FALSE(res);
  11839. EXPECT_LT(received, size);
  11840. }
  11841. #endif
  11842. // Forward declaration (see the base64_encode note).
  11843. namespace httplib {
  11844. namespace detail {
  11845. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11846. const std::string &content_type,
  11847. EncodingType encoding);
  11848. } // namespace detail
  11849. } // namespace httplib
  11850. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11851. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11852. ASSERT_TRUE(mm->is_open());
  11853. Response res;
  11854. detail::set_file_content_provider(res, mm, "text/html",
  11855. detail::EncodingType::None);
  11856. std::string out;
  11857. DataSink sink;
  11858. sink.write = [&](const char *d, size_t l) {
  11859. out.append(d, l);
  11860. return true;
  11861. };
  11862. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11863. EXPECT_EQ("test.html", out);
  11864. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11865. EXPECT_EQ("test.html", out);
  11866. }
  11867. TEST(LongPollingTest, ClientCloseDetection) {
  11868. Server svr;
  11869. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11870. res.set_chunked_content_provider(
  11871. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11872. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11873. sink.os << "hello";
  11874. auto count = 10;
  11875. while (count > 0 && sink.is_writable()) {
  11876. this_thread::sleep_for(chrono::milliseconds(10));
  11877. count--;
  11878. }
  11879. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11880. return true;
  11881. });
  11882. });
  11883. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11884. auto se = detail::scope_exit([&] {
  11885. svr.stop();
  11886. listen_thread.join();
  11887. ASSERT_FALSE(svr.is_running());
  11888. });
  11889. svr.wait_until_ready();
  11890. Client cli("localhost", PORT);
  11891. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11892. EXPECT_EQ("hello", string(data, data_length));
  11893. return false; // close the socket immediately.
  11894. });
  11895. ASSERT_FALSE(res);
  11896. }
  11897. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11898. Server svr;
  11899. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11900. res.set_chunked_content_provider(
  11901. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11902. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11903. sink.os << "hello";
  11904. EXPECT_TRUE(sink.os.good());
  11905. // Wait for the client to close the connection
  11906. auto count = 10;
  11907. while (count > 0 && sink.is_writable()) {
  11908. this_thread::sleep_for(chrono::milliseconds(10));
  11909. count--;
  11910. }
  11911. // After client disconnect, write repeatedly until the socket
  11912. // write actually fails (small writes may be absorbed by the
  11913. // kernel buffer)
  11914. std::string chunk(1024, 'x');
  11915. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11916. sink.os << chunk;
  11917. }
  11918. EXPECT_TRUE(sink.os.fail());
  11919. return true;
  11920. });
  11921. });
  11922. auto port = svr.bind_to_any_port("localhost");
  11923. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11924. auto se = detail::scope_exit([&] {
  11925. svr.stop();
  11926. listen_thread.join();
  11927. ASSERT_FALSE(svr.is_running());
  11928. });
  11929. svr.wait_until_ready();
  11930. Client cli("localhost", port);
  11931. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11932. EXPECT_EQ("hello", string(data, data_length));
  11933. return false; // close the socket immediately.
  11934. });
  11935. ASSERT_FALSE(res);
  11936. }
  11937. TEST(GetWithParametersTest, GetWithParameters) {
  11938. Server svr;
  11939. svr.Get("/", [&](const Request &req, Response &) {
  11940. EXPECT_EQ("world", req.get_param_value("hello"));
  11941. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11942. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11943. });
  11944. svr.Get("/params", [&](const Request &req, Response &) {
  11945. EXPECT_EQ("world", req.get_param_value("hello"));
  11946. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11947. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11948. });
  11949. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11950. EXPECT_EQ("resource-id", req.matches[1]);
  11951. EXPECT_EQ("foo", req.get_param_value("param1"));
  11952. EXPECT_EQ("bar", req.get_param_value("param2"));
  11953. });
  11954. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11955. EXPECT_EQ("user-id", req.path_params.at("id"));
  11956. EXPECT_EQ("foo", req.get_param_value("param1"));
  11957. EXPECT_EQ("bar", req.get_param_value("param2"));
  11958. });
  11959. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11960. auto se = detail::scope_exit([&] {
  11961. svr.stop();
  11962. listen_thread.join();
  11963. ASSERT_FALSE(svr.is_running());
  11964. });
  11965. svr.wait_until_ready();
  11966. {
  11967. Client cli(HOST, PORT);
  11968. Params params;
  11969. params.emplace("hello", "world");
  11970. params.emplace("hello2", "world2");
  11971. params.emplace("hello3", "world3");
  11972. auto res = cli.Get("/", params, Headers{});
  11973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11974. EXPECT_EQ(StatusCode::OK_200, res->status);
  11975. }
  11976. {
  11977. Client cli(HOST, PORT);
  11978. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11980. EXPECT_EQ(StatusCode::OK_200, res->status);
  11981. }
  11982. {
  11983. Client cli(HOST, PORT);
  11984. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11986. EXPECT_EQ(StatusCode::OK_200, res->status);
  11987. }
  11988. {
  11989. Client cli(HOST, PORT);
  11990. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11992. EXPECT_EQ(StatusCode::OK_200, res->status);
  11993. }
  11994. }
  11995. TEST(GetWithParametersTest, GetWithParameters2) {
  11996. Server svr;
  11997. svr.Get("/", [&](const Request &req, Response &res) {
  11998. auto text = req.get_param_value("hello");
  11999. res.set_content(text, "text/plain");
  12000. });
  12001. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12002. auto se = detail::scope_exit([&] {
  12003. svr.stop();
  12004. listen_thread.join();
  12005. ASSERT_FALSE(svr.is_running());
  12006. });
  12007. svr.wait_until_ready();
  12008. Client cli("localhost", PORT);
  12009. Params params;
  12010. params.emplace("hello", "world");
  12011. std::string body;
  12012. auto res = cli.Get("/", params, Headers{},
  12013. [&](const char *data, size_t data_length) {
  12014. body.append(data, data_length);
  12015. return true;
  12016. });
  12017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12018. EXPECT_EQ(StatusCode::OK_200, res->status);
  12019. EXPECT_EQ("world", body);
  12020. }
  12021. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12022. Server svr;
  12023. svr.Get("/search", [&](const Request &req, Response &res) {
  12024. auto q = req.get_param_value("q");
  12025. res.set_content(q, "text/plain");
  12026. });
  12027. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12028. auto se = detail::scope_exit([&] {
  12029. svr.stop();
  12030. listen_thread.join();
  12031. ASSERT_FALSE(svr.is_running());
  12032. });
  12033. svr.wait_until_ready();
  12034. Client cli("localhost", PORT);
  12035. // Verify that Get(path, params) works without requiring Headers argument
  12036. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12038. EXPECT_EQ(StatusCode::OK_200, res->status);
  12039. EXPECT_EQ("cpp-httplib", res->body);
  12040. }
  12041. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12042. auto host = "httpbingo.org";
  12043. auto path = std::string{"/range/32"};
  12044. #ifdef CPPHTTPLIB_SSL_ENABLED
  12045. SSLClient cli(host);
  12046. #else
  12047. Client cli(host);
  12048. #endif
  12049. cli.set_default_headers({make_range_header({{1, 10}})});
  12050. cli.set_connection_timeout(5);
  12051. {
  12052. auto res = cli.Get(path);
  12053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12054. EXPECT_EQ("bcdefghijk", res->body);
  12055. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12056. }
  12057. {
  12058. auto res = cli.Get(path);
  12059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12060. EXPECT_EQ("bcdefghijk", res->body);
  12061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12062. }
  12063. }
  12064. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12065. Server svr;
  12066. svr.set_default_headers({{"Hello", "World"}});
  12067. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12068. res.set_content("ok", "text/plain");
  12069. });
  12070. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12071. auto se = detail::scope_exit([&] {
  12072. svr.stop();
  12073. listen_thread.join();
  12074. ASSERT_FALSE(svr.is_running());
  12075. });
  12076. svr.wait_until_ready();
  12077. Client cli("localhost", PORT);
  12078. auto res = cli.Get("/");
  12079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12080. EXPECT_EQ(StatusCode::OK_200, res->status);
  12081. EXPECT_EQ("ok", res->body);
  12082. EXPECT_EQ("World", res->get_header_value("Hello"));
  12083. }
  12084. #ifdef CPPHTTPLIB_SSL_ENABLED
  12085. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12087. ASSERT_TRUE(svr.is_valid());
  12088. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12089. std::this_thread::sleep_for(std::chrono::seconds(2));
  12090. res.set_content("a", "text/plain");
  12091. });
  12092. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12093. res.set_content("b", "text/plain");
  12094. });
  12095. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12096. auto se = detail::scope_exit([&] {
  12097. svr.stop();
  12098. listen_thread.join();
  12099. ASSERT_FALSE(svr.is_running());
  12100. });
  12101. svr.wait_until_ready();
  12102. SSLClient cli("localhost", PORT);
  12103. cli.enable_server_certificate_verification(false);
  12104. cli.set_keep_alive(true);
  12105. cli.set_read_timeout(std::chrono::seconds(1));
  12106. auto resa = cli.Get("/a");
  12107. ASSERT_TRUE(!resa);
  12108. EXPECT_EQ(Error::Read, resa.error());
  12109. auto resb = cli.Get("/b");
  12110. ASSERT_TRUE(resb);
  12111. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12112. EXPECT_EQ("b", resb->body);
  12113. }
  12114. // Closing an idle keep-alive connection sends close_notify and returns. The
  12115. // server must not wait for the client's close_notify: an idle client never
  12116. // sends one, so the worker would be held until the read timeout expires, and
  12117. // stop() would wait for it.
  12118. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12119. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12120. ASSERT_TRUE(svr.is_valid());
  12121. svr.set_keep_alive_timeout(1);
  12122. svr.set_read_timeout(10, 0);
  12123. svr.Get("/", [](const Request &, Response &res) {
  12124. res.set_content("ok", "text/plain");
  12125. });
  12126. auto port = svr.bind_to_any_port(HOST);
  12127. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12128. auto se = detail::scope_exit([&] {
  12129. if (listen_thread.joinable()) {
  12130. svr.stop();
  12131. listen_thread.join();
  12132. }
  12133. });
  12134. svr.wait_until_ready();
  12135. SSLClient cli(HOST, port);
  12136. cli.enable_server_certificate_verification(false);
  12137. cli.set_keep_alive(true);
  12138. auto res = cli.Get("/");
  12139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12140. EXPECT_EQ(StatusCode::OK_200, res->status);
  12141. // Stay idle past the keep-alive timeout so the server closes the connection.
  12142. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12143. auto start = std::chrono::steady_clock::now();
  12144. svr.stop();
  12145. listen_thread.join();
  12146. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12147. std::chrono::steady_clock::now() - start)
  12148. .count();
  12149. EXPECT_LT(elapsed, 3000);
  12150. }
  12151. #endif
  12152. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12153. protected:
  12154. ServerTestWithAI_PASSIVE()
  12155. : cli_(HOST, PORT)
  12156. #ifdef CPPHTTPLIB_SSL_ENABLED
  12157. ,
  12158. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12159. #endif
  12160. {
  12161. #ifdef CPPHTTPLIB_SSL_ENABLED
  12162. cli_.enable_server_certificate_verification(false);
  12163. #endif
  12164. }
  12165. virtual void SetUp() {
  12166. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12167. res.set_content("Hello World!", "text/plain");
  12168. });
  12169. t_ = thread(
  12170. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12171. svr_.wait_until_ready();
  12172. }
  12173. virtual void TearDown() {
  12174. svr_.stop();
  12175. t_.join();
  12176. }
  12177. #ifdef CPPHTTPLIB_SSL_ENABLED
  12178. SSLClient cli_;
  12179. SSLServer svr_;
  12180. #else
  12181. Client cli_;
  12182. Server svr_;
  12183. #endif
  12184. thread t_;
  12185. };
  12186. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12187. auto res = cli_.Get("/hi");
  12188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12189. EXPECT_EQ(StatusCode::OK_200, res->status);
  12190. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12191. EXPECT_EQ("Hello World!", res->body);
  12192. }
  12193. class ServerUpDownTest : public ::testing::Test {
  12194. protected:
  12195. ServerUpDownTest() : cli_(HOST, PORT) {}
  12196. virtual void SetUp() {
  12197. t_ = thread([&]() {
  12198. svr_.bind_to_any_port(HOST);
  12199. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12200. ASSERT_TRUE(svr_.listen_after_bind());
  12201. });
  12202. svr_.wait_until_ready();
  12203. }
  12204. virtual void TearDown() {
  12205. svr_.stop();
  12206. t_.join();
  12207. }
  12208. Client cli_;
  12209. Server svr_;
  12210. thread t_;
  12211. };
  12212. TEST_F(ServerUpDownTest, QuickStartStop) {
  12213. // Should not crash, especially when run with
  12214. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12215. }
  12216. class PayloadMaxLengthTest : public ::testing::Test {
  12217. protected:
  12218. PayloadMaxLengthTest()
  12219. : cli_(HOST, PORT)
  12220. #ifdef CPPHTTPLIB_SSL_ENABLED
  12221. ,
  12222. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12223. #endif
  12224. {
  12225. #ifdef CPPHTTPLIB_SSL_ENABLED
  12226. cli_.enable_server_certificate_verification(false);
  12227. #endif
  12228. }
  12229. virtual void SetUp() {
  12230. svr_.set_payload_max_length(8);
  12231. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12232. res.set_content("test", "text/plain");
  12233. });
  12234. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12235. svr_.wait_until_ready();
  12236. }
  12237. virtual void TearDown() {
  12238. svr_.stop();
  12239. t_.join();
  12240. }
  12241. #ifdef CPPHTTPLIB_SSL_ENABLED
  12242. SSLClient cli_;
  12243. SSLServer svr_;
  12244. #else
  12245. Client cli_;
  12246. Server svr_;
  12247. #endif
  12248. thread t_;
  12249. };
  12250. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12251. auto res = cli_.Post("/test", "123456789", "text/plain");
  12252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12253. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12254. res = cli_.Post("/test", "12345678", "text/plain");
  12255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12256. EXPECT_EQ(StatusCode::OK_200, res->status);
  12257. }
  12258. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12259. // Test chunked encoding with payload exceeding the 8-byte limit
  12260. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12261. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12263. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12264. }
  12265. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12266. // Test chunked encoding with payload within the 8-byte limit
  12267. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12268. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12270. EXPECT_EQ(StatusCode::OK_200, res->status);
  12271. }
  12272. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12273. // Test using send_request to send chunked data exceeding payload limit
  12274. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12275. "Host: " +
  12276. std::string(HOST) + ":" + std::to_string(PORT) +
  12277. "\r\n"
  12278. "Transfer-Encoding: chunked\r\n"
  12279. "Connection: close\r\n"
  12280. "\r\n"
  12281. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12282. "0123456789\r\n"
  12283. "0\r\n" // End chunk
  12284. "\r\n";
  12285. std::string response;
  12286. bool result = send_request(1, chunked_request, &response);
  12287. if (!result) {
  12288. // If send_request fails, it might be because the server closed the
  12289. // connection due to payload limit enforcement, which is acceptable
  12290. SUCCEED()
  12291. << "Server rejected oversized chunked request (connection closed)";
  12292. } else {
  12293. // If we got a response, check if it's an error response or connection was
  12294. // closed early Short response length indicates connection was closed due to
  12295. // payload limit
  12296. if (response.length() <= 10) {
  12297. SUCCEED() << "Server closed connection for oversized chunked request";
  12298. } else {
  12299. // Check for error status codes
  12300. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12301. response.find("Payload Too Large") != std::string::npos ||
  12302. response.find("400") != std::string::npos);
  12303. }
  12304. }
  12305. }
  12306. class LargePayloadMaxLengthTest : public ::testing::Test {
  12307. protected:
  12308. LargePayloadMaxLengthTest()
  12309. : cli_(HOST, PORT)
  12310. #ifdef CPPHTTPLIB_SSL_ENABLED
  12311. ,
  12312. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12313. #endif
  12314. {
  12315. #ifdef CPPHTTPLIB_SSL_ENABLED
  12316. cli_.enable_server_certificate_verification(false);
  12317. #endif
  12318. }
  12319. virtual void SetUp() {
  12320. // Set 10MB payload limit
  12321. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12322. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12323. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12324. res.set_content("Large payload test", "text/plain");
  12325. });
  12326. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12327. svr_.wait_until_ready();
  12328. }
  12329. virtual void TearDown() {
  12330. svr_.stop();
  12331. t_.join();
  12332. }
  12333. #ifdef CPPHTTPLIB_SSL_ENABLED
  12334. SSLClient cli_;
  12335. SSLServer svr_;
  12336. #else
  12337. Client cli_;
  12338. Server svr_;
  12339. #endif
  12340. thread t_;
  12341. };
  12342. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12343. // Test chunked encoding with payload within 10MB limit
  12344. std::string medium_payload(5 * 1024 * 1024,
  12345. 'A'); // 5MB payload, within 10MB limit
  12346. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12348. EXPECT_EQ(StatusCode::OK_200, res->status);
  12349. }
  12350. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12351. // Test chunked encoding with payload exceeding 10MB limit
  12352. std::string large_payload(12 * 1024 * 1024,
  12353. 'B'); // 12MB payload, exceeds 10MB limit
  12354. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12355. // Server may either return 413 or close the connection
  12356. if (res) {
  12357. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12358. } else {
  12359. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12360. }
  12361. }
  12362. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12363. Server svr;
  12364. svr.Get("/", [](const Request &, Response &res) {
  12365. // Claims the most the client accepts, far more than it sends, then drops
  12366. // the connection.
  12367. res.set_content_provider(std::string().max_size(), "text/plain",
  12368. [](size_t, size_t, DataSink &sink) {
  12369. sink.write("abc", 3);
  12370. return false;
  12371. });
  12372. });
  12373. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12374. auto se = detail::scope_exit([&] {
  12375. svr.stop();
  12376. thread.join();
  12377. ASSERT_FALSE(svr.is_running());
  12378. });
  12379. svr.wait_until_ready();
  12380. Client cli(HOST, PORT);
  12381. cli.set_payload_max_length(0);
  12382. EXPECT_FALSE(cli.Get("/"));
  12383. }
  12384. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12385. // Stream API does, not as a plain read failure
  12386. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12387. Server svr;
  12388. svr.Get("/big", [](const Request &, Response &res) {
  12389. res.set_content(std::string(100000, 'b'), "text/plain");
  12390. });
  12391. auto port = svr.bind_to_any_port(HOST);
  12392. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12393. auto se = detail::scope_exit([&] {
  12394. svr.stop();
  12395. thread.join();
  12396. });
  12397. svr.wait_until_ready();
  12398. Client cli(HOST, port);
  12399. cli.set_payload_max_length(1000);
  12400. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12401. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12402. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12403. [](const char *, size_t) { return true; });
  12404. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12405. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12406. // Small on the wire, over the limit once decompressed
  12407. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12408. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12409. #endif
  12410. }
  12411. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12412. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12413. // path.
  12414. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12415. Server svr;
  12416. const size_t LIMIT = 64 * 1024; // 64KB
  12417. svr.set_payload_max_length(LIMIT);
  12418. size_t total = 0;
  12419. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12420. const ContentReader &content_reader) {
  12421. content_reader([&](const char * /*data*/, size_t len) {
  12422. total += len;
  12423. return true;
  12424. });
  12425. res.status = 200;
  12426. res.set_content("stream_ok", "text/plain");
  12427. });
  12428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12429. auto se = detail::scope_exit([&] {
  12430. svr.stop();
  12431. thread.join();
  12432. ASSERT_FALSE(svr.is_running());
  12433. });
  12434. svr.wait_until_ready();
  12435. // Prepare 256KB raw data and gzip-compress it
  12436. std::string raw(256 * 1024, 'A');
  12437. std::string gz;
  12438. {
  12439. z_stream zs{};
  12440. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12441. Z_DEFAULT_STRATEGY);
  12442. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12443. zs.avail_in = static_cast<uInt>(raw.size());
  12444. char outbuf[4096];
  12445. int ret;
  12446. do {
  12447. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12448. zs.avail_out = sizeof(outbuf);
  12449. ret = deflate(&zs, Z_FINISH);
  12450. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12451. } while (ret != Z_STREAM_END);
  12452. deflateEnd(&zs);
  12453. }
  12454. Client cli(HOST, PORT);
  12455. cli.set_connection_timeout(std::chrono::seconds(5));
  12456. Headers headers = {{"Content-Encoding", "gzip"}};
  12457. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12458. "application/octet-stream");
  12459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12460. // Server must reject oversized decompressed payloads with 413.
  12461. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12462. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12463. EXPECT_LE(total, LIMIT);
  12464. }
  12465. #endif
  12466. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12467. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12468. // the payload must be passed through untouched instead of being rejected.
  12469. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12470. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12471. Server svr;
  12472. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12473. res.set_content(body, "image/jpeg");
  12474. res.set_header("Content-Encoding", "UTF-8");
  12475. });
  12476. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12477. res.set_content(body, "image/jpeg");
  12478. res.set_header("Content-Encoding", "identity");
  12479. });
  12480. svr.Post("/echo", [](const Request &req, Response &res) {
  12481. res.set_content(req.body, "image/jpeg");
  12482. });
  12483. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12484. auto se = detail::scope_exit([&] {
  12485. svr.stop();
  12486. t.join();
  12487. ASSERT_FALSE(svr.is_running());
  12488. });
  12489. svr.wait_until_ready();
  12490. Client cli(HOST, PORT);
  12491. {
  12492. auto res = cli.Get("/image");
  12493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12494. EXPECT_EQ(StatusCode::OK_200, res->status);
  12495. EXPECT_EQ(body, res->body);
  12496. }
  12497. {
  12498. auto res = cli.Get("/identity");
  12499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12500. EXPECT_EQ(StatusCode::OK_200, res->status);
  12501. EXPECT_EQ(body, res->body);
  12502. }
  12503. {
  12504. // The same applies to a request body reaching the server.
  12505. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12506. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12508. EXPECT_EQ(StatusCode::OK_200, res->status);
  12509. EXPECT_EQ(body, res->body);
  12510. }
  12511. }
  12512. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12513. // gzip-encoded response even when the build has no zlib support.
  12514. static const char GZIPPED_HELLO_WORLD[] = {
  12515. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12516. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12517. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12518. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12519. // A content coding is a whole token, not something the field value merely
  12520. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12521. // as "fibre" look like Brotli, and turned a multi-coding value like
  12522. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12523. // it was never meant to see.
  12524. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12525. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12526. Server svr;
  12527. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12528. res.set_content(body, "image/jpeg");
  12529. res.set_header("Content-Encoding", "fibre");
  12530. });
  12531. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12532. res.set_content(body, "image/jpeg");
  12533. res.set_header("Content-Encoding", "gzip, br");
  12534. });
  12535. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12536. res.set_content(body, "image/jpeg");
  12537. res.set_header("Content-Encoding", "x-zstd-ish");
  12538. });
  12539. auto port = svr.bind_to_any_port(HOST);
  12540. thread t = thread([&]() { svr.listen_after_bind(); });
  12541. auto se = detail::scope_exit([&] {
  12542. svr.stop();
  12543. t.join();
  12544. ASSERT_FALSE(svr.is_running());
  12545. });
  12546. svr.wait_until_ready();
  12547. Client cli(HOST, port);
  12548. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12549. auto res = cli.Get(path);
  12550. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12551. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12552. // Not a coding we recognize, so the payload comes back untouched
  12553. EXPECT_EQ(body, res->body) << path;
  12554. }
  12555. }
  12556. // A content coding cpp-httplib recognizes but was not built with must be
  12557. // reported as such. Handing the still-compressed payload back to the caller
  12558. // would silently corrupt it.
  12559. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12560. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12561. Server svr;
  12562. // "image/jpeg" keeps the server from applying a content coding of its own,
  12563. // so the hand-crafted Content-Encoding below survives.
  12564. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12565. res.set_content(gzipped, "image/jpeg");
  12566. res.set_header("Content-Encoding", "gzip");
  12567. });
  12568. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12569. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12570. res.set_content(gzipped, "image/jpeg");
  12571. res.set_header("Content-Encoding", "GZIP");
  12572. });
  12573. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12574. auto se = detail::scope_exit([&] {
  12575. svr.stop();
  12576. t.join();
  12577. ASSERT_FALSE(svr.is_running());
  12578. });
  12579. svr.wait_until_ready();
  12580. Client cli(HOST, PORT);
  12581. {
  12582. auto res = cli.Get("/gzipped");
  12583. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12585. EXPECT_EQ("Hello World!", res->body);
  12586. #else
  12587. ASSERT_FALSE(res);
  12588. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12589. #endif
  12590. }
  12591. {
  12592. // open_stream() must behave the same way.
  12593. auto handle = cli.open_stream("GET", "/gzipped");
  12594. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12595. ASSERT_TRUE(handle.is_valid());
  12596. std::string received;
  12597. char buf[256];
  12598. ssize_t n;
  12599. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12600. received.append(buf, static_cast<size_t>(n));
  12601. }
  12602. EXPECT_EQ("Hello World!", received);
  12603. #else
  12604. EXPECT_FALSE(handle.is_valid());
  12605. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12606. #endif
  12607. }
  12608. {
  12609. // A differently-cased coding must not be mistaken for an unknown one, or
  12610. // the body would be handed back still compressed.
  12611. auto res = cli.Get("/gzipped-uppercase");
  12612. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12614. EXPECT_EQ("Hello World!", res->body);
  12615. #else
  12616. ASSERT_FALSE(res);
  12617. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12618. #endif
  12619. }
  12620. }
  12621. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12622. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12623. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12624. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12625. // body a second time and appending a second Content-Encoding field line, so
  12626. // clients that decode one coding per listed value handed back raw gzip bytes.
  12627. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12628. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12629. Server svr;
  12630. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12631. // keeps the server from applying a coding of its own.
  12632. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12633. res.set_content(gzipped, "text/plain");
  12634. res.set_header("Content-Encoding", "gzip");
  12635. });
  12636. auto port = svr.bind_to_any_port(HOST);
  12637. thread t = thread([&]() { svr.listen_after_bind(); });
  12638. auto se = detail::scope_exit([&] {
  12639. svr.stop();
  12640. t.join();
  12641. ASSERT_FALSE(svr.is_running());
  12642. });
  12643. svr.wait_until_ready();
  12644. Client cli(HOST, port);
  12645. Headers headers = {{"Accept-Encoding", "gzip"}};
  12646. auto res = cli.Get("/pre-gzipped", headers);
  12647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12648. EXPECT_EQ(StatusCode::OK_200, res->status);
  12649. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12650. EXPECT_EQ("Hello World!", res->body);
  12651. }
  12652. // set_compress(false) sends every handler response as it is, buffered or
  12653. // streamed
  12654. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12655. const std::string text(1000, 'a');
  12656. Server svr;
  12657. svr.set_compress(false);
  12658. svr.Get("/buffered", [&](const Request &, Response &res) {
  12659. res.set_content(text, "text/plain");
  12660. });
  12661. svr.Get("/streamed", [&](const Request &, Response &res) {
  12662. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12663. sink.write(text.data(), text.size());
  12664. sink.done();
  12665. return true;
  12666. });
  12667. });
  12668. auto port = svr.bind_to_any_port(HOST);
  12669. ASSERT_LT(0, port);
  12670. thread t = thread([&] { svr.listen_after_bind(); });
  12671. auto se = detail::scope_exit([&] {
  12672. svr.stop();
  12673. t.join();
  12674. ASSERT_FALSE(svr.is_running());
  12675. });
  12676. svr.wait_until_ready();
  12677. Client cli(HOST, port);
  12678. cli.set_decompress(false);
  12679. for (auto path : {"/buffered", "/streamed"}) {
  12680. SCOPED_TRACE(path);
  12681. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12683. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12684. EXPECT_EQ(text, res->body);
  12685. }
  12686. }
  12687. // A chunked provider settles its coding where the headers are written and
  12688. // reuses it at write time. Both ends of that have to hold: a handler's own
  12689. // Content-Encoding suppresses the coding, and a response without one is still
  12690. // compressed as it always was.
  12691. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12692. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12693. const std::string plain = "Hello World! Hello World! Hello World!";
  12694. Server svr;
  12695. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12696. res.set_header("Content-Encoding", "gzip");
  12697. res.set_chunked_content_provider(
  12698. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12699. sink.write(gzipped.data(), gzipped.size());
  12700. sink.done();
  12701. return true;
  12702. });
  12703. });
  12704. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12705. res.set_chunked_content_provider(
  12706. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12707. sink.write(plain.data(), plain.size());
  12708. sink.done();
  12709. return true;
  12710. });
  12711. });
  12712. auto port = svr.bind_to_any_port(HOST);
  12713. thread t = thread([&]() { svr.listen_after_bind(); });
  12714. auto se = detail::scope_exit([&] {
  12715. svr.stop();
  12716. t.join();
  12717. ASSERT_FALSE(svr.is_running());
  12718. });
  12719. svr.wait_until_ready();
  12720. Client cli(HOST, port);
  12721. Headers headers = {{"Accept-Encoding", "gzip"}};
  12722. {
  12723. auto res = cli.Get("/pre-gzipped", headers);
  12724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12725. EXPECT_EQ(StatusCode::OK_200, res->status);
  12726. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12727. EXPECT_EQ("Hello World!", res->body);
  12728. }
  12729. {
  12730. auto res = cli.Get("/negotiated", headers);
  12731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12732. EXPECT_EQ(StatusCode::OK_200, res->status);
  12733. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12734. EXPECT_EQ(plain, res->body);
  12735. }
  12736. }
  12737. #endif
  12738. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12739. // the same message as the comma-joined one, so both have to be read the same
  12740. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12741. // single gzip coding, and a body the sender says was encoded twice was handed
  12742. // back after one pass, still compressed but presented as decoded.
  12743. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12744. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12745. Server svr;
  12746. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12747. res.set_content(body, "image/jpeg");
  12748. res.headers.emplace("Content-Encoding", "gzip");
  12749. res.headers.emplace("Content-Encoding", "gzip");
  12750. });
  12751. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12752. res.set_content(body, "image/jpeg");
  12753. res.set_header("Content-Encoding", "gzip, gzip");
  12754. });
  12755. auto port = svr.bind_to_any_port(HOST);
  12756. thread t = thread([&]() { svr.listen_after_bind(); });
  12757. auto se = detail::scope_exit([&] {
  12758. svr.stop();
  12759. t.join();
  12760. ASSERT_FALSE(svr.is_running());
  12761. });
  12762. svr.wait_until_ready();
  12763. Client cli(HOST, port);
  12764. // Two codings is not something cpp-httplib decodes, so both representations
  12765. // take the pass-through path rather than one of them being gunzipped once.
  12766. for (const char *path : {"/split", "/joined"}) {
  12767. auto res = cli.Get(path);
  12768. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12769. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12770. EXPECT_EQ(body, res->body) << path;
  12771. }
  12772. }
  12773. // Regression test for DoS vulnerability: a malicious server sending a response
  12774. // without Content-Length header must not cause unbounded memory consumption on
  12775. // the client side. The client should stop reading after a reasonable limit,
  12776. // similar to the server-side set_payload_max_length protection.
  12777. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12778. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12779. #ifndef _WIN32
  12780. signal(SIGPIPE, SIG_IGN);
  12781. #endif
  12782. auto server_thread = std::thread([] {
  12783. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12784. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12785. default_socket_options(srv);
  12786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12787. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12788. sockaddr_in addr{};
  12789. addr.sin_family = AF_INET;
  12790. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12791. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12792. int opt = 1;
  12793. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12794. #ifdef _WIN32
  12795. reinterpret_cast<const char *>(&opt),
  12796. #else
  12797. &opt,
  12798. #endif
  12799. sizeof(opt));
  12800. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12801. ::listen(srv, 1);
  12802. sockaddr_in cli_addr{};
  12803. socklen_t cli_len = sizeof(cli_addr);
  12804. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12805. if (cli != INVALID_SOCKET) {
  12806. char buf[4096];
  12807. ::recv(cli, buf, sizeof(buf), 0);
  12808. // Malicious response: no Content-Length, no chunked encoding
  12809. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12810. "Connection: close\r\n"
  12811. "\r\n";
  12812. ::send(cli,
  12813. #ifdef _WIN32
  12814. static_cast<const char *>(response_header.c_str()),
  12815. static_cast<int>(response_header.size()),
  12816. #else
  12817. response_header.c_str(), response_header.size(),
  12818. #endif
  12819. 0);
  12820. // Send 10MB of data
  12821. std::string chunk(64 * 1024, 'A');
  12822. size_t total_sent = 0;
  12823. while (total_sent < MALICIOUS_DATA_SIZE) {
  12824. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12825. auto sent = ::send(cli,
  12826. #ifdef _WIN32
  12827. static_cast<const char *>(chunk.c_str()),
  12828. static_cast<int>(to_send),
  12829. #else
  12830. chunk.c_str(), to_send,
  12831. #endif
  12832. 0);
  12833. if (sent <= 0) break;
  12834. total_sent += static_cast<size_t>(sent);
  12835. }
  12836. detail::close_socket(cli);
  12837. }
  12838. detail::close_socket(srv);
  12839. });
  12840. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12841. size_t total_read = 0;
  12842. {
  12843. Client cli("127.0.0.1", PORT + 2);
  12844. cli.set_read_timeout(5, 0);
  12845. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12846. auto stream = cli.open_stream("GET", "/malicious");
  12847. ASSERT_TRUE(stream.is_valid());
  12848. char buffer[64 * 1024];
  12849. ssize_t n;
  12850. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12851. total_read += static_cast<size_t>(n);
  12852. }
  12853. } // StreamHandle and Client destroyed here, closing the socket
  12854. server_thread.join();
  12855. // With set_payload_max_length, the client must stop reading before consuming
  12856. // all 10MB. The read loop should be cut off at or near the configured limit.
  12857. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12858. << "Client read " << total_read << " bytes, exceeding the configured "
  12859. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12860. }
  12861. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12862. // the entire response body without truncation.
  12863. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12864. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12865. #ifndef _WIN32
  12866. signal(SIGPIPE, SIG_IGN);
  12867. #endif
  12868. auto server_thread = std::thread([] {
  12869. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12870. default_socket_options(srv);
  12871. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12872. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12873. sockaddr_in addr{};
  12874. addr.sin_family = AF_INET;
  12875. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12876. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12877. int opt = 1;
  12878. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12879. #ifdef _WIN32
  12880. reinterpret_cast<const char *>(&opt),
  12881. #else
  12882. &opt,
  12883. #endif
  12884. sizeof(opt));
  12885. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12886. ::listen(srv, 1);
  12887. sockaddr_in cli_addr{};
  12888. socklen_t cli_len = sizeof(cli_addr);
  12889. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12890. if (cli != INVALID_SOCKET) {
  12891. char buf[4096];
  12892. ::recv(cli, buf, sizeof(buf), 0);
  12893. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12894. "Connection: close\r\n"
  12895. "\r\n";
  12896. ::send(cli,
  12897. #ifdef _WIN32
  12898. static_cast<const char *>(response_header.c_str()),
  12899. static_cast<int>(response_header.size()),
  12900. #else
  12901. response_header.c_str(), response_header.size(),
  12902. #endif
  12903. 0);
  12904. std::string chunk(64 * 1024, 'A');
  12905. size_t total_sent = 0;
  12906. while (total_sent < DATA_SIZE) {
  12907. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12908. auto sent = ::send(cli,
  12909. #ifdef _WIN32
  12910. static_cast<const char *>(chunk.c_str()),
  12911. static_cast<int>(to_send),
  12912. #else
  12913. chunk.c_str(), to_send,
  12914. #endif
  12915. 0);
  12916. if (sent <= 0) break;
  12917. total_sent += static_cast<size_t>(sent);
  12918. }
  12919. #ifdef _WIN32
  12920. ::shutdown(cli, SD_SEND);
  12921. #else
  12922. ::shutdown(cli, SHUT_WR);
  12923. #endif
  12924. // Drain until the client closes its end, ensuring all data is delivered
  12925. char drain[1024];
  12926. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12927. detail::close_socket(cli);
  12928. }
  12929. detail::close_socket(srv);
  12930. });
  12931. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12932. size_t total_read = 0;
  12933. {
  12934. Client cli("127.0.0.1", PORT + 2);
  12935. cli.set_read_timeout(5, 0);
  12936. cli.set_payload_max_length(0); // 0 means no limit
  12937. auto stream = cli.open_stream("GET", "/data");
  12938. ASSERT_TRUE(stream.is_valid());
  12939. char buffer[64 * 1024];
  12940. ssize_t n;
  12941. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12942. total_read += static_cast<size_t>(n);
  12943. }
  12944. }
  12945. server_thread.join();
  12946. EXPECT_EQ(total_read, DATA_SIZE)
  12947. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12948. << " bytes without truncation, but only read " << total_read << " bytes.";
  12949. }
  12950. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12951. // enormous Content-Length must not cause the client to pre-allocate a huge
  12952. // response body buffer. The reservation is capped at payload_max_length_, and
  12953. // the read itself fails when the body exceeds the limit.
  12954. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12955. #ifndef _WIN32
  12956. signal(SIGPIPE, SIG_IGN);
  12957. #endif
  12958. auto server_thread = std::thread([] {
  12959. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12960. default_socket_options(srv);
  12961. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12962. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12963. sockaddr_in addr{};
  12964. addr.sin_family = AF_INET;
  12965. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12966. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12967. int opt = 1;
  12968. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12969. #ifdef _WIN32
  12970. reinterpret_cast<const char *>(&opt),
  12971. #else
  12972. &opt,
  12973. #endif
  12974. sizeof(opt));
  12975. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12976. ::listen(srv, 1);
  12977. sockaddr_in cli_addr{};
  12978. socklen_t cli_len = sizeof(cli_addr);
  12979. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12980. if (cli != INVALID_SOCKET) {
  12981. char buf[4096];
  12982. ::recv(cli, buf, sizeof(buf), 0);
  12983. // Malicious response: claim a 20GB body but send only a tiny payload.
  12984. std::string response = "HTTP/1.1 200 OK\r\n"
  12985. "Content-Length: 20000000000\r\n"
  12986. "\r\n"
  12987. "abc";
  12988. ::send(cli,
  12989. #ifdef _WIN32
  12990. static_cast<const char *>(response.c_str()),
  12991. static_cast<int>(response.size()),
  12992. #else
  12993. response.c_str(), response.size(),
  12994. #endif
  12995. 0);
  12996. detail::close_socket(cli);
  12997. }
  12998. detail::close_socket(srv);
  12999. });
  13000. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13001. {
  13002. Client cli("127.0.0.1", PORT + 2);
  13003. cli.set_read_timeout(5, 0);
  13004. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13005. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13006. // (server claims more bytes than payload_max_length permits), but it must
  13007. // not exhaust memory before getting there.
  13008. auto res = cli.Get("/malicious");
  13009. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13010. }
  13011. server_thread.join();
  13012. }
  13013. // Verify that content_receiver bypasses the default payload_max_length,
  13014. // allowing streaming downloads larger than 100MB without requiring an explicit
  13015. // set_payload_max_length call.
  13016. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13017. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13018. #ifndef _WIN32
  13019. signal(SIGPIPE, SIG_IGN);
  13020. #endif
  13021. auto server_thread = std::thread([] {
  13022. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13023. default_socket_options(srv);
  13024. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13025. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13026. sockaddr_in addr{};
  13027. addr.sin_family = AF_INET;
  13028. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13029. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13030. int opt = 1;
  13031. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13032. #ifdef _WIN32
  13033. reinterpret_cast<const char *>(&opt),
  13034. #else
  13035. &opt,
  13036. #endif
  13037. sizeof(opt));
  13038. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13039. ::listen(srv, 1);
  13040. sockaddr_in cli_addr{};
  13041. socklen_t cli_len = sizeof(cli_addr);
  13042. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13043. if (cli != INVALID_SOCKET) {
  13044. char buf[4096];
  13045. ::recv(cli, buf, sizeof(buf), 0);
  13046. // Response with Content-Length larger than default 100MB limit
  13047. auto content_length = std::to_string(DATA_SIZE);
  13048. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13049. "Content-Length: " +
  13050. content_length +
  13051. "\r\n"
  13052. "Connection: close\r\n"
  13053. "\r\n";
  13054. ::send(cli,
  13055. #ifdef _WIN32
  13056. static_cast<const char *>(response_header.c_str()),
  13057. static_cast<int>(response_header.size()),
  13058. #else
  13059. response_header.c_str(), response_header.size(),
  13060. #endif
  13061. 0);
  13062. std::string chunk(64 * 1024, 'A');
  13063. size_t total_sent = 0;
  13064. while (total_sent < DATA_SIZE) {
  13065. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13066. auto sent = ::send(cli,
  13067. #ifdef _WIN32
  13068. static_cast<const char *>(chunk.c_str()),
  13069. static_cast<int>(to_send),
  13070. #else
  13071. chunk.c_str(), to_send,
  13072. #endif
  13073. 0);
  13074. if (sent <= 0) break;
  13075. total_sent += static_cast<size_t>(sent);
  13076. }
  13077. detail::close_socket(cli);
  13078. }
  13079. detail::close_socket(srv);
  13080. });
  13081. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13082. size_t total_received = 0;
  13083. {
  13084. Client cli("127.0.0.1", PORT + 2);
  13085. cli.set_read_timeout(10, 0);
  13086. // Do NOT call set_payload_max_length — use the default 100MB limit
  13087. auto res =
  13088. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13089. total_received += data_length;
  13090. return true;
  13091. });
  13092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13093. EXPECT_EQ(StatusCode::OK_200, res->status);
  13094. }
  13095. server_thread.join();
  13096. EXPECT_EQ(total_received, DATA_SIZE)
  13097. << "With content_receiver, the client should read all " << DATA_SIZE
  13098. << " bytes despite the default 100MB payload_max_length, but only read "
  13099. << total_received << " bytes.";
  13100. }
  13101. // Verify that an explicit set_payload_max_length smaller than the response is
  13102. // enforced even when a content_receiver is used.
  13103. TEST(ClientVulnerabilityTest,
  13104. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13105. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13106. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13107. #ifndef _WIN32
  13108. signal(SIGPIPE, SIG_IGN);
  13109. #endif
  13110. auto server_thread = std::thread([] {
  13111. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13112. default_socket_options(srv);
  13113. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13114. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13115. sockaddr_in addr{};
  13116. addr.sin_family = AF_INET;
  13117. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13118. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13119. int opt = 1;
  13120. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13121. #ifdef _WIN32
  13122. reinterpret_cast<const char *>(&opt),
  13123. #else
  13124. &opt,
  13125. #endif
  13126. sizeof(opt));
  13127. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13128. ::listen(srv, 1);
  13129. sockaddr_in cli_addr{};
  13130. socklen_t cli_len = sizeof(cli_addr);
  13131. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13132. if (cli != INVALID_SOCKET) {
  13133. char buf[4096];
  13134. ::recv(cli, buf, sizeof(buf), 0);
  13135. auto content_length = std::to_string(DATA_SIZE);
  13136. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13137. "Content-Length: " +
  13138. content_length +
  13139. "\r\n"
  13140. "Connection: close\r\n"
  13141. "\r\n";
  13142. ::send(cli,
  13143. #ifdef _WIN32
  13144. static_cast<const char *>(response_header.c_str()),
  13145. static_cast<int>(response_header.size()),
  13146. #else
  13147. response_header.c_str(), response_header.size(),
  13148. #endif
  13149. 0);
  13150. std::string chunk(64 * 1024, 'A');
  13151. size_t total_sent = 0;
  13152. while (total_sent < DATA_SIZE) {
  13153. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13154. auto sent = ::send(cli,
  13155. #ifdef _WIN32
  13156. static_cast<const char *>(chunk.c_str()),
  13157. static_cast<int>(to_send),
  13158. #else
  13159. chunk.c_str(), to_send,
  13160. #endif
  13161. 0);
  13162. if (sent <= 0) break;
  13163. total_sent += static_cast<size_t>(sent);
  13164. }
  13165. detail::close_socket(cli);
  13166. }
  13167. detail::close_socket(srv);
  13168. });
  13169. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13170. size_t total_received = 0;
  13171. {
  13172. Client cli("127.0.0.1", PORT + 2);
  13173. cli.set_read_timeout(10, 0);
  13174. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13175. auto res =
  13176. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13177. total_received += data_length;
  13178. return true;
  13179. });
  13180. // Should fail because 200MB exceeds the explicit 150MB limit
  13181. EXPECT_FALSE(res);
  13182. }
  13183. server_thread.join();
  13184. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13185. << "Client with content_receiver should respect the explicit "
  13186. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13187. << total_received << " bytes.";
  13188. }
  13189. // Verify that an explicit set_payload_max_length larger than the response
  13190. // allows the content_receiver to read all data successfully.
  13191. TEST(ClientVulnerabilityTest,
  13192. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13193. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13194. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13195. #ifndef _WIN32
  13196. signal(SIGPIPE, SIG_IGN);
  13197. #endif
  13198. auto server_thread = std::thread([] {
  13199. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13200. default_socket_options(srv);
  13201. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13202. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13203. sockaddr_in addr{};
  13204. addr.sin_family = AF_INET;
  13205. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13206. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13207. int opt = 1;
  13208. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13209. #ifdef _WIN32
  13210. reinterpret_cast<const char *>(&opt),
  13211. #else
  13212. &opt,
  13213. #endif
  13214. sizeof(opt));
  13215. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13216. ::listen(srv, 1);
  13217. sockaddr_in cli_addr{};
  13218. socklen_t cli_len = sizeof(cli_addr);
  13219. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13220. if (cli != INVALID_SOCKET) {
  13221. char buf[4096];
  13222. ::recv(cli, buf, sizeof(buf), 0);
  13223. auto content_length = std::to_string(DATA_SIZE);
  13224. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13225. "Content-Length: " +
  13226. content_length +
  13227. "\r\n"
  13228. "Connection: close\r\n"
  13229. "\r\n";
  13230. ::send(cli,
  13231. #ifdef _WIN32
  13232. static_cast<const char *>(response_header.c_str()),
  13233. static_cast<int>(response_header.size()),
  13234. #else
  13235. response_header.c_str(), response_header.size(),
  13236. #endif
  13237. 0);
  13238. std::string chunk(64 * 1024, 'A');
  13239. size_t total_sent = 0;
  13240. while (total_sent < DATA_SIZE) {
  13241. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13242. auto sent = ::send(cli,
  13243. #ifdef _WIN32
  13244. static_cast<const char *>(chunk.c_str()),
  13245. static_cast<int>(to_send),
  13246. #else
  13247. chunk.c_str(), to_send,
  13248. #endif
  13249. 0);
  13250. if (sent <= 0) break;
  13251. total_sent += static_cast<size_t>(sent);
  13252. }
  13253. #ifdef _WIN32
  13254. ::shutdown(cli, SD_SEND);
  13255. #else
  13256. ::shutdown(cli, SHUT_WR);
  13257. #endif
  13258. char drain[1024];
  13259. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13260. detail::close_socket(cli);
  13261. }
  13262. detail::close_socket(srv);
  13263. });
  13264. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13265. size_t total_received = 0;
  13266. {
  13267. Client cli("127.0.0.1", PORT + 2);
  13268. cli.set_read_timeout(10, 0);
  13269. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13270. auto res =
  13271. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13272. total_received += data_length;
  13273. return true;
  13274. });
  13275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13276. EXPECT_EQ(StatusCode::OK_200, res->status);
  13277. }
  13278. server_thread.join();
  13279. EXPECT_EQ(total_received, DATA_SIZE)
  13280. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13281. << " bytes (larger than " << DATA_SIZE
  13282. << " bytes response), content_receiver should read all data, but only "
  13283. "read "
  13284. << total_received << " bytes.";
  13285. }
  13286. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13287. // Regression test for "zip bomb" attack on the client side: a malicious server
  13288. // sends a small gzip-compressed response that decompresses to a huge payload.
  13289. // The client must enforce payload_max_length on the decompressed size.
  13290. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13291. constexpr size_t DECOMPRESSED_SIZE =
  13292. 10 * 1024 * 1024; // 10MB after decompression
  13293. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13294. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13295. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13296. std::string compressed;
  13297. {
  13298. httplib::detail::gzip_compressor compressor;
  13299. bool ok =
  13300. compressor.compress(uncompressed.data(), uncompressed.size(),
  13301. /*last=*/true, [&](const char *buf, size_t len) {
  13302. compressed.append(buf, len);
  13303. return true;
  13304. });
  13305. ASSERT_TRUE(ok);
  13306. }
  13307. // Sanity: compressed data should be much smaller than the decompressed size
  13308. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13309. #ifndef _WIN32
  13310. signal(SIGPIPE, SIG_IGN);
  13311. #endif
  13312. // Set up the listening socket in the main thread so the server is guaranteed
  13313. // to be ready before the client connects (eliminates race condition).
  13314. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13315. default_socket_options(srv);
  13316. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13317. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13318. sockaddr_in addr{};
  13319. addr.sin_family = AF_INET;
  13320. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13321. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13322. int opt = 1;
  13323. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13324. #ifdef _WIN32
  13325. reinterpret_cast<const char *>(&opt),
  13326. #else
  13327. &opt,
  13328. #endif
  13329. sizeof(opt));
  13330. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13331. ASSERT_EQ(0, ::listen(srv, 1));
  13332. auto server_thread = std::thread([&compressed, srv] {
  13333. sockaddr_in cli_addr{};
  13334. socklen_t cli_len = sizeof(cli_addr);
  13335. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13336. if (cli != INVALID_SOCKET) {
  13337. // Read the full HTTP request (until \r\n\r\n)
  13338. char buf[4096];
  13339. size_t total = 0;
  13340. while (total < sizeof(buf)) {
  13341. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13342. if (n <= 0) break;
  13343. total += static_cast<size_t>(n);
  13344. // Check for end of headers
  13345. if (total >= 4) {
  13346. std::string req(buf, total);
  13347. if (req.find("\r\n\r\n") != std::string::npos) break;
  13348. }
  13349. }
  13350. // Malicious response: gzip-compressed body, no Content-Length
  13351. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13352. "Content-Encoding: gzip\r\n"
  13353. "Connection: close\r\n"
  13354. "\r\n";
  13355. ::send(cli,
  13356. #ifdef _WIN32
  13357. static_cast<const char *>(response_header.c_str()),
  13358. static_cast<int>(response_header.size()),
  13359. #else
  13360. response_header.c_str(), response_header.size(),
  13361. #endif
  13362. 0);
  13363. // Send the compressed payload (small on the wire, huge when decompressed)
  13364. size_t total_sent = 0;
  13365. while (total_sent < compressed.size()) {
  13366. auto to_send = std::min(compressed.size() - total_sent,
  13367. static_cast<size_t>(64 * 1024));
  13368. auto sent =
  13369. ::send(cli,
  13370. #ifdef _WIN32
  13371. static_cast<const char *>(compressed.c_str() + total_sent),
  13372. static_cast<int>(to_send),
  13373. #else
  13374. compressed.c_str() + total_sent, to_send,
  13375. #endif
  13376. 0);
  13377. if (sent <= 0) break;
  13378. total_sent += static_cast<size_t>(sent);
  13379. }
  13380. detail::close_socket(cli);
  13381. }
  13382. });
  13383. auto se = detail::scope_exit([&] {
  13384. detail::close_socket(srv);
  13385. server_thread.join();
  13386. });
  13387. size_t total_decompressed = 0;
  13388. {
  13389. Client cli("127.0.0.1", PORT + 3);
  13390. cli.set_read_timeout(5, 0);
  13391. cli.set_decompress(true);
  13392. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13393. auto stream = cli.open_stream("GET", "/zipbomb");
  13394. ASSERT_TRUE(stream.is_valid());
  13395. char buffer[64 * 1024];
  13396. ssize_t n;
  13397. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13398. total_decompressed += static_cast<size_t>(n);
  13399. }
  13400. }
  13401. // The decompressed size must be capped by payload_max_length. Without
  13402. // protection, the client would decompress the full 10MB from a tiny
  13403. // compressed payload, enabling a zip bomb DoS attack.
  13404. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13405. << "Client decompressed " << total_decompressed
  13406. << " bytes from a gzip response. The decompressed size should be "
  13407. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13408. }
  13409. #endif
  13410. TEST(HostAndPortPropertiesTest, NoSSL) {
  13411. httplib::Client cli("www.google.com", 1234);
  13412. ASSERT_EQ("www.google.com", cli.host());
  13413. ASSERT_EQ(1234, cli.port());
  13414. }
  13415. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13416. httplib::Client cli("www.google.com:1234");
  13417. ASSERT_EQ("www.google.com", cli.host());
  13418. ASSERT_EQ(1234, cli.port());
  13419. }
  13420. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13421. // Port number that overflows int — should not crash, client becomes invalid
  13422. httplib::Client cli("http://www.google.com:99999999999999999999");
  13423. ASSERT_FALSE(cli.is_valid());
  13424. }
  13425. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13426. // Port 99999 exceeds valid range (1-65535) — should not crash
  13427. httplib::Client cli("http://www.google.com:99999");
  13428. ASSERT_FALSE(cli.is_valid());
  13429. auto res = cli.Get("/");
  13430. EXPECT_FALSE(res);
  13431. EXPECT_EQ(Error::Connection, res.error());
  13432. }
  13433. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13434. httplib::Client cli("http://user:pass@localhost:1234");
  13435. ASSERT_FALSE(cli.is_valid());
  13436. EXPECT_FALSE(cli.Get("/"));
  13437. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13438. }
  13439. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13440. httplib::Client cli("http://www.google.com:80abc");
  13441. ASSERT_FALSE(cli.is_valid());
  13442. }
  13443. #ifdef CPPHTTPLIB_SSL_ENABLED
  13444. TEST(HostAndPortPropertiesTest, SSL) {
  13445. httplib::SSLClient cli("www.google.com");
  13446. ASSERT_EQ("www.google.com", cli.host());
  13447. ASSERT_EQ(443, cli.port());
  13448. }
  13449. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13450. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13451. std::string cert;
  13452. read_file(CA_CERT_FILE, cert);
  13453. httplib::SSLClient httplib_client("www.google.com");
  13454. // Load CA store first time
  13455. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13456. // Load CA store second time (update)
  13457. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13458. // Verify client is still valid and can make connections
  13459. httplib_client.enable_server_certificate_verification(true);
  13460. auto res = httplib_client.Get("/");
  13461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13462. // Google may return 200 or 301 depending on various factors
  13463. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13464. res->status == StatusCode::MovedPermanently_301);
  13465. }
  13466. TEST(SSLClientTest, ServerNameIndication_Online) {
  13467. auto host = "httpbingo.org";
  13468. auto path = std::string{"/get"};
  13469. SSLClient cli(host, 443);
  13470. auto res = cli.Get(path);
  13471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13472. ASSERT_EQ(StatusCode::OK_200, res->status);
  13473. }
  13474. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13475. // Use a site that will cause SSL verification failure due to self-signed cert
  13476. SSLClient cli("self-signed.badssl.com", 443);
  13477. cli.enable_server_certificate_verification(true);
  13478. auto res = cli.Get("/");
  13479. ASSERT_TRUE(!res);
  13480. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13481. // Verify backend error is captured for SSLServerVerification
  13482. // This occurs when certificate verification fails
  13483. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13484. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13485. EXPECT_NE(0UL, res.ssl_backend_error());
  13486. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13487. res.ssl_error());
  13488. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13489. #if !defined(_WIN32) || \
  13490. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13491. // On non-Windows or when Windows Schannel is disabled, the error comes
  13492. // from OpenSSL's verification
  13493. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13494. res.ssl_backend_error());
  13495. #endif
  13496. #endif
  13497. }
  13498. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13499. // Use a site where hostname doesn't match the certificate
  13500. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13501. SSLClient cli("wrong.host.badssl.com", 443);
  13502. cli.enable_server_certificate_verification(true);
  13503. cli.enable_server_hostname_verification(true);
  13504. auto res = cli.Get("/");
  13505. ASSERT_TRUE(!res);
  13506. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13507. // Verify backend error is captured for hostname verification failure
  13508. EXPECT_NE(0UL, res.ssl_backend_error());
  13509. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13510. res.ssl_error());
  13511. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13512. #if !defined(_WIN32) || \
  13513. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13514. // On non-Windows or when Windows Schannel is disabled, the error comes
  13515. // from OpenSSL's hostname verification
  13516. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13517. res.ssl_backend_error());
  13518. #endif
  13519. #endif
  13520. }
  13521. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13522. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13523. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13524. SSLClient cli("www.google.com", 443);
  13525. cli.enable_server_certificate_verification(true);
  13526. auto res = cli.Get("/");
  13527. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13528. }
  13529. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13530. SSLClient cli("www.google.com", 443);
  13531. cli.enable_server_certificate_verification(true);
  13532. cli.enable_windows_certificate_verification(false);
  13533. auto res = cli.Get("/");
  13534. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13535. }
  13536. // The server sends an intermediate cross-signed by a root Windows trusts,
  13537. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13538. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13539. SSLClient cli("accounts.spotify.com", 443);
  13540. auto res = cli.Get("/");
  13541. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13542. << " ssl_backend_error=" << res.ssl_backend_error();
  13543. }
  13544. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13545. // policy status, which no backend reports for a self-signed certificate.
  13546. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13547. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13548. ASSERT_TRUE(svr.is_valid());
  13549. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13550. auto se = detail::scope_exit([&] {
  13551. svr.stop();
  13552. t.join();
  13553. ASSERT_FALSE(svr.is_running());
  13554. });
  13555. svr.wait_until_ready();
  13556. SSLClient cli("127.0.0.1", PORT);
  13557. cli.set_connection_timeout(30);
  13558. auto res = cli.Get("/");
  13559. ASSERT_FALSE(res);
  13560. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13561. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13562. }
  13563. #endif
  13564. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13565. Client cli("https://google.com");
  13566. auto res = cli.Get("/");
  13567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13568. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13569. }
  13570. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13571. SSLClient cli("google.com");
  13572. cli.set_ca_cert_path(CA_CERT_FILE);
  13573. auto res = cli.Get("/");
  13574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13575. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13576. }
  13577. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13578. SSLClient cli("google.com");
  13579. cli.enable_server_certificate_verification(true);
  13580. cli.set_ca_cert_path("hello");
  13581. auto res = cli.Get("/");
  13582. ASSERT_TRUE(!res);
  13583. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13584. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13585. // should be set
  13586. EXPECT_EQ(0, res.ssl_error());
  13587. // Verify backend error is captured for SSLLoadingCerts
  13588. // This error occurs when loading CA certificates fails
  13589. EXPECT_NE(0UL, res.ssl_backend_error());
  13590. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13591. // OpenSSL specific error codes:
  13592. // > openssl errstr 0x80000002
  13593. // error:80000002:system library::No such file or directory
  13594. // > openssl errstr 0xA000126
  13595. // error:0A000126:SSL routines::unexpected eof while reading
  13596. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13597. res.ssl_backend_error() == 0xA000126);
  13598. #endif
  13599. }
  13600. TEST(SSLClientTest, ServerCertificateVerification4) {
  13601. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13602. ASSERT_TRUE(svr.is_valid());
  13603. svr.Get("/test", [&](const Request &, Response &res) {
  13604. res.set_content("test", "text/plain");
  13605. svr.stop();
  13606. ASSERT_TRUE(true);
  13607. });
  13608. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13609. auto se = detail::scope_exit([&] {
  13610. t.join();
  13611. ASSERT_FALSE(svr.is_running());
  13612. });
  13613. svr.wait_until_ready();
  13614. SSLClient cli("127.0.0.1", PORT);
  13615. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13616. cli.enable_server_certificate_verification(true);
  13617. cli.set_connection_timeout(30);
  13618. auto res = cli.Get("/test");
  13619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13620. ASSERT_EQ(StatusCode::OK_200, res->status);
  13621. }
  13622. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13623. std::string cert;
  13624. read_file(CA_CERT_FILE, cert);
  13625. SSLClient cli("google.com");
  13626. cli.load_ca_cert_store(cert.data(), cert.size());
  13627. const auto res = cli.Get("/");
  13628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13629. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13630. }
  13631. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13632. // clang-format off
  13633. static constexpr char cert[] =
  13634. "GlobalSign Root CA\n"
  13635. "==================\n"
  13636. "-----BEGIN CERTIFICATE-----\n"
  13637. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13638. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13639. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13640. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13641. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13642. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13643. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13644. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13645. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13646. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13647. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13648. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13649. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13650. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13651. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13652. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13653. "-----END CERTIFICATE-----\n";
  13654. // clang-format on
  13655. SSLClient cli("google.com");
  13656. cli.load_ca_cert_store(cert, sizeof(cert));
  13657. const auto res = cli.Get("/");
  13658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13659. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13660. }
  13661. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13662. SSLClient cli("www.youtube.com");
  13663. cli.set_ca_cert_path(CA_CERT_FILE);
  13664. cli.enable_server_certificate_verification(true);
  13665. cli.set_follow_location(true);
  13666. auto res = cli.Get("/");
  13667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13668. ASSERT_EQ(StatusCode::OK_200, res->status);
  13669. }
  13670. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13671. SSLClient cli("wWw.YouTube.Com");
  13672. cli.set_ca_cert_path(CA_CERT_FILE);
  13673. cli.enable_server_certificate_verification(true);
  13674. cli.enable_server_hostname_verification(true);
  13675. cli.set_follow_location(true);
  13676. auto res = cli.Get("/");
  13677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13678. ASSERT_EQ(StatusCode::OK_200, res->status);
  13679. }
  13680. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13681. SSLClient cli("gOoGlE.COm");
  13682. cli.enable_server_certificate_verification(true);
  13683. cli.enable_server_hostname_verification(true);
  13684. cli.set_follow_location(true);
  13685. auto res = cli.Get("/");
  13686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13687. ASSERT_EQ(StatusCode::OK_200, res->status);
  13688. }
  13689. TEST(SSLClientTest, Issue2004_Online) {
  13690. Client client("https://google.com");
  13691. client.set_follow_location(true);
  13692. auto res = client.Get("/");
  13693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13694. ASSERT_EQ(StatusCode::OK_200, res->status);
  13695. auto body = res->body;
  13696. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13697. }
  13698. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13699. // Create SSLClient with invalid cert/key to make is_valid() return false
  13700. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13701. "nonexistent_key.pem");
  13702. // is_valid() should be false due to cert loading failure
  13703. ASSERT_FALSE(cli.is_valid());
  13704. auto res = cli.Get("/");
  13705. ASSERT_FALSE(res);
  13706. EXPECT_EQ(Error::SSLConnection, res.error());
  13707. }
  13708. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13709. // Test for Issue #2251: SSL error not properly reported when client cert
  13710. // and key paths are swapped or mismatched
  13711. // This simulates the scenario where user accidentally swaps the cert and key
  13712. // files
  13713. // Using client cert file as private key and vice versa (completely wrong)
  13714. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13715. // Should fail validation due to cert/key mismatch
  13716. ASSERT_FALSE(cli.is_valid());
  13717. // Attempt to make a request should fail with proper error
  13718. auto res = cli.Get("/");
  13719. ASSERT_FALSE(res);
  13720. EXPECT_EQ(Error::SSLConnection, res.error());
  13721. // SSL error should be recorded in the Result object (this is the key fix for
  13722. // Issue #2251)
  13723. auto backend_error = res.ssl_backend_error();
  13724. EXPECT_NE(0u, backend_error);
  13725. }
  13726. // Tests cert/key mismatch detection at the TLS context level
  13727. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13728. // Test that using mismatched cert/key causes connection failure.
  13729. // We verify this at the SSLClient level rather than through internal
  13730. // TLS API functions.
  13731. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13732. cli.enable_server_certificate_verification(false);
  13733. cli.set_connection_timeout(2);
  13734. // The mismatch should cause a connection or handshake error
  13735. auto res = cli.Get("/test");
  13736. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13737. // Either way, the request should fail
  13738. EXPECT_FALSE(res);
  13739. }
  13740. #endif
  13741. #if 0
  13742. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13743. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13744. ASSERT_TRUE(cli != nullptr);
  13745. cli->set_address_family(AF_INET6);
  13746. cli->set_interface("en0");
  13747. auto res = cli->Get("/get");
  13748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13749. ASSERT_EQ(StatusCode::OK_200, res->status);
  13750. }
  13751. #endif
  13752. // Client certificate tests - work with all TLS backends
  13753. #ifdef CPPHTTPLIB_SSL_ENABLED
  13754. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13755. void ClientCertPresent(
  13756. const std::string &client_cert_file,
  13757. const std::string &client_private_key_file,
  13758. const std::string &client_encrypted_private_key_pass = std::string(),
  13759. const ClientCertServerSetup &setup = nullptr) {
  13760. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13761. ASSERT_TRUE(svr.is_valid());
  13762. if (setup) { setup(svr); }
  13763. svr.Get("/test", [&](const Request &req, Response &res) {
  13764. res.set_content("test", "text/plain");
  13765. auto cert = req.peer_cert();
  13766. ASSERT_TRUE(static_cast<bool>(cert));
  13767. std::string common_name = cert.subject_cn();
  13768. EXPECT_EQ("Common Name", common_name);
  13769. });
  13770. auto port = svr.bind_to_any_port(HOST);
  13771. ASSERT_LT(0, port);
  13772. thread t = thread([&]() { svr.listen_after_bind(); });
  13773. auto se = detail::scope_exit([&] {
  13774. svr.stop();
  13775. t.join();
  13776. ASSERT_FALSE(svr.is_running());
  13777. });
  13778. svr.wait_until_ready();
  13779. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13780. client_encrypted_private_key_pass);
  13781. cli.enable_server_certificate_verification(false);
  13782. cli.set_connection_timeout(30);
  13783. auto res = cli.Get("/test");
  13784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13785. ASSERT_EQ(StatusCode::OK_200, res->status);
  13786. }
  13787. TEST(SSLClientServerTest, ClientCertPresent) {
  13788. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13789. }
  13790. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13791. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13792. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13793. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13794. }
  13795. // Expects svr, which must require client certificates, to reject a client
  13796. // that has none
  13797. void RejectsClientWithoutCert(SSLServer &svr) {
  13798. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13799. auto port = svr.bind_to_any_port(HOST);
  13800. ASSERT_LT(0, port);
  13801. thread t = thread([&]() { svr.listen_after_bind(); });
  13802. auto se = detail::scope_exit([&] {
  13803. svr.stop();
  13804. t.join();
  13805. ASSERT_FALSE(svr.is_running());
  13806. });
  13807. svr.wait_until_ready();
  13808. SSLClient cli(HOST, port);
  13809. cli.set_connection_timeout(30);
  13810. // Skip the server certificate check, so that the request fails because the
  13811. // client certificate is missing rather than because cert.pem is not trusted
  13812. cli.enable_server_certificate_verification(false);
  13813. auto res = cli.Get("/test");
  13814. ASSERT_FALSE(res);
  13815. // The server rejects the client during the handshake, or on TLS 1.3 right
  13816. // after it, which the client notices on its first write or read
  13817. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13818. res.error() == Error::Write || res.error() == Error::Read)
  13819. << to_string(res.error());
  13820. if (res.error() == Error::SSLConnection) {
  13821. EXPECT_NE(0UL, res.ssl_backend_error());
  13822. }
  13823. // A rejection noticed on the write keeps the TLS error the write hit
  13824. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13825. }
  13826. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13828. ASSERT_TRUE(svr.is_valid());
  13829. if (setup) { setup(svr); }
  13830. RejectsClientWithoutCert(svr);
  13831. }
  13832. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13833. // A server that requires client certificates must keep requiring them after
  13834. // setup changes it, and keep accepting a client that has one
  13835. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13836. ClientCertMissing(setup);
  13837. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13838. setup);
  13839. }
  13840. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13841. ClientCertStillRequired([](SSLServer &svr) {
  13842. ASSERT_TRUE(tls::set_verify_callback(
  13843. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13844. });
  13845. }
  13846. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13847. ClientCertStillRequired([](SSLServer &svr) {
  13848. ASSERT_TRUE(tls::set_verify_callback(
  13849. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13850. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13851. });
  13852. }
  13853. // The client verifies the server certificate during the handshake, so a
  13854. // server that fails the check never gets the client certificate, even when a
  13855. // verifier of the client's own accepts it
  13856. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13857. struct Case {
  13858. const char *trusted_ca;
  13859. const char *host;
  13860. Error error;
  13861. };
  13862. // cert2.pem names localhost: the first client does not trust it, and the
  13863. // second trusts it but asks for another name
  13864. for (const auto &c :
  13865. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13866. Case{SERVER_CERT2_FILE, "example.com",
  13867. Error::SSLServerHostnameVerification}}) {
  13868. for (auto with_verifier : {false, true}) {
  13869. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13870. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13871. CLIENT_CA_CERT_FILE);
  13872. ASSERT_TRUE(svr.is_valid());
  13873. std::atomic<bool> got_client_cert{false};
  13874. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13875. [&](const tls::VerifyContext &) {
  13876. got_client_cert = true;
  13877. return true;
  13878. }));
  13879. auto port = svr.bind_to_any_port("127.0.0.1");
  13880. ASSERT_LT(0, port);
  13881. thread t = thread([&] { svr.listen_after_bind(); });
  13882. svr.wait_until_ready();
  13883. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13884. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13885. cli.set_ca_cert_path(c.trusted_ca);
  13886. if (with_verifier) {
  13887. cli.set_server_certificate_verifier(
  13888. [](const tls::VerifyContext &) { return true; });
  13889. }
  13890. auto res = cli.Get("/");
  13891. EXPECT_FALSE(res);
  13892. EXPECT_EQ(c.error, res.error());
  13893. svr.stop();
  13894. t.join();
  13895. EXPECT_FALSE(got_client_cert);
  13896. }
  13897. }
  13898. }
  13899. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13900. std::string cert_pem, key_pem, ca_pem;
  13901. read_file(SERVER_CERT_FILE, cert_pem);
  13902. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13903. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13904. ASSERT_TRUE(
  13905. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13906. }
  13907. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13909. ASSERT_TRUE(svr.is_valid());
  13910. UpdateCertsPemWithClientCA(svr);
  13911. RejectsClientWithoutCert(svr);
  13912. }
  13913. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13914. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13915. }
  13916. // A TLS error from one request must not show up in a later request's Result
  13917. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13919. ASSERT_TRUE(svr.is_valid());
  13920. svr.Get("/test", [](const Request &, Response &res) {
  13921. res.set_content("test", "text/plain");
  13922. });
  13923. auto port = svr.bind_to_any_port(HOST);
  13924. ASSERT_LT(0, port);
  13925. thread t = thread([&]() { svr.listen_after_bind(); });
  13926. auto se = detail::scope_exit([&] {
  13927. svr.stop();
  13928. t.join();
  13929. ASSERT_FALSE(svr.is_running());
  13930. });
  13931. svr.wait_until_ready();
  13932. SSLClient cli(HOST, port);
  13933. cli.set_connection_timeout(30);
  13934. cli.enable_server_hostname_verification(false);
  13935. // cert.pem is not trusted, so the handshake fails
  13936. ASSERT_FALSE(cli.Get("/test"));
  13937. cli.enable_server_certificate_verification(false);
  13938. auto res = cli.Get("/test");
  13939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13940. EXPECT_EQ(0, res.ssl_error());
  13941. EXPECT_EQ(0UL, res.ssl_backend_error());
  13942. }
  13943. // PEM memory-based constructor tests (works with all TLS backends).
  13944. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13945. // terminator after it.
  13946. void PemMemoryClientCertPresent(
  13947. const std::string &client_cert_file,
  13948. const std::string &client_private_key_file,
  13949. const std::string &client_encrypted_private_key_pass = std::string(),
  13950. bool exact_size = false) {
  13951. // Read PEM files into memory
  13952. std::string server_cert_pem, server_key_pem;
  13953. std::string client_ca_pem;
  13954. std::string client_cert_pem, client_key_pem;
  13955. read_file(SERVER_CERT_FILE, server_cert_pem);
  13956. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13957. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13958. read_file(client_cert_file, client_cert_pem);
  13959. read_file(client_private_key_file, client_key_pem);
  13960. std::list<std::vector<char>> exact_copies;
  13961. auto data = [&](const std::string &pem) -> const char * {
  13962. if (!exact_size) { return pem.c_str(); }
  13963. exact_copies.emplace_back(pem.begin(), pem.end());
  13964. return exact_copies.back().data();
  13965. };
  13966. // Create server with PEM memory
  13967. SSLServer::PemMemory server_pem = {
  13968. data(server_cert_pem),
  13969. server_cert_pem.size(),
  13970. data(server_key_pem),
  13971. server_key_pem.size(),
  13972. data(client_ca_pem),
  13973. client_ca_pem.size(),
  13974. nullptr // no password for server key
  13975. };
  13976. SSLServer svr(server_pem);
  13977. ASSERT_TRUE(svr.is_valid());
  13978. svr.Get("/test", [&](const Request &req, Response &res) {
  13979. res.set_content("test", "text/plain");
  13980. auto cert = req.peer_cert();
  13981. ASSERT_TRUE(static_cast<bool>(cert));
  13982. EXPECT_EQ("Common Name", cert.subject_cn());
  13983. });
  13984. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13985. auto se = detail::scope_exit([&] {
  13986. svr.stop();
  13987. t.join();
  13988. ASSERT_FALSE(svr.is_running());
  13989. });
  13990. svr.wait_until_ready();
  13991. // Create client with PEM memory
  13992. const char *password = client_encrypted_private_key_pass.empty()
  13993. ? nullptr
  13994. : client_encrypted_private_key_pass.c_str();
  13995. SSLClient::PemMemory client_pem = {
  13996. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13997. client_key_pem.size(), password};
  13998. SSLClient cli(HOST, PORT, client_pem);
  13999. cli.enable_server_certificate_verification(false);
  14000. cli.set_connection_timeout(30);
  14001. auto res = cli.Get("/test");
  14002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14003. ASSERT_EQ(StatusCode::OK_200, res->status);
  14004. }
  14005. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14006. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14007. }
  14008. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14009. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14010. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14011. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14012. }
  14013. // A server built from PEM memory with a client CA requires client certificates,
  14014. // also when the CA is a NUL-terminated string passed with a length of 0
  14015. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14016. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14017. read_file(SERVER_CERT_FILE, server_cert_pem);
  14018. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14019. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14020. SSLServer::PemMemory server_pem = {
  14021. server_cert_pem.c_str(),
  14022. server_cert_pem.size(),
  14023. server_key_pem.c_str(),
  14024. server_key_pem.size(),
  14025. client_ca_pem.c_str(),
  14026. client_ca_pem.size(),
  14027. nullptr // no password for server key
  14028. };
  14029. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14030. SCOPED_TRACE(client_ca_pem_len);
  14031. server_pem.client_ca_pem_len = client_ca_pem_len;
  14032. SSLServer svr(server_pem);
  14033. ASSERT_TRUE(svr.is_valid());
  14034. RejectsClientWithoutCert(svr);
  14035. }
  14036. // An empty CA fails to load instead of turning the check off
  14037. server_pem.client_ca_pem = "";
  14038. server_pem.client_ca_pem_len = 0;
  14039. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14040. }
  14041. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14042. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14043. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14044. true);
  14045. }
  14046. // A length shorter than the PEM cuts it short, so it no longer loads
  14047. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14048. std::string cert, key;
  14049. read_file(SERVER_CERT_FILE, cert);
  14050. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14051. for (auto cut_cert : {true, false}) {
  14052. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14053. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14054. SSLServer::PemMemory server_pem = {
  14055. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14056. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14057. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14058. key_len, nullptr};
  14059. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14060. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14061. key.c_str(), key_len, nullptr};
  14062. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14063. }
  14064. }
  14065. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14066. class NoListenSSLServer : public SSLServer {
  14067. public:
  14068. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14069. const char *client_ca_cert_file_path,
  14070. const char *client_ca_cert_dir_path = nullptr)
  14071. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14072. client_ca_cert_dir_path),
  14073. stop_(false) {}
  14074. std::atomic_bool stop_;
  14075. private:
  14076. bool process_and_close_socket(socket_t /*sock*/) override {
  14077. // Don't create SSL context
  14078. while (!stop_.load()) {
  14079. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14080. }
  14081. return true;
  14082. }
  14083. };
  14084. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14085. CLIENT_CA_CERT_FILE);
  14086. ASSERT_TRUE(svr.is_valid());
  14087. svr.Get("/test", [&](const Request &, Response &res) {
  14088. res.set_content("test", "text/plain");
  14089. });
  14090. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14091. auto se = detail::scope_exit([&] {
  14092. svr.stop_ = true;
  14093. svr.stop();
  14094. t.join();
  14095. ASSERT_FALSE(svr.is_running());
  14096. });
  14097. svr.wait_until_ready();
  14098. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14099. cli.enable_server_certificate_verification(false);
  14100. cli.set_connection_timeout(1);
  14101. auto res = cli.Get("/test");
  14102. ASSERT_TRUE(!res);
  14103. EXPECT_EQ(Error::SSLConnection, res.error());
  14104. // Timeout results in WantRead error code (maps to backend-specific value)
  14105. EXPECT_NE(0, res.ssl_error());
  14106. }
  14107. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14108. // Test SSLServer with client certificate verification using the standard
  14109. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14110. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14111. CLIENT_CA_CERT_DIR);
  14112. ASSERT_TRUE(svr.is_valid());
  14113. svr.Get("/test", [&](const Request &req, Response &res) {
  14114. res.set_content("test", "text/plain");
  14115. auto cert = req.peer_cert();
  14116. ASSERT_TRUE(static_cast<bool>(cert));
  14117. auto common_name = cert.subject_cn();
  14118. EXPECT_EQ("Common Name", common_name);
  14119. });
  14120. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14121. auto se = detail::scope_exit([&] {
  14122. svr.stop();
  14123. t.join();
  14124. ASSERT_FALSE(svr.is_running());
  14125. });
  14126. svr.wait_until_ready();
  14127. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14128. cli.enable_server_certificate_verification(false);
  14129. cli.set_connection_timeout(30);
  14130. auto res = cli.Get("/test");
  14131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14132. ASSERT_EQ(StatusCode::OK_200, res->status);
  14133. }
  14134. // Test verify_hostname on every backend: a host is named by a SAN only
  14135. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14136. using namespace httplib::tls;
  14137. // We need a running server to test against
  14138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14139. ASSERT_TRUE(svr.is_valid());
  14140. svr.Get("/test", [](const Request &, Response &res) {
  14141. res.set_content("ok", "text/plain");
  14142. });
  14143. thread t([&]() { svr.listen(HOST, PORT); });
  14144. auto se = detail::scope_exit([&] {
  14145. svr.stop();
  14146. t.join();
  14147. });
  14148. svr.wait_until_ready();
  14149. bool verify_callback_called = false;
  14150. bool verify_result_wrong = false;
  14151. SSLClient cli(HOST, PORT);
  14152. cli.enable_server_certificate_verification(true);
  14153. cli.set_ca_cert_path(CA_CERT_FILE);
  14154. cli.set_connection_timeout(5);
  14155. // Note: Test certificate has CN="Common Name", not "localhost"
  14156. bool verify_result_cn = false;
  14157. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14158. verify_callback_called = true;
  14159. if (!ctx.cert) return false;
  14160. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14161. verify_result_cn = ctx.check_hostname("Common Name");
  14162. // Test 2: wrong hostname should not match
  14163. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14164. return true; // Accept for the purpose of this test
  14165. });
  14166. auto res = cli.Get("/test");
  14167. // The request may succeed or fail depending on cert configuration
  14168. // but the callback should have been called
  14169. ASSERT_TRUE(verify_callback_called)
  14170. << "Verify callback should have been called";
  14171. EXPECT_FALSE(verify_result_cn)
  14172. << "verify_hostname must not match the certificate CN (no SAN)";
  14173. // Wrong hostname should not match
  14174. EXPECT_FALSE(verify_result_wrong)
  14175. << "verify_hostname should not match 'wronghost.example.com'";
  14176. }
  14177. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14178. // backend verifies it.
  14179. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14180. // Certificate CN is "localhost" and it carries no SAN.
  14181. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14182. ASSERT_TRUE(svr.is_valid());
  14183. svr.Get("/test", [](const Request &, Response &res) {
  14184. res.set_content("ok", "text/plain");
  14185. });
  14186. auto port = svr.bind_to_any_port(HOST);
  14187. thread t([&]() { svr.listen_after_bind(); });
  14188. auto se = detail::scope_exit([&] {
  14189. svr.stop();
  14190. t.join();
  14191. });
  14192. svr.wait_until_ready();
  14193. SSLClient cli("localhost", port);
  14194. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14195. cli.enable_server_certificate_verification(true);
  14196. cli.set_connection_timeout(5);
  14197. auto res = cli.Get("/test");
  14198. ASSERT_FALSE(res);
  14199. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14200. // The same certificate is accepted once host name verification is off, so the
  14201. // failure above is the host name and not the chain.
  14202. cli.enable_server_hostname_verification(false);
  14203. res = cli.Get("/test");
  14204. ASSERT_TRUE(res) << to_string(res.error());
  14205. EXPECT_EQ(StatusCode::OK_200, res->status);
  14206. }
  14207. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14208. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14209. // X509_check_ip behavior and must hold for every backend.
  14210. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14211. using namespace httplib::tls;
  14212. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14213. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14214. ASSERT_TRUE(svr.is_valid());
  14215. svr.Get("/test", [](const Request &, Response &res) {
  14216. res.set_content("ok", "text/plain");
  14217. });
  14218. thread t([&]() { svr.listen(HOST, PORT); });
  14219. auto se = detail::scope_exit([&] {
  14220. svr.stop();
  14221. t.join();
  14222. });
  14223. svr.wait_until_ready();
  14224. bool verify_callback_called = false;
  14225. bool ip_matched_via_cn = true;
  14226. SSLClient cli(HOST, PORT);
  14227. cli.enable_server_certificate_verification(true);
  14228. cli.set_ca_cert_path(CA_CERT_FILE);
  14229. cli.set_connection_timeout(5);
  14230. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14231. verify_callback_called = true;
  14232. if (!ctx.cert) return false;
  14233. // The IP appears only in the CN, so it must NOT be accepted.
  14234. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14235. return true; // Accept for the purpose of this test
  14236. });
  14237. cli.Get("/test");
  14238. ASSERT_TRUE(verify_callback_called)
  14239. << "Verify callback should have been called";
  14240. EXPECT_FALSE(ip_matched_via_cn)
  14241. << "An IP host must not be authenticated via the certificate CN";
  14242. }
  14243. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14244. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14245. using namespace httplib::tls;
  14246. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14247. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14248. ASSERT_TRUE(svr.is_valid());
  14249. svr.Get("/test", [](const Request &, Response &res) {
  14250. res.set_content("ok", "text/plain");
  14251. });
  14252. thread t([&]() { svr.listen(HOST, PORT); });
  14253. auto se = detail::scope_exit([&] {
  14254. svr.stop();
  14255. t.join();
  14256. });
  14257. svr.wait_until_ready();
  14258. bool verify_callback_called = false;
  14259. bool san_matched = false;
  14260. bool wrong_ipv6_matched = true;
  14261. bool cn_ipv6_matched = true;
  14262. SSLClient cli(HOST, PORT);
  14263. cli.enable_server_certificate_verification(true);
  14264. cli.set_ca_cert_path(CA_CERT_FILE);
  14265. cli.set_connection_timeout(5);
  14266. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14267. verify_callback_called = true;
  14268. if (!ctx.cert) return false;
  14269. // Matches the IPv6 iPAddress SAN.
  14270. san_matched = ctx.check_hostname("2001:db8::1");
  14271. // A different IPv6 address must not match.
  14272. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14273. // "::1" lives only in the CN, so it must not be accepted.
  14274. cn_ipv6_matched = ctx.check_hostname("::1");
  14275. return true; // Accept for the purpose of this test
  14276. });
  14277. cli.Get("/test");
  14278. ASSERT_TRUE(verify_callback_called)
  14279. << "Verify callback should have been called";
  14280. EXPECT_TRUE(san_matched)
  14281. << "verify_hostname should match an IPv6 iPAddress SAN";
  14282. EXPECT_FALSE(wrong_ipv6_matched)
  14283. << "verify_hostname should not match a non-matching IPv6 address";
  14284. EXPECT_FALSE(cn_ipv6_matched)
  14285. << "An IPv6 host must not be authenticated via the certificate CN";
  14286. }
  14287. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14288. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14289. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14290. using namespace httplib::tls;
  14291. // SANs: DNS:a.zz, IP:42.46.122.122
  14292. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14293. ASSERT_TRUE(svr.is_valid());
  14294. svr.Get("/test", [](const Request &, Response &res) {
  14295. res.set_content("ok", "text/plain");
  14296. });
  14297. auto port = svr.bind_to_any_port(HOST);
  14298. thread t([&]() { svr.listen_after_bind(); });
  14299. auto se = detail::scope_exit([&] {
  14300. svr.stop();
  14301. t.join();
  14302. });
  14303. svr.wait_until_ready();
  14304. bool verify_callback_called = false;
  14305. bool dns_san_matched = false;
  14306. bool ip_san_matched = false;
  14307. bool ip_matched_via_dns_san = true;
  14308. bool dns_matched_via_ip_san = true;
  14309. bool cn_matched_next_to_dns_san = true;
  14310. SSLClient cli(HOST, port);
  14311. cli.enable_server_certificate_verification(true);
  14312. cli.set_ca_cert_path(CA_CERT_FILE);
  14313. cli.set_connection_timeout(5);
  14314. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14315. verify_callback_called = true;
  14316. if (!ctx.cert) return false;
  14317. dns_san_matched = ctx.check_hostname("a.zz");
  14318. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14319. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14320. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14321. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14322. return true; // Accept for the purpose of this test
  14323. });
  14324. cli.Get("/test");
  14325. ASSERT_TRUE(verify_callback_called)
  14326. << "Verify callback should have been called";
  14327. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14328. EXPECT_TRUE(ip_san_matched)
  14329. << "verify_hostname should match an iPAddress SAN";
  14330. EXPECT_FALSE(ip_matched_via_dns_san)
  14331. << "An IP host must not be authenticated via a dNSName SAN";
  14332. EXPECT_FALSE(dns_matched_via_ip_san)
  14333. << "A DNS host must not be authenticated via an iPAddress SAN";
  14334. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14335. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14336. }
  14337. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14338. // "www.*.example.test" names one host and not every host under example.test.
  14339. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14340. using namespace httplib::tls;
  14341. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14342. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14343. ASSERT_TRUE(svr.is_valid());
  14344. svr.Get("/test", [](const Request &, Response &res) {
  14345. res.set_content("ok", "text/plain");
  14346. });
  14347. auto port = svr.bind_to_any_port(HOST);
  14348. thread t([&]() { svr.listen_after_bind(); });
  14349. auto se = detail::scope_exit([&] {
  14350. svr.stop();
  14351. t.join();
  14352. });
  14353. svr.wait_until_ready();
  14354. bool verify_callback_called = false;
  14355. bool leftmost_wildcard_matched = false;
  14356. bool wildcard_spanned_labels = true;
  14357. bool inner_wildcard_matched = true;
  14358. SSLClient cli(HOST, port);
  14359. cli.enable_server_certificate_verification(true);
  14360. cli.set_ca_cert_path(CA_CERT_FILE);
  14361. cli.set_connection_timeout(5);
  14362. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14363. verify_callback_called = true;
  14364. if (!ctx.cert) return false;
  14365. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14366. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14367. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14368. return true; // Accept for the purpose of this test
  14369. });
  14370. cli.Get("/test");
  14371. ASSERT_TRUE(verify_callback_called)
  14372. << "Verify callback should have been called";
  14373. EXPECT_TRUE(leftmost_wildcard_matched)
  14374. << "A leftmost wildcard should match a single label";
  14375. EXPECT_FALSE(wildcard_spanned_labels)
  14376. << "A wildcard label must not match more than one label";
  14377. EXPECT_FALSE(inner_wildcard_matched)
  14378. << "A wildcard outside the leftmost label must not be honoured";
  14379. }
  14380. // sans() must report each SAN entry under its own type.
  14381. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14382. using namespace httplib::tls;
  14383. // SANs: DNS:a.zz, IP:42.46.122.122
  14384. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14385. ASSERT_TRUE(svr.is_valid());
  14386. svr.Get("/test", [](const Request &, Response &res) {
  14387. res.set_content("ok", "text/plain");
  14388. });
  14389. auto port = svr.bind_to_any_port(HOST);
  14390. thread t([&]() { svr.listen_after_bind(); });
  14391. auto se = detail::scope_exit([&] {
  14392. svr.stop();
  14393. t.join();
  14394. });
  14395. svr.wait_until_ready();
  14396. bool verify_callback_called = false;
  14397. std::vector<SanEntry> sans;
  14398. SSLClient cli(HOST, port);
  14399. cli.enable_server_certificate_verification(true);
  14400. cli.set_ca_cert_path(CA_CERT_FILE);
  14401. cli.set_connection_timeout(5);
  14402. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14403. verify_callback_called = true;
  14404. if (!ctx.cert) return false;
  14405. sans = ctx.sans();
  14406. return true; // Accept for the purpose of this test
  14407. });
  14408. cli.Get("/test");
  14409. ASSERT_TRUE(verify_callback_called)
  14410. << "Verify callback should have been called";
  14411. auto has_san = [&](SanType type, const std::string &value) {
  14412. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14413. return san.type == type && san.value == value;
  14414. });
  14415. };
  14416. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14417. << "sans() should report the dNSName SAN";
  14418. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14419. << "sans() should report the iPAddress SAN";
  14420. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14421. << "sans() must not report the dNSName SAN as an address";
  14422. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14423. << "sans() must not report the iPAddress SAN as a DNS name";
  14424. }
  14425. #endif
  14426. // mbedTLS-specific callback constructor test
  14427. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14428. #ifdef CPPHTTPLIB_SSL_ENABLED
  14429. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14431. ASSERT_TRUE(svr.is_valid());
  14432. // Set up a handler to verify client certificate is present
  14433. bool client_cert_verified = false;
  14434. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14435. // Verify that client certificate was provided
  14436. client_cert_verified = true;
  14437. res.set_content("success", "text/plain");
  14438. });
  14439. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14440. auto se = detail::scope_exit([&] {
  14441. svr.stop();
  14442. t.join();
  14443. ASSERT_FALSE(svr.is_running());
  14444. });
  14445. svr.wait_until_ready();
  14446. // Client with certificate
  14447. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14448. cli.enable_server_certificate_verification(false);
  14449. cli.set_connection_timeout(30);
  14450. auto res = cli.Get("/test");
  14451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14452. ASSERT_EQ(StatusCode::OK_200, res->status);
  14453. ASSERT_TRUE(client_cert_verified);
  14454. EXPECT_EQ("success", res->body);
  14455. }
  14456. #endif
  14457. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14458. // backends
  14459. #ifdef CPPHTTPLIB_SSL_ENABLED
  14460. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14461. using namespace httplib::tls;
  14462. // Test that when client CA cert file is provided,
  14463. // the server properly requests and validates client certificates
  14464. // Create a server with client authentication
  14465. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14466. ASSERT_TRUE(svr.is_valid());
  14467. bool handler_called = false;
  14468. svr.Get("/test", [&](const Request &req, Response &res) {
  14469. handler_called = true;
  14470. // Verify that a client certificate was provided
  14471. auto cert = req.peer_cert();
  14472. ASSERT_TRUE(static_cast<bool>(cert));
  14473. // Get the issuer name
  14474. std::string issuer_str = cert.issuer_name();
  14475. ASSERT_FALSE(issuer_str.empty());
  14476. // The client certificate should be issued by our test CA
  14477. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14478. res.set_content("authenticated", "text/plain");
  14479. });
  14480. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14481. auto se = detail::scope_exit([&] {
  14482. svr.stop();
  14483. t.join();
  14484. ASSERT_FALSE(svr.is_running());
  14485. });
  14486. svr.wait_until_ready();
  14487. // Connect with a client certificate issued by the CA
  14488. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14489. cli.enable_server_certificate_verification(false);
  14490. cli.set_connection_timeout(30);
  14491. auto res = cli.Get("/test");
  14492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14493. ASSERT_EQ(StatusCode::OK_200, res->status);
  14494. ASSERT_TRUE(handler_called);
  14495. EXPECT_EQ("authenticated", res->body);
  14496. }
  14497. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14498. using namespace httplib::tls;
  14499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14500. ASSERT_TRUE(svr.is_valid());
  14501. svr.Get("/test", [](const Request &, Response &res) {
  14502. res.set_content("ok", "text/plain");
  14503. });
  14504. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14505. auto se = detail::scope_exit([&] {
  14506. svr.stop();
  14507. t.join();
  14508. });
  14509. svr.wait_until_ready();
  14510. SSLClient cli(HOST, PORT);
  14511. cli.enable_server_certificate_verification(false);
  14512. cli.set_connection_timeout(30);
  14513. bool cert_checked = false;
  14514. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14515. if (ctx.cert) {
  14516. auto sans = ctx.sans();
  14517. // Test certificate may or may not have SANs - just verify the API
  14518. // works If SANs exist, verify the types are valid
  14519. for (const auto &san : sans) {
  14520. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14521. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14522. san.type == SanType::OTHER);
  14523. EXPECT_FALSE(san.value.empty());
  14524. }
  14525. cert_checked = true;
  14526. }
  14527. return true;
  14528. });
  14529. auto res = cli.Get("/test");
  14530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14531. EXPECT_TRUE(cert_checked);
  14532. }
  14533. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14534. using namespace httplib::tls;
  14535. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14536. ASSERT_TRUE(svr.is_valid());
  14537. svr.Get("/test", [](const Request &, Response &res) {
  14538. res.set_content("ok", "text/plain");
  14539. });
  14540. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14541. auto se = detail::scope_exit([&] {
  14542. svr.stop();
  14543. t.join();
  14544. });
  14545. svr.wait_until_ready();
  14546. SSLClient cli(HOST, PORT);
  14547. cli.enable_server_certificate_verification(false);
  14548. cli.set_connection_timeout(30);
  14549. bool validity_checked = false;
  14550. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14551. if (ctx.cert) {
  14552. time_t not_before = 0, not_after = 0;
  14553. bool result = ctx.validity(not_before, not_after);
  14554. EXPECT_TRUE(result);
  14555. // Verify that not_before < now < not_after for a valid cert
  14556. time_t now = time(nullptr);
  14557. EXPECT_LT(not_before, now);
  14558. EXPECT_GT(not_after, now);
  14559. validity_checked = true;
  14560. }
  14561. return true;
  14562. });
  14563. auto res = cli.Get("/test");
  14564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14565. EXPECT_TRUE(validity_checked);
  14566. }
  14567. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14568. using namespace httplib::tls;
  14569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14570. ASSERT_TRUE(svr.is_valid());
  14571. svr.Get("/test", [](const Request &, Response &res) {
  14572. res.set_content("ok", "text/plain");
  14573. });
  14574. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14575. auto se = detail::scope_exit([&] {
  14576. svr.stop();
  14577. t.join();
  14578. });
  14579. svr.wait_until_ready();
  14580. SSLClient cli(HOST, PORT);
  14581. cli.enable_server_certificate_verification(false);
  14582. cli.set_connection_timeout(30);
  14583. bool serial_checked = false;
  14584. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14585. if (ctx.cert) {
  14586. std::string serial = ctx.serial();
  14587. EXPECT_FALSE(serial.empty());
  14588. // Serial should be a hex string
  14589. for (char c : serial) {
  14590. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14591. (c >= 'a' && c <= 'f'));
  14592. }
  14593. serial_checked = true;
  14594. }
  14595. return true;
  14596. });
  14597. auto res = cli.Get("/test");
  14598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14599. EXPECT_TRUE(serial_checked);
  14600. }
  14601. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14602. // Test 1: Valid CA file - no error should be recorded
  14603. {
  14604. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14605. CLIENT_CA_CERT_FILE);
  14606. ASSERT_TRUE(svr.is_valid());
  14607. // With valid setup, last_ssl_error should be 0
  14608. EXPECT_EQ(0, svr.ssl_last_error());
  14609. }
  14610. // Test 2: Invalid CA file content
  14611. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14612. {
  14613. // Create a temporary file with completely invalid content
  14614. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14615. {
  14616. std::ofstream ofs(temp_invalid_ca);
  14617. ofs << "This is not a certificate file at all\n";
  14618. ofs << "Just plain text content\n";
  14619. }
  14620. // Create server with invalid CA file
  14621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14622. // Clean up temporary file
  14623. std::remove(temp_invalid_ca);
  14624. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14625. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14626. // Note: SSL_CTX_load_verify_locations typically fails first,
  14627. // but our error handling code path is still exercised
  14628. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14629. }
  14630. }
  14631. TEST(VerifyCallbackTest, VerifyContextFields) {
  14632. using namespace httplib::tls;
  14633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14634. ASSERT_TRUE(svr.is_valid());
  14635. svr.Get("/test", [](const Request &, Response &res) {
  14636. res.set_content("ok", "text/plain");
  14637. });
  14638. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14639. auto se = detail::scope_exit([&] {
  14640. svr.stop();
  14641. t.join();
  14642. });
  14643. svr.wait_until_ready();
  14644. SSLClient cli(HOST, PORT);
  14645. cli.enable_server_certificate_verification(false);
  14646. cli.set_connection_timeout(30);
  14647. int callback_count = 0;
  14648. bool saw_leaf_cert = false;
  14649. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14650. if (ctx.cert) {
  14651. callback_count++;
  14652. // We should see at least one certificate (the leaf)
  14653. std::string cn = ctx.subject_cn();
  14654. if (!cn.empty()) { saw_leaf_cert = true; }
  14655. // Verify context fields are populated
  14656. EXPECT_NE(ctx.session, nullptr);
  14657. EXPECT_GE(ctx.depth, 0);
  14658. }
  14659. return true;
  14660. });
  14661. auto res = cli.Get("/test");
  14662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14663. EXPECT_GT(callback_count, 0);
  14664. EXPECT_TRUE(saw_leaf_cert);
  14665. }
  14666. // A verifier that accepts runs alongside the built-in verification, and is the
  14667. // only check once that is turned off.
  14668. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14669. using namespace httplib::tls;
  14670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14671. ASSERT_TRUE(svr.is_valid());
  14672. svr.Get("/test", [](const Request &, Response &res) {
  14673. res.set_content("ok", "text/plain");
  14674. });
  14675. auto port = svr.bind_to_any_port(HOST);
  14676. thread t([&]() { svr.listen_after_bind(); });
  14677. auto se = detail::scope_exit([&] {
  14678. svr.stop();
  14679. t.join();
  14680. });
  14681. svr.wait_until_ready();
  14682. SSLClient cli(HOST, port);
  14683. cli.enable_server_hostname_verification(false);
  14684. auto calls = 0;
  14685. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14686. calls++;
  14687. return true;
  14688. });
  14689. // cert.pem is not trusted
  14690. auto res = cli.Get("/test");
  14691. ASSERT_FALSE(res);
  14692. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14693. EXPECT_GT(calls, 0);
  14694. cli.enable_server_certificate_verification(false);
  14695. res = cli.Get("/test");
  14696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14697. EXPECT_EQ("ok", res->body);
  14698. }
  14699. // A verifier belongs to the client that set it, not to the thread that set it.
  14700. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14701. using namespace httplib::tls;
  14702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14703. ASSERT_TRUE(svr.is_valid());
  14704. svr.Get("/test", [](const Request &, Response &res) {
  14705. res.set_content("ok", "text/plain");
  14706. });
  14707. auto port = svr.bind_to_any_port(HOST);
  14708. thread t([&]() { svr.listen_after_bind(); });
  14709. auto se = detail::scope_exit([&] {
  14710. svr.stop();
  14711. t.join();
  14712. });
  14713. svr.wait_until_ready();
  14714. auto rejecting_calls = 0;
  14715. SSLClient rejecting(HOST, port);
  14716. rejecting.enable_server_certificate_verification(false);
  14717. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14718. rejecting_calls++;
  14719. return false;
  14720. });
  14721. auto accepting_calls = 0;
  14722. SSLClient accepting(HOST, port);
  14723. accepting.enable_server_certificate_verification(false);
  14724. // Set on another thread than the requests below.
  14725. thread([&]() {
  14726. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14727. accepting_calls++;
  14728. return true;
  14729. });
  14730. }).join();
  14731. // Requested on another thread than the verifier was set on.
  14732. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14733. EXPECT_GT(rejecting_calls, 0);
  14734. auto res = accepting.Get("/test");
  14735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14736. EXPECT_GT(accepting_calls, 0);
  14737. }
  14738. // A verifier replaced while a handshake runs it lives until it returns.
  14739. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14740. using namespace httplib::tls;
  14741. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14742. ASSERT_TRUE(svr.is_valid());
  14743. svr.Get("/test", [](const Request &, Response &res) {
  14744. res.set_content("ok", "text/plain");
  14745. });
  14746. auto port = svr.bind_to_any_port(HOST);
  14747. thread t([&]() { svr.listen_after_bind(); });
  14748. auto se = detail::scope_exit([&] {
  14749. svr.stop();
  14750. t.join();
  14751. });
  14752. svr.wait_until_ready();
  14753. SSLClient cli(HOST, port);
  14754. cli.enable_server_certificate_verification(false);
  14755. std::promise<void> entered;
  14756. std::promise<void> replaced;
  14757. auto replaced_future = replaced.get_future();
  14758. auto first_call = true;
  14759. // Long enough to live on the heap
  14760. std::string expected(64, 'v');
  14761. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14762. if (first_call) {
  14763. first_call = false;
  14764. entered.set_value();
  14765. replaced_future.wait();
  14766. }
  14767. return expected == std::string(64, 'v');
  14768. });
  14769. thread request([&]() {
  14770. auto res = cli.Get("/test");
  14771. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14772. });
  14773. entered.get_future().wait();
  14774. cli.set_server_certificate_verifier(
  14775. [](const VerifyContext &) { return true; });
  14776. replaced.set_value();
  14777. request.join();
  14778. }
  14779. // VerifyContext::session is the same handle the other tls:: functions take.
  14780. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14781. using namespace httplib::tls;
  14782. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14783. ASSERT_TRUE(svr.is_valid());
  14784. svr.Get("/test", [](const Request &, Response &res) {
  14785. res.set_content("ok", "text/plain");
  14786. });
  14787. auto port = svr.bind_to_any_port(HOST);
  14788. thread t([&]() { svr.listen_after_bind(); });
  14789. auto se = detail::scope_exit([&] {
  14790. svr.stop();
  14791. t.join();
  14792. });
  14793. svr.wait_until_ready();
  14794. SSLClient cli(HOST, port);
  14795. cli.enable_server_certificate_verification(false);
  14796. session_t verifier_session = nullptr;
  14797. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14798. verifier_session = ctx.session;
  14799. return true;
  14800. });
  14801. session_t session_verifier_session = nullptr;
  14802. cli.set_session_verifier([&](session_t session) {
  14803. session_verifier_session = session;
  14804. return SSLVerifierResponse::NoDecisionMade;
  14805. });
  14806. auto res = cli.Get("/test");
  14807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14808. EXPECT_NE(nullptr, verifier_session);
  14809. EXPECT_EQ(session_verifier_session, verifier_session);
  14810. }
  14811. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14812. using httplib::tls::TlsError;
  14813. // Test that verify_error_to_string returns empty for success
  14814. std::string success_str = TlsError::verify_error_to_string(0);
  14815. EXPECT_TRUE(success_str.empty());
  14816. // Test that verify_error_to_string returns non-empty for error codes
  14817. // Using a common error code (certificate expired)
  14818. std::string error_str =
  14819. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14820. EXPECT_FALSE(error_str.empty());
  14821. }
  14822. TEST(SessionVerifierTest, CertificateAccepted) {
  14823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14824. ASSERT_TRUE(svr.is_valid());
  14825. svr.Get("/test", [](const Request &, Response &res) {
  14826. res.set_content("ok", "text/plain");
  14827. });
  14828. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14829. auto se = detail::scope_exit([&] {
  14830. svr.stop();
  14831. t.join();
  14832. });
  14833. svr.wait_until_ready();
  14834. SSLClient cli(HOST, PORT);
  14835. cli.enable_server_certificate_verification(false);
  14836. cli.set_connection_timeout(30);
  14837. bool callback_called = false;
  14838. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14839. EXPECT_NE(session, nullptr);
  14840. callback_called = true;
  14841. return SSLVerifierResponse::CertificateAccepted;
  14842. });
  14843. auto res = cli.Get("/test");
  14844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14845. EXPECT_EQ(200, res->status);
  14846. EXPECT_TRUE(callback_called);
  14847. }
  14848. TEST(SessionVerifierTest, CertificateRejected) {
  14849. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14850. ASSERT_TRUE(svr.is_valid());
  14851. svr.Get("/test", [](const Request &, Response &res) {
  14852. res.set_content("ok", "text/plain");
  14853. });
  14854. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14855. auto se = detail::scope_exit([&] {
  14856. svr.stop();
  14857. t.join();
  14858. });
  14859. svr.wait_until_ready();
  14860. SSLClient cli(HOST, PORT);
  14861. cli.enable_server_certificate_verification(false);
  14862. cli.set_connection_timeout(30);
  14863. bool callback_called = false;
  14864. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14865. EXPECT_NE(session, nullptr);
  14866. callback_called = true;
  14867. return SSLVerifierResponse::CertificateRejected;
  14868. });
  14869. auto res = cli.Get("/test");
  14870. EXPECT_FALSE(res);
  14871. EXPECT_TRUE(callback_called);
  14872. }
  14873. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14874. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14875. ASSERT_TRUE(svr.is_valid());
  14876. svr.Get("/test", [](const Request &, Response &res) {
  14877. res.set_content("ok", "text/plain");
  14878. });
  14879. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14880. auto se = detail::scope_exit([&] {
  14881. svr.stop();
  14882. t.join();
  14883. });
  14884. svr.wait_until_ready();
  14885. // NoDecisionMade with verification disabled should succeed (no default check)
  14886. SSLClient cli(HOST, PORT);
  14887. cli.enable_server_certificate_verification(false);
  14888. cli.set_connection_timeout(30);
  14889. bool callback_called = false;
  14890. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14891. EXPECT_NE(session, nullptr);
  14892. callback_called = true;
  14893. return SSLVerifierResponse::NoDecisionMade;
  14894. });
  14895. auto res = cli.Get("/test");
  14896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14897. EXPECT_EQ(200, res->status);
  14898. EXPECT_TRUE(callback_called);
  14899. }
  14900. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14902. ASSERT_TRUE(svr.is_valid());
  14903. svr.Get("/test", [](const Request &, Response &res) {
  14904. res.set_content("ok", "text/plain");
  14905. });
  14906. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14907. auto se = detail::scope_exit([&] {
  14908. svr.stop();
  14909. t.join();
  14910. });
  14911. svr.wait_until_ready();
  14912. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14913. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14914. // so we only check that the request fails, not whether the callback was
  14915. // called.
  14916. SSLClient cli(HOST, PORT);
  14917. cli.enable_server_certificate_verification(true);
  14918. cli.set_connection_timeout(30);
  14919. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14920. EXPECT_NE(session, nullptr);
  14921. return SSLVerifierResponse::NoDecisionMade;
  14922. });
  14923. auto res = cli.Get("/test");
  14924. EXPECT_FALSE(res);
  14925. }
  14926. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14927. // Test SSL server using PemMemory constructor with client CA certificates
  14928. // Read PEM files
  14929. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14930. read_file(SERVER_CERT_FILE, server_cert_pem);
  14931. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14932. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14933. // Create SSLServer with PemMemory constructor including client CA
  14934. SSLServer::PemMemory server_pem = {
  14935. server_cert_pem.c_str(),
  14936. server_cert_pem.size(),
  14937. server_key_pem.c_str(),
  14938. server_key_pem.size(),
  14939. client_ca_pem.c_str(),
  14940. client_ca_pem.size(),
  14941. nullptr // no password for server key
  14942. };
  14943. SSLServer svr(server_pem);
  14944. ASSERT_TRUE(svr.is_valid());
  14945. // No SSL error should be recorded for valid setup
  14946. EXPECT_EQ(0, svr.ssl_last_error());
  14947. // Set up server endpoints
  14948. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14949. res.set_content("ok", "text/plain");
  14950. });
  14951. // Start server in a thread
  14952. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14953. svr.wait_until_ready();
  14954. // Connect with client certificate (using constructor with paths)
  14955. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14956. cli.enable_server_certificate_verification(false);
  14957. auto res = cli.Get("/test-pem-ca");
  14958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14959. EXPECT_EQ(200, res->status);
  14960. EXPECT_EQ("ok", res->body);
  14961. svr.stop();
  14962. server_thread.join();
  14963. }
  14964. #endif
  14965. #ifdef _WIN32
  14966. TEST(CleanupTest, WSACleanup) {
  14967. int ret = WSACleanup();
  14968. ASSERT_EQ(0, ret);
  14969. }
  14970. #endif
  14971. #ifndef CPPHTTPLIB_SSL_ENABLED
  14972. TEST(NoSSLSupport, SimpleInterface) {
  14973. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14974. }
  14975. #endif
  14976. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14977. TEST(InvalidScheme, SimpleInterface) {
  14978. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14979. }
  14980. #endif
  14981. TEST(NoScheme, SimpleInterface) {
  14982. Client cli("yahoo.com:80");
  14983. ASSERT_TRUE(cli.is_valid());
  14984. }
  14985. TEST(SendAPI, SimpleInterface_Online) {
  14986. Client cli("http://yahoo.com");
  14987. Request req;
  14988. req.method = "GET";
  14989. req.path = "/";
  14990. auto res = cli.send(req);
  14991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14992. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14993. }
  14994. TEST(SendAPI, WithParamsInRequest) {
  14995. Server svr;
  14996. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14997. EXPECT_TRUE(req.has_param("test"));
  14998. EXPECT_EQ("test_value", req.get_param_value("test"));
  14999. });
  15000. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15001. auto se = detail::scope_exit([&] {
  15002. svr.stop();
  15003. t.join();
  15004. ASSERT_FALSE(svr.is_running());
  15005. });
  15006. svr.wait_until_ready();
  15007. Client cli(HOST, PORT);
  15008. {
  15009. Request req;
  15010. req.method = "GET";
  15011. req.path = "/";
  15012. req.params.emplace("test", "test_value");
  15013. auto res = cli.send(req);
  15014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15015. }
  15016. {
  15017. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15019. }
  15020. }
  15021. TEST(ClientImplMethods, GetSocketTest) {
  15022. httplib::Server svr;
  15023. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15024. res.status = StatusCode::OK_200;
  15025. });
  15026. auto port = svr.bind_to_any_port("127.0.0.1");
  15027. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15028. auto se = detail::scope_exit([&] {
  15029. svr.stop();
  15030. thread.join();
  15031. ASSERT_FALSE(svr.is_running());
  15032. });
  15033. svr.wait_until_ready();
  15034. {
  15035. httplib::Client cli("127.0.0.1", port);
  15036. cli.set_keep_alive(true);
  15037. // Use the behavior of cpp-httplib of opening the connection
  15038. // only when the first request happens. If that changes,
  15039. // this test would be obsolete.
  15040. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15041. // This also implicitly tests the server. But other tests would fail much
  15042. // earlier than this one to be considered.
  15043. auto res = cli.Get("/");
  15044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15045. EXPECT_EQ(StatusCode::OK_200, res->status);
  15046. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15047. }
  15048. }
  15049. #ifdef CPPHTTPLIB_SSL_ENABLED
  15050. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15051. Client cli("http://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, SimpleInterface_Online) {
  15062. Client cli("https://yahoo.com");
  15063. auto res = cli.Get("/");
  15064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15065. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15066. cli.set_follow_location(true);
  15067. res = cli.Get("/");
  15068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15069. EXPECT_EQ(StatusCode::OK_200, res->status);
  15070. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15071. }
  15072. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15073. Client cli("https://yahoo.com");
  15074. auto res = cli.Get("/");
  15075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15076. ASSERT_FALSE(!res);
  15077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15078. ASSERT_FALSE(res == nullptr);
  15079. ASSERT_TRUE(res != nullptr);
  15080. EXPECT_EQ(Error::Success, res.error());
  15081. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15082. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15083. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15084. cli.set_follow_location(true);
  15085. res = cli.Get("/");
  15086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15087. EXPECT_EQ(Error::Success, res.error());
  15088. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15089. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15090. EXPECT_EQ(StatusCode::OK_200, res->status);
  15091. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15092. }
  15093. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15094. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15095. Client cli("https://cdnjs.cloudflare.com");
  15096. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15097. Headers{{"Accept-Encoding", "br"}});
  15098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15099. EXPECT_EQ(StatusCode::OK_200, res->status);
  15100. EXPECT_EQ(287630U, res->body.size());
  15101. EXPECT_EQ("application/javascript; charset=utf-8",
  15102. res->get_header_value("Content-Type"));
  15103. }
  15104. #endif
  15105. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15106. #undef REDIR_HOST // Silence compiler warning
  15107. #define REDIR_HOST "https://httpbingo.org"
  15108. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15109. Client cli(REDIR_HOST);
  15110. cli.set_follow_location(true);
  15111. auto res =
  15112. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15114. EXPECT_EQ(StatusCode::OK_200, res->status);
  15115. }
  15116. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15117. Client cli(REDIR_HOST);
  15118. cli.set_follow_location(true);
  15119. Params params;
  15120. params.emplace("url", "http://example.com");
  15121. params.emplace("status_code", "302");
  15122. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15124. EXPECT_EQ(StatusCode::OK_200, res->status);
  15125. }
  15126. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15127. Client cli(REDIR_HOST);
  15128. cli.set_follow_location(true);
  15129. Params params;
  15130. params.emplace("url", "http://example.com");
  15131. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15133. EXPECT_EQ(StatusCode::OK_200, res->status);
  15134. }
  15135. TEST(HttpToHttpsRedirectTest, CertFile) {
  15136. auto ssl_port = PORT + 1;
  15137. Server svr;
  15138. ASSERT_TRUE(svr.is_valid());
  15139. svr.Get("/index", [&](const Request &, Response &res) {
  15140. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15141. "/index");
  15142. svr.stop();
  15143. });
  15144. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15145. ASSERT_TRUE(ssl_svr.is_valid());
  15146. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15147. res.set_content("test", "text/plain");
  15148. ssl_svr.stop();
  15149. });
  15150. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15151. thread t2 =
  15152. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15153. auto se = detail::scope_exit([&] {
  15154. t2.join();
  15155. t.join();
  15156. ASSERT_FALSE(svr.is_running());
  15157. });
  15158. svr.wait_until_ready();
  15159. ssl_svr.wait_until_ready();
  15160. Client cli("127.0.0.1", PORT);
  15161. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15162. cli.enable_server_certificate_verification(true);
  15163. cli.set_follow_location(true);
  15164. cli.set_connection_timeout(30);
  15165. auto res = cli.Get("/index");
  15166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15167. ASSERT_EQ(StatusCode::OK_200, res->status);
  15168. }
  15169. TEST(SSLClientRedirectTest, CertFile) {
  15170. auto ssl_port = PORT + 1;
  15171. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15172. ASSERT_TRUE(ssl_svr1.is_valid());
  15173. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15174. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15175. "/index");
  15176. ssl_svr1.stop();
  15177. });
  15178. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15179. ASSERT_TRUE(ssl_svr2.is_valid());
  15180. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15181. res.set_content("test", "text/plain");
  15182. ssl_svr2.stop();
  15183. });
  15184. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15185. thread t2 =
  15186. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15187. auto se = detail::scope_exit([&] {
  15188. t2.join();
  15189. t.join();
  15190. ASSERT_FALSE(ssl_svr1.is_running());
  15191. });
  15192. ssl_svr1.wait_until_ready();
  15193. ssl_svr2.wait_until_ready();
  15194. SSLClient cli("127.0.0.1", PORT);
  15195. std::string cert;
  15196. read_file(SERVER_CERT2_FILE, cert);
  15197. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15198. cli.enable_server_certificate_verification(true);
  15199. cli.set_follow_location(true);
  15200. cli.set_connection_timeout(30);
  15201. auto res = cli.Get("/index");
  15202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15203. ASSERT_EQ(StatusCode::OK_200, res->status);
  15204. }
  15205. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15206. // another port, so the client follows it with a new client.
  15207. static Result GetThroughTlsRedirectToDifferentPort(
  15208. const std::function<void(SSLClient &)> &setup,
  15209. const char *target_cert = SERVER_CERT2_FILE,
  15210. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15211. auto ssl_port = PORT + 1;
  15212. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15213. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15214. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15215. "/index");
  15216. });
  15217. SSLServer ssl_svr2(target_cert, target_key);
  15218. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15219. res.set_content("test", "text/plain");
  15220. });
  15221. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15222. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15223. auto se = detail::scope_exit([&] {
  15224. ssl_svr2.stop();
  15225. ssl_svr1.stop();
  15226. t2.join();
  15227. t.join();
  15228. });
  15229. ssl_svr1.wait_until_ready();
  15230. ssl_svr2.wait_until_ready();
  15231. SSLClient cli("127.0.0.1", PORT);
  15232. cli.set_follow_location(true);
  15233. cli.set_connection_timeout(30);
  15234. setup(cli);
  15235. return cli.Get("/index");
  15236. }
  15237. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15238. auto calls = 0;
  15239. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15240. cli.enable_server_certificate_verification(false);
  15241. // Accept the first server only.
  15242. cli.set_session_verifier([&](tls::session_t) {
  15243. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15244. : SSLVerifierResponse::CertificateRejected;
  15245. });
  15246. });
  15247. ASSERT_FALSE(res);
  15248. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15249. EXPECT_EQ(2, calls);
  15250. }
  15251. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15252. std::string pinned;
  15253. auto res = GetThroughTlsRedirectToDifferentPort(
  15254. [&](SSLClient &cli) {
  15255. cli.enable_server_certificate_verification(false);
  15256. // Pin the first certificate seen.
  15257. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15258. if (pinned.empty()) { pinned = ctx.serial(); }
  15259. return ctx.serial() == pinned;
  15260. });
  15261. },
  15262. // A certificate other than the first server's.
  15263. SERVER_CERT_FILE);
  15264. EXPECT_FALSE(res);
  15265. EXPECT_FALSE(pinned.empty());
  15266. }
  15267. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15268. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15269. std::string cert;
  15270. read_file(SERVER_CERT2_FILE, cert);
  15271. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15272. });
  15273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15274. EXPECT_EQ(StatusCode::OK_200, res->status);
  15275. }
  15276. // The target's certificate is signed by the root CA, which the first server's
  15277. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15278. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15279. auto res = GetThroughTlsRedirectToDifferentPort(
  15280. [](SSLClient &cli) {
  15281. std::string root_ca, cert;
  15282. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15283. read_file(SERVER_CERT2_FILE, cert);
  15284. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15285. cli.load_ca_cert_store(cert.data(), cert.size());
  15286. cli.enable_server_hostname_verification(false);
  15287. },
  15288. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15290. EXPECT_EQ(StatusCode::OK_200, res->status);
  15291. }
  15292. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15293. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15294. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15295. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15296. auto res = GetThroughTlsRedirectToDifferentPort(
  15297. [](SSLClient &cli) {
  15298. std::string root_ca, cert;
  15299. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15300. read_file(SERVER_CERT2_FILE, cert);
  15301. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15302. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15303. cli.enable_server_hostname_verification(false);
  15304. },
  15305. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15306. ASSERT_FALSE(res);
  15307. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15308. }
  15309. #endif
  15310. #endif
  15311. #ifdef CPPHTTPLIB_SSL_ENABLED
  15312. // Test that set_ca_cert_store() skips system certs (consistent with
  15313. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15314. // should be trusted - system certs should NOT be loaded.
  15315. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15316. // Load a specific cert that is NOT a system CA cert
  15317. std::string cert;
  15318. read_file(SERVER_CERT2_FILE, cert);
  15319. SSLClient cli("google.com");
  15320. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15321. cli.enable_server_certificate_verification(true);
  15322. // This should FAIL because:
  15323. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15324. // 2. System certs should NOT be loaded when custom store is set
  15325. // If system certs WERE loaded, this would succeed
  15326. auto res = cli.Get("/");
  15327. ASSERT_FALSE(res);
  15328. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15329. }
  15330. // Same as above, but through the native store handle path. Regression test:
  15331. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15332. // merged system certs into the user-provided store.
  15333. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15334. std::string cert;
  15335. read_file(SERVER_CERT2_FILE, cert);
  15336. SSLClient cli("google.com");
  15337. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15338. cli.enable_server_certificate_verification(true);
  15339. auto res = cli.Get("/");
  15340. ASSERT_FALSE(res);
  15341. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15342. }
  15343. // A custom store set via the native handle must still verify a server whose
  15344. // cert it does contain.
  15345. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15346. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15347. ASSERT_TRUE(svr.is_valid());
  15348. svr.Get("/test", [&](const Request &, Response &res) {
  15349. res.set_content("test", "text/plain");
  15350. });
  15351. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15352. auto se = detail::scope_exit([&] {
  15353. svr.stop();
  15354. t.join();
  15355. ASSERT_FALSE(svr.is_running());
  15356. });
  15357. svr.wait_until_ready();
  15358. SSLClient cli("127.0.0.1", PORT);
  15359. std::string cert;
  15360. read_file(SERVER_CERT2_FILE, cert);
  15361. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15362. cli.enable_server_certificate_verification(true);
  15363. cli.set_connection_timeout(30);
  15364. auto res = cli.Get("/test");
  15365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15366. ASSERT_EQ(StatusCode::OK_200, res->status);
  15367. }
  15368. // CA certs loaded through the universal Client must be transferred to the
  15369. // client created internally for following an HTTPS redirect. Regression test:
  15370. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15371. // the CA data for redirect transfer.
  15372. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15373. auto ssl_port = PORT + 1;
  15374. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15375. ASSERT_TRUE(ssl_svr1.is_valid());
  15376. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15377. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15378. "/index");
  15379. });
  15380. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15381. ASSERT_TRUE(ssl_svr2.is_valid());
  15382. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15383. res.set_content("test", "text/plain");
  15384. });
  15385. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15386. thread t2 =
  15387. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15388. auto se = detail::scope_exit([&] {
  15389. ssl_svr2.stop();
  15390. ssl_svr1.stop();
  15391. t2.join();
  15392. t.join();
  15393. ASSERT_FALSE(ssl_svr1.is_running());
  15394. });
  15395. ssl_svr1.wait_until_ready();
  15396. ssl_svr2.wait_until_ready();
  15397. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15398. std::string cert;
  15399. read_file(SERVER_CERT2_FILE, cert);
  15400. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15401. cli.enable_server_certificate_verification(true);
  15402. cli.set_follow_location(true);
  15403. cli.set_connection_timeout(30);
  15404. auto res = cli.Get("/index");
  15405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15406. ASSERT_EQ(StatusCode::OK_200, res->status);
  15407. }
  15408. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15409. // so a host signed by a system CA verifies even though a custom CA is set
  15410. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15411. std::string cert;
  15412. read_file(SERVER_CERT2_FILE, cert);
  15413. SSLClient cli("google.com");
  15414. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15415. cli.enable_system_ca(true);
  15416. cli.enable_server_certificate_verification(true);
  15417. auto res = cli.Get("/");
  15418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15419. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15420. }
  15421. // The custom CA remains effective when combined with the system CA
  15422. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15423. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15424. ASSERT_TRUE(svr.is_valid());
  15425. svr.Get("/test", [&](const Request &, Response &res) {
  15426. res.set_content("test", "text/plain");
  15427. });
  15428. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15429. auto se = detail::scope_exit([&] {
  15430. svr.stop();
  15431. t.join();
  15432. ASSERT_FALSE(svr.is_running());
  15433. });
  15434. svr.wait_until_ready();
  15435. SSLClient cli("127.0.0.1", PORT);
  15436. std::string cert;
  15437. read_file(SERVER_CERT2_FILE, cert);
  15438. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15439. cli.enable_system_ca(true);
  15440. cli.enable_server_certificate_verification(true);
  15441. cli.set_connection_timeout(30);
  15442. auto res = cli.Get("/test");
  15443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15444. ASSERT_EQ(StatusCode::OK_200, res->status);
  15445. }
  15446. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15447. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15448. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15449. static CFDictionaryRef
  15450. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15451. const SecTrustSettingsResult *result) {
  15452. auto constraint =
  15453. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15454. &kCFTypeDictionaryValueCallBacks);
  15455. if (policy) {
  15456. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15457. }
  15458. if (policy_string) {
  15459. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15460. kCFStringEncodingUTF8);
  15461. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15462. CFRelease(str);
  15463. }
  15464. if (result) {
  15465. auto number_value = static_cast<SInt32>(*result);
  15466. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15467. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15468. CFRelease(number);
  15469. }
  15470. return constraint;
  15471. }
  15472. static SecTrustSettingsResult
  15473. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15474. auto trust_settings =
  15475. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15476. for (auto constraint : constraints) {
  15477. CFArrayAppendValue(trust_settings, constraint);
  15478. CFRelease(constraint);
  15479. }
  15480. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15481. CFRelease(trust_settings);
  15482. return result;
  15483. }
  15484. // The system CA loader takes a Keychain certificate as a trusted root only
  15485. // when its Trust Settings say so for SSL, not merely because it has some.
  15486. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15487. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15488. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15489. const auto deny = kSecTrustSettingsResultDeny;
  15490. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15491. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15492. auto x509_policy = SecPolicyCreateBasicX509();
  15493. // "Always Trust", which stores no constraint at all
  15494. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15495. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15496. ssl_trust_settings_result(
  15497. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15498. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15499. ssl_trust_settings_result(
  15500. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15501. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15502. ssl_trust_settings_result(
  15503. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15504. // "Never Trust", for everything or for SSL
  15505. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15506. ssl_trust_settings_result(
  15507. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15508. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15509. ssl_trust_settings_result(
  15510. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15511. // Trusted for another policy, for one host, or not at all
  15512. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15513. ssl_trust_settings_result(
  15514. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15515. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15516. ssl_trust_settings_result({make_usage_constraint(
  15517. ssl_policy, "www.example.com", &trust_root)}));
  15518. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15519. ssl_trust_settings_result(
  15520. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15521. // The first constraint that applies to SSL decides
  15522. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15523. ssl_trust_settings_result(
  15524. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15525. make_usage_constraint(nullptr, nullptr, &deny)}));
  15526. CFRelease(x509_policy);
  15527. CFRelease(ssl_policy);
  15528. }
  15529. #endif
  15530. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15531. // skip chain verification entirely (only the certificate identity was
  15532. // checked), so a server presenting an untrusted certificate with a matching
  15533. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15534. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15535. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15536. ASSERT_TRUE(svr.is_valid());
  15537. svr.Get("/test", [&](const Request &, Response &res) {
  15538. res.set_content("test", "text/plain");
  15539. });
  15540. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15541. auto se = detail::scope_exit([&] {
  15542. svr.stop();
  15543. t.join();
  15544. ASSERT_FALSE(svr.is_running());
  15545. });
  15546. svr.wait_until_ready();
  15547. SSLClient cli("127.0.0.1", PORT);
  15548. std::string cert;
  15549. // A trusted CA that did not sign the server certificate. The server cert
  15550. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15551. // this connection.
  15552. read_file(CLIENT_CA_CERT_FILE, cert);
  15553. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15554. cli.enable_server_certificate_verification(true);
  15555. cli.set_connection_timeout(30);
  15556. auto res = cli.Get("/test");
  15557. ASSERT_FALSE(res);
  15558. }
  15559. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15560. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15561. // CA that failed to come through fails verification instead of trusting them.
  15562. // (wolfSSL does not list the system CAs it loaded.)
  15563. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15564. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15565. ASSERT_TRUE(svr.is_valid());
  15566. auto port = svr.bind_to_any_port("127.0.0.1");
  15567. ASSERT_LT(0, port);
  15568. thread t = thread([&] { svr.listen_after_bind(); });
  15569. auto se = detail::scope_exit([&] {
  15570. svr.stop();
  15571. t.join();
  15572. ASSERT_FALSE(svr.is_running());
  15573. });
  15574. svr.wait_until_ready();
  15575. // The CAs a client trusts once its first request has loaded them
  15576. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15577. Client cli("https://127.0.0.1:" + std::to_string(port));
  15578. setup(cli);
  15579. cli.Get("/");
  15580. return tls::get_ca_names(cli.tls_context()).size();
  15581. };
  15582. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15583. EXPECT_EQ(0u,
  15584. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15585. }
  15586. #endif
  15587. // A TLS setting changed between requests applies to the next one, not just to
  15588. // the next connection
  15589. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15590. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15591. ASSERT_TRUE(svr.is_valid());
  15592. svr.Get("/", [](const Request &req, Response &res) {
  15593. res.set_content(std::to_string(req.remote_port), "text/plain");
  15594. });
  15595. auto port = svr.bind_to_any_port("127.0.0.1");
  15596. ASSERT_LT(0, port);
  15597. thread t = thread([&] { svr.listen_after_bind(); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. t.join();
  15601. ASSERT_FALSE(svr.is_running());
  15602. });
  15603. svr.wait_until_ready();
  15604. SSLClient cli("127.0.0.1", port);
  15605. cli.set_keep_alive(true);
  15606. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15607. cli.enable_server_certificate_verification(false);
  15608. // The port the request went out from, so a new one means a new connection
  15609. auto client_port = [&] {
  15610. auto res = cli.Get("/");
  15611. return res ? res->body : std::string();
  15612. };
  15613. auto last = client_port();
  15614. ASSERT_FALSE(last.empty());
  15615. // Setting a value it already has keeps the connection
  15616. cli.enable_server_certificate_verification(false);
  15617. cli.enable_server_hostname_verification(true);
  15618. EXPECT_EQ(last, client_port());
  15619. cli.enable_server_certificate_verification(true);
  15620. auto res = cli.Get("/");
  15621. EXPECT_FALSE(res);
  15622. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15623. std::string ca;
  15624. read_file(SERVER_CERT2_FILE, ca);
  15625. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15626. last = client_port();
  15627. ASSERT_FALSE(last.empty());
  15628. std::vector<std::function<void()>> setters = {
  15629. [&] { cli.enable_server_hostname_verification(false); },
  15630. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15631. [&] {
  15632. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15633. },
  15634. [&] {
  15635. cli.set_server_certificate_verifier(
  15636. [](const tls::VerifyContext &) { return true; });
  15637. },
  15638. [&] {
  15639. cli.set_session_verifier(
  15640. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15641. },
  15642. };
  15643. for (const auto &setter : setters) {
  15644. setter();
  15645. auto next = client_port();
  15646. ASSERT_FALSE(next.empty());
  15647. EXPECT_NE(last, next);
  15648. last = next;
  15649. }
  15650. cli.set_session_verifier(
  15651. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15652. auto handle = cli.open_stream("GET", "/");
  15653. EXPECT_FALSE(handle.is_valid());
  15654. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15655. }
  15656. // A PEM given to create_ca_store() needs no NUL after it
  15657. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15658. std::string pem;
  15659. read_file(SERVER_CERT2_FILE, pem);
  15660. auto buf = pem + "X";
  15661. auto store = tls::create_ca_store(buf.data(), pem.size());
  15662. EXPECT_TRUE(store != nullptr);
  15663. SSLClient cli("localhost");
  15664. cli.set_ca_cert_store(store);
  15665. }
  15666. // enable_system_ca(false) prevents system CA loading entirely
  15667. TEST(SSLClientTest, DisableSystemCa_Online) {
  15668. SSLClient cli("google.com");
  15669. cli.enable_system_ca(false);
  15670. cli.enable_server_certificate_verification(true);
  15671. auto res = cli.Get("/");
  15672. ASSERT_FALSE(res);
  15673. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15674. // itself when the CA chain is empty
  15675. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15676. res.error() == Error::SSLConnection);
  15677. }
  15678. // The universal Client forwards enable_system_ca()
  15679. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15680. std::string cert;
  15681. read_file(SERVER_CERT2_FILE, cert);
  15682. Client cli("https://google.com");
  15683. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15684. cli.enable_system_ca(true);
  15685. cli.enable_server_certificate_verification(true);
  15686. auto res = cli.Get("/");
  15687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15688. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15689. }
  15690. // The system CA policy must carry over to the client created internally for
  15691. // following a cross-host HTTPS redirect
  15692. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15693. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15694. ASSERT_TRUE(svr.is_valid());
  15695. svr.Get("/index", [&](const Request &, Response &res) {
  15696. res.set_redirect("https://www.google.com/");
  15697. });
  15698. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15699. auto se = detail::scope_exit([&] {
  15700. svr.stop();
  15701. t.join();
  15702. ASSERT_FALSE(svr.is_running());
  15703. });
  15704. svr.wait_until_ready();
  15705. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15706. std::string cert;
  15707. read_file(SERVER_CERT2_FILE, cert);
  15708. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15709. cli.enable_system_ca(true);
  15710. cli.enable_server_certificate_verification(true);
  15711. cli.set_follow_location(true);
  15712. cli.set_connection_timeout(30);
  15713. // Receiving any response proves the redirect client completed the TLS
  15714. // handshake with a system-CA-signed host
  15715. auto res = cli.Get("/index");
  15716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15717. }
  15718. TEST(MultipartFormDataTest, LargeData) {
  15719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15720. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15721. const ContentReader &content_reader) {
  15722. if (req.is_multipart_form_data()) {
  15723. std::vector<FormData> items;
  15724. content_reader(
  15725. [&](const FormData &file) {
  15726. items.push_back(file);
  15727. return true;
  15728. },
  15729. [&](const char *data, size_t data_length) {
  15730. items.back().content.append(data, data_length);
  15731. return true;
  15732. });
  15733. EXPECT_TRUE(std::string(items[0].name) == "document");
  15734. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15735. EXPECT_TRUE(items[0].filename == "2MB_data");
  15736. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15737. EXPECT_TRUE(items[1].name == "hello");
  15738. EXPECT_TRUE(items[1].content == "world");
  15739. EXPECT_TRUE(items[1].filename == "");
  15740. EXPECT_TRUE(items[1].content_type == "");
  15741. } else {
  15742. std::string body;
  15743. content_reader([&](const char *data, size_t data_length) {
  15744. body.append(data, data_length);
  15745. return true;
  15746. });
  15747. }
  15748. });
  15749. auto port = svr.bind_to_any_port(HOST);
  15750. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15751. auto se = detail::scope_exit([&] {
  15752. svr.stop();
  15753. t.join();
  15754. ASSERT_FALSE(svr.is_running());
  15755. });
  15756. svr.wait_until_ready();
  15757. {
  15758. std::string data(1024 * 1024 * 2, '.');
  15759. std::stringstream buffer;
  15760. buffer << data;
  15761. SSLClient cli(HOST, port);
  15762. cli.enable_server_certificate_verification(false);
  15763. UploadFormDataItems items{
  15764. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15765. {"hello", "world", "", ""},
  15766. };
  15767. auto res = cli.Post("/post", items);
  15768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15769. ASSERT_EQ(StatusCode::OK_200, res->status);
  15770. }
  15771. }
  15772. TEST(MultipartFormDataTest, DataProviderItems) {
  15773. std::random_device seed_gen;
  15774. std::mt19937 random(seed_gen());
  15775. std::string rand1;
  15776. rand1.resize(1000);
  15777. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15778. std::string rand2;
  15779. rand2.resize(3000);
  15780. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15782. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15783. const ContentReader &content_reader) {
  15784. ASSERT_FALSE(req.is_multipart_form_data());
  15785. std::string body;
  15786. content_reader([&](const char *data, size_t data_length) {
  15787. body.append(data, data_length);
  15788. return true;
  15789. });
  15790. EXPECT_EQ(body, "");
  15791. });
  15792. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15793. const ContentReader &content_reader) {
  15794. ASSERT_TRUE(req.is_multipart_form_data());
  15795. std::vector<FormData> items;
  15796. content_reader(
  15797. [&](const FormData &file) {
  15798. items.push_back(file);
  15799. return true;
  15800. },
  15801. [&](const char *data, size_t data_length) {
  15802. items.back().content.append(data, data_length);
  15803. return true;
  15804. });
  15805. ASSERT_TRUE(items.size() == 2);
  15806. EXPECT_EQ(std::string(items[0].name), "name1");
  15807. EXPECT_EQ(items[0].content, "Testing123");
  15808. EXPECT_EQ(items[0].filename, "filename1");
  15809. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15810. EXPECT_EQ(items[1].name, "name2");
  15811. EXPECT_EQ(items[1].content, "Testing456");
  15812. EXPECT_EQ(items[1].filename, "");
  15813. EXPECT_EQ(items[1].content_type, "");
  15814. });
  15815. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15816. const ContentReader &content_reader) {
  15817. ASSERT_TRUE(req.is_multipart_form_data());
  15818. std::vector<FormData> items;
  15819. content_reader(
  15820. [&](const FormData &file) {
  15821. items.push_back(file);
  15822. return true;
  15823. },
  15824. [&](const char *data, size_t data_length) {
  15825. items.back().content.append(data, data_length);
  15826. return true;
  15827. });
  15828. ASSERT_TRUE(items.size() == 2);
  15829. EXPECT_EQ(items[0].name, "name3");
  15830. EXPECT_EQ(items[0].content, rand1);
  15831. EXPECT_EQ(items[0].filename, "filename3");
  15832. EXPECT_EQ(items[0].content_type, "");
  15833. EXPECT_EQ(items[1].name, "name4");
  15834. EXPECT_EQ(items[1].content, rand2);
  15835. EXPECT_EQ(items[1].filename, "filename4");
  15836. EXPECT_EQ(items[1].content_type, "");
  15837. });
  15838. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15839. const ContentReader &content_reader) {
  15840. ASSERT_TRUE(req.is_multipart_form_data());
  15841. std::vector<FormData> items;
  15842. content_reader(
  15843. [&](const FormData &file) {
  15844. items.push_back(file);
  15845. return true;
  15846. },
  15847. [&](const char *data, size_t data_length) {
  15848. items.back().content.append(data, data_length);
  15849. return true;
  15850. });
  15851. ASSERT_TRUE(items.size() == 4);
  15852. EXPECT_EQ(std::string(items[0].name), "name1");
  15853. EXPECT_EQ(items[0].content, "Testing123");
  15854. EXPECT_EQ(items[0].filename, "filename1");
  15855. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15856. EXPECT_EQ(items[1].name, "name2");
  15857. EXPECT_EQ(items[1].content, "Testing456");
  15858. EXPECT_EQ(items[1].filename, "");
  15859. EXPECT_EQ(items[1].content_type, "");
  15860. EXPECT_EQ(items[2].name, "name3");
  15861. EXPECT_EQ(items[2].content, rand1);
  15862. EXPECT_EQ(items[2].filename, "filename3");
  15863. EXPECT_EQ(items[2].content_type, "");
  15864. EXPECT_EQ(items[3].name, "name4");
  15865. EXPECT_EQ(items[3].content, rand2);
  15866. EXPECT_EQ(items[3].filename, "filename4");
  15867. EXPECT_EQ(items[3].content_type, "");
  15868. });
  15869. auto port = svr.bind_to_any_port("localhost");
  15870. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15871. auto se = detail::scope_exit([&] {
  15872. svr.stop();
  15873. t.join();
  15874. ASSERT_FALSE(svr.is_running());
  15875. });
  15876. svr.wait_until_ready();
  15877. {
  15878. SSLClient cli("localhost", port);
  15879. cli.enable_server_certificate_verification(false);
  15880. UploadFormDataItems items{
  15881. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15882. {"name2", "Testing456", "", ""}, // not a file
  15883. };
  15884. {
  15885. auto res = cli.Post("/post-none", {}, {}, {});
  15886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15887. ASSERT_EQ(StatusCode::OK_200, res->status);
  15888. }
  15889. FormDataProviderItems providers;
  15890. {
  15891. auto res =
  15892. cli.Post("/post-items", {}, items, providers); // empty providers
  15893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15894. ASSERT_EQ(StatusCode::OK_200, res->status);
  15895. }
  15896. providers.push_back({"name3",
  15897. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15898. // test the offset is given correctly at each step
  15899. if (!offset)
  15900. sink.os.write(rand1.data(), 30);
  15901. else if (offset == 30)
  15902. sink.os.write(rand1.data() + 30, 300);
  15903. else if (offset == 330)
  15904. sink.os.write(rand1.data() + 330, 670);
  15905. else if (offset == rand1.size())
  15906. sink.done();
  15907. return true;
  15908. },
  15909. "filename3",
  15910. {}});
  15911. providers.push_back({"name4",
  15912. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15913. // test the offset is given correctly at each step
  15914. if (!offset)
  15915. sink.os.write(rand2.data(), 2000);
  15916. else if (offset == 2000)
  15917. sink.os.write(rand2.data() + 2000, 1);
  15918. else if (offset == 2001)
  15919. sink.os.write(rand2.data() + 2001, 999);
  15920. else if (offset == rand2.size())
  15921. sink.done();
  15922. return true;
  15923. },
  15924. "filename4",
  15925. {}});
  15926. {
  15927. auto res = cli.Post("/post-providers", {}, {}, providers);
  15928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15929. ASSERT_EQ(StatusCode::OK_200, res->status);
  15930. }
  15931. {
  15932. auto res = cli.Post("/post-both", {}, items, providers);
  15933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15934. ASSERT_EQ(StatusCode::OK_200, res->status);
  15935. }
  15936. }
  15937. }
  15938. TEST(MultipartFormDataTest, BadHeader) {
  15939. Server svr;
  15940. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15941. res.set_content("ok", "text/plain");
  15942. });
  15943. thread t = thread([&] { svr.listen(HOST, PORT); });
  15944. auto se = detail::scope_exit([&] {
  15945. svr.stop();
  15946. t.join();
  15947. ASSERT_FALSE(svr.is_running());
  15948. });
  15949. svr.wait_until_ready();
  15950. const std::string body =
  15951. "This is the preamble. It is to be ignored, though it\r\n"
  15952. "is a handy place for composition agents to include an\r\n"
  15953. "explanatory note to non-MIME conformant readers.\r\n"
  15954. "\r\n"
  15955. "\r\n"
  15956. "--simple boundary\r\n"
  15957. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15958. ": BAD...\r\n"
  15959. "\r\n"
  15960. "value1\r\n"
  15961. "--simple boundary\r\n"
  15962. "Content-Disposition: form-data; name=\"field2\"; "
  15963. "filename=\"example.txt\"\r\n"
  15964. "\r\n"
  15965. "value2\r\n"
  15966. "--simple boundary--\r\n"
  15967. "This is the epilogue. It is also to be ignored.\r\n";
  15968. std::string content_type =
  15969. R"(multipart/form-data; boundary="simple boundary")";
  15970. Client cli(HOST, PORT);
  15971. auto res = cli.Post("/post", body, content_type.c_str());
  15972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15973. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15974. }
  15975. TEST(MultipartFormDataTest, WithPreamble) {
  15976. Server svr;
  15977. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15978. res.set_content("ok", "text/plain");
  15979. });
  15980. thread t = thread([&] { svr.listen(HOST, PORT); });
  15981. auto se = detail::scope_exit([&] {
  15982. svr.stop();
  15983. t.join();
  15984. ASSERT_FALSE(svr.is_running());
  15985. });
  15986. svr.wait_until_ready();
  15987. const std::string body =
  15988. "This is the preamble. It is to be ignored, though it\r\n"
  15989. "is a handy place for composition agents to include an\r\n"
  15990. "explanatory note to non-MIME conformant readers.\r\n"
  15991. "\r\n"
  15992. "\r\n"
  15993. "--simple boundary\r\n"
  15994. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15995. "\r\n"
  15996. "value1\r\n"
  15997. "--simple boundary\r\n"
  15998. "Content-Disposition: form-data; name=\"field2\"; "
  15999. "filename=\"example.txt\"\r\n"
  16000. "\r\n"
  16001. "value2\r\n"
  16002. "--simple boundary--\r\n"
  16003. "This is the epilogue. It is also to be ignored.\r\n";
  16004. std::string content_type =
  16005. R"(multipart/form-data; boundary="simple boundary")";
  16006. Client cli(HOST, PORT);
  16007. auto res = cli.Post("/post", body, content_type.c_str());
  16008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16009. EXPECT_EQ(StatusCode::OK_200, res->status);
  16010. }
  16011. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16012. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16013. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16014. const ContentReader &content_reader) {
  16015. if (req.is_multipart_form_data()) {
  16016. std::vector<FormData> items;
  16017. content_reader(
  16018. [&](const FormData &file) {
  16019. items.push_back(file);
  16020. return true;
  16021. },
  16022. [&](const char *data, size_t data_length) {
  16023. items.back().content.append(data, data_length);
  16024. return true;
  16025. });
  16026. EXPECT_TRUE(std::string(items[0].name) == "document");
  16027. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16028. EXPECT_TRUE(items[0].filename == "2MB_data");
  16029. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16030. EXPECT_TRUE(items[1].name == "hello");
  16031. EXPECT_TRUE(items[1].content == "world");
  16032. EXPECT_TRUE(items[1].filename == "");
  16033. EXPECT_TRUE(items[1].content_type == "");
  16034. } else {
  16035. std::string body;
  16036. content_reader([&](const char *data, size_t data_length) {
  16037. body.append(data, data_length);
  16038. return true;
  16039. });
  16040. }
  16041. });
  16042. auto port = svr.bind_to_any_port("localhost");
  16043. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16044. auto se = detail::scope_exit([&] {
  16045. svr.stop();
  16046. t.join();
  16047. ASSERT_FALSE(svr.is_running());
  16048. });
  16049. svr.wait_until_ready();
  16050. {
  16051. std::string data(1024 * 1024 * 2, '.');
  16052. std::stringstream buffer;
  16053. buffer << data;
  16054. SSLClient cli("localhost", port);
  16055. cli.enable_server_certificate_verification(false);
  16056. UploadFormDataItems items{
  16057. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16058. {"hello", "world", "", ""},
  16059. };
  16060. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16062. ASSERT_EQ(StatusCode::OK_200, res->status);
  16063. }
  16064. }
  16065. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16066. std::string data(1024 * 1024 * 2, '&');
  16067. std::stringstream buffer;
  16068. buffer << data;
  16069. Client cli("https://localhost:8080");
  16070. UploadFormDataItems items{
  16071. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16072. {"hello", "world", "", ""},
  16073. };
  16074. for (const char &c : " \t\r\n") {
  16075. auto res =
  16076. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16077. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16078. ASSERT_FALSE(res);
  16079. }
  16080. }
  16081. TEST(MultipartFormDataTest, PutFormData) {
  16082. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16083. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16084. const ContentReader &content_reader) {
  16085. if (req.is_multipart_form_data()) {
  16086. std::vector<FormData> items;
  16087. content_reader(
  16088. [&](const FormData &file) {
  16089. items.push_back(file);
  16090. return true;
  16091. },
  16092. [&](const char *data, size_t data_length) {
  16093. items.back().content.append(data, data_length);
  16094. return true;
  16095. });
  16096. EXPECT_TRUE(std::string(items[0].name) == "document");
  16097. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16098. EXPECT_TRUE(items[0].filename == "2MB_data");
  16099. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16100. EXPECT_TRUE(items[1].name == "hello");
  16101. EXPECT_TRUE(items[1].content == "world");
  16102. EXPECT_TRUE(items[1].filename == "");
  16103. EXPECT_TRUE(items[1].content_type == "");
  16104. } else {
  16105. std::string body;
  16106. content_reader([&](const char *data, size_t data_length) {
  16107. body.append(data, data_length);
  16108. return true;
  16109. });
  16110. }
  16111. });
  16112. auto port = svr.bind_to_any_port("localhost");
  16113. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16114. auto se = detail::scope_exit([&] {
  16115. svr.stop();
  16116. t.join();
  16117. ASSERT_FALSE(svr.is_running());
  16118. });
  16119. svr.wait_until_ready();
  16120. {
  16121. std::string data(1024 * 1024 * 2, '&');
  16122. std::stringstream buffer;
  16123. buffer << data;
  16124. SSLClient cli("localhost", port);
  16125. cli.enable_server_certificate_verification(false);
  16126. UploadFormDataItems items{
  16127. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16128. {"hello", "world", "", ""},
  16129. };
  16130. auto res = cli.Put("/put", items);
  16131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16132. ASSERT_EQ(StatusCode::OK_200, res->status);
  16133. }
  16134. }
  16135. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16136. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16137. svr.Put("/put_customboundary",
  16138. [&](const Request &req, const Response & /*res*/,
  16139. const ContentReader &content_reader) {
  16140. if (req.is_multipart_form_data()) {
  16141. std::vector<FormData> items;
  16142. content_reader(
  16143. [&](const FormData &file) {
  16144. items.push_back(file);
  16145. return true;
  16146. },
  16147. [&](const char *data, size_t data_length) {
  16148. items.back().content.append(data, data_length);
  16149. return true;
  16150. });
  16151. EXPECT_TRUE(std::string(items[0].name) == "document");
  16152. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16153. EXPECT_TRUE(items[0].filename == "2MB_data");
  16154. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16155. EXPECT_TRUE(items[1].name == "hello");
  16156. EXPECT_TRUE(items[1].content == "world");
  16157. EXPECT_TRUE(items[1].filename == "");
  16158. EXPECT_TRUE(items[1].content_type == "");
  16159. } else {
  16160. std::string body;
  16161. content_reader([&](const char *data, size_t data_length) {
  16162. body.append(data, data_length);
  16163. return true;
  16164. });
  16165. }
  16166. });
  16167. auto port = svr.bind_to_any_port("localhost");
  16168. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16169. auto se = detail::scope_exit([&] {
  16170. svr.stop();
  16171. t.join();
  16172. ASSERT_FALSE(svr.is_running());
  16173. });
  16174. svr.wait_until_ready();
  16175. {
  16176. std::string data(1024 * 1024 * 2, '&');
  16177. std::stringstream buffer;
  16178. buffer << data;
  16179. SSLClient cli("localhost", port);
  16180. cli.enable_server_certificate_verification(false);
  16181. UploadFormDataItems items{
  16182. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16183. {"hello", "world", "", ""},
  16184. };
  16185. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16187. ASSERT_EQ(StatusCode::OK_200, res->status);
  16188. }
  16189. }
  16190. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16191. std::string data(1024 * 1024 * 2, '&');
  16192. std::stringstream buffer;
  16193. buffer << data;
  16194. Client cli("https://localhost:8080");
  16195. cli.enable_server_certificate_verification(false);
  16196. UploadFormDataItems items{
  16197. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16198. {"hello", "world", "", ""},
  16199. };
  16200. for (const char &c : " \t\r\n") {
  16201. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16202. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16203. ASSERT_FALSE(res);
  16204. }
  16205. }
  16206. TEST(MultipartFormDataTest, AlternateFilename) {
  16207. auto handled = false;
  16208. Server svr;
  16209. svr.Post("/test", [&](const Request &req, Response &res) {
  16210. ASSERT_EQ(2u, req.form.files.size());
  16211. ASSERT_EQ(1u, req.form.fields.size());
  16212. // Test files
  16213. const auto &file1 = req.form.get_file("file1");
  16214. ASSERT_EQ("file1", file1.name);
  16215. ASSERT_EQ("A.txt", file1.filename);
  16216. ASSERT_EQ("text/plain", file1.content_type);
  16217. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16218. const auto &file2 = req.form.get_file("file2");
  16219. ASSERT_EQ("file2", file2.name);
  16220. ASSERT_EQ("a.html", file2.filename);
  16221. ASSERT_EQ("text/html", file2.content_type);
  16222. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16223. file2.content);
  16224. // Test text field
  16225. const auto &text = req.form.get_field("text");
  16226. ASSERT_EQ("text default", text);
  16227. res.set_content("ok", "text/plain");
  16228. handled = true;
  16229. });
  16230. thread t = thread([&] { svr.listen(HOST, PORT); });
  16231. auto se = detail::scope_exit([&] {
  16232. svr.stop();
  16233. t.join();
  16234. ASSERT_FALSE(svr.is_running());
  16235. ASSERT_TRUE(handled);
  16236. });
  16237. svr.wait_until_ready();
  16238. auto req = "POST /test HTTP/1.1\r\n"
  16239. "Host: localhost\r\n"
  16240. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16241. "Content-Length: 399\r\n"
  16242. "\r\n"
  16243. "----------\r\n"
  16244. "Content-Disposition: form-data; name=\"text\"\r\n"
  16245. "\r\n"
  16246. "text default\r\n"
  16247. "----------\r\n"
  16248. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16249. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16250. "Content-Type: text/plain\r\n"
  16251. "\r\n"
  16252. "Content of a.txt.\r\n"
  16253. "\r\n"
  16254. "----------\r\n"
  16255. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16256. "\"a.html\"\r\n"
  16257. "Content-Type: text/html\r\n"
  16258. "\r\n"
  16259. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16260. "\r\n"
  16261. "------------\r\n";
  16262. ASSERT_TRUE(send_request(1, req));
  16263. }
  16264. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16265. auto handled = false;
  16266. Server svr;
  16267. svr.Post("/test", [&](const Request &req, Response &res) {
  16268. // Case-insensitive "utf-8''" prefix with a long value
  16269. const auto &file = req.form.get_file("file1");
  16270. ASSERT_EQ("file1", file.name);
  16271. // 8000 chars exercises both the Content-Disposition parser and the
  16272. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16273. // Prior to the fix, std::regex_match on this header would cause O(N)
  16274. // stack recursion in libstdc++, leading to SIGSEGV.
  16275. std::string expected_filename(8000, 'A');
  16276. ASSERT_EQ(expected_filename, file.filename);
  16277. res.set_content("ok", "text/plain");
  16278. handled = true;
  16279. });
  16280. thread t = thread([&] { svr.listen(HOST, PORT); });
  16281. auto se = detail::scope_exit([&] {
  16282. svr.stop();
  16283. t.join();
  16284. ASSERT_FALSE(svr.is_running());
  16285. ASSERT_TRUE(handled);
  16286. });
  16287. svr.wait_until_ready();
  16288. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16289. // Regression test for GHSA-qq6v-r583-3h69
  16290. std::string long_filename(8000, 'A');
  16291. std::string body = "----------\r\n"
  16292. "Content-Disposition: form-data; name=\"file1\"; "
  16293. "filename*=\"Utf-8''" +
  16294. long_filename +
  16295. "\"\r\n"
  16296. "\r\n"
  16297. "hello\r\n"
  16298. "------------\r\n";
  16299. auto req = "POST /test HTTP/1.1\r\n"
  16300. "Host: localhost\r\n"
  16301. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16302. "Content-Length: " +
  16303. std::to_string(body.size()) + "\r\n\r\n" + body;
  16304. ASSERT_TRUE(send_request(1, req));
  16305. }
  16306. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16307. auto handled = false;
  16308. Server svr;
  16309. svr.Post("/test", [&](const Request &req, Response &) {
  16310. ASSERT_EQ(2u, req.form.fields.size());
  16311. const auto &text1 = req.form.get_field("text1");
  16312. ASSERT_EQ("text1", text1);
  16313. const auto &text2 = req.form.get_field("text2");
  16314. ASSERT_EQ("text2", text2);
  16315. handled = true;
  16316. });
  16317. thread t = thread([&] { svr.listen(HOST, PORT); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. t.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. ASSERT_TRUE(handled);
  16323. });
  16324. svr.wait_until_ready();
  16325. auto req = "POST /test HTTP/1.1\r\n"
  16326. "Host: localhost\r\n"
  16327. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16328. "Content-Length: 146\r\n"
  16329. "\r\n----------\r\n"
  16330. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16331. "\r\n"
  16332. "text1"
  16333. "\r\n----------\r\n"
  16334. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16335. "\r\n"
  16336. "text2"
  16337. "\r\n------------";
  16338. std::string response;
  16339. ASSERT_TRUE(send_request(1, req, &response));
  16340. ASSERT_EQ("200", response.substr(9, 3));
  16341. }
  16342. TEST(MultipartFormDataTest, ContentLength) {
  16343. auto handled = false;
  16344. Server svr;
  16345. svr.Post("/test", [&](const Request &req, Response &) {
  16346. ASSERT_EQ(2u, req.form.fields.size());
  16347. const auto &text1 = req.form.get_field("text1");
  16348. ASSERT_EQ("text1", text1);
  16349. const auto &text2 = req.form.get_field("text2");
  16350. ASSERT_EQ("text2", text2);
  16351. handled = true;
  16352. });
  16353. thread t = thread([&] { svr.listen(HOST, PORT); });
  16354. auto se = detail::scope_exit([&] {
  16355. svr.stop();
  16356. t.join();
  16357. ASSERT_FALSE(svr.is_running());
  16358. ASSERT_TRUE(handled);
  16359. });
  16360. svr.wait_until_ready();
  16361. auto req = "POST /test HTTP/1.1\r\n"
  16362. "Host: localhost\r\n"
  16363. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16364. "Content-Length: 167\r\n"
  16365. "\r\n----------\r\n"
  16366. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16367. "Content-Length: 5\r\n"
  16368. "\r\n"
  16369. "text1"
  16370. "\r\n----------\r\n"
  16371. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16372. "\r\n"
  16373. "text2"
  16374. "\r\n------------\r\n";
  16375. std::string response;
  16376. ASSERT_TRUE(send_request(1, req, &response));
  16377. ASSERT_EQ("200", response.substr(9, 3));
  16378. }
  16379. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16380. auto handled = false;
  16381. Server svr;
  16382. svr.Post("/test", [&](const Request &req, Response &) {
  16383. ASSERT_EQ(2u, req.form.fields.size());
  16384. const auto &text1 = req.form.get_field("text1");
  16385. ASSERT_EQ("text1", text1);
  16386. // TODO: Add header access for text fields if needed
  16387. const auto &text2 = req.form.get_field("text2");
  16388. ASSERT_EQ("text2", text2);
  16389. // TODO: Header access for text fields needs to be implemented
  16390. // auto &headers = it->second.headers;
  16391. // ASSERT_EQ(3U, headers.size());
  16392. // auto custom_header = headers.find("x-whatever");
  16393. // ASSERT_TRUE(custom_header != headers.end());
  16394. // ASSERT_NE("customvalue", custom_header->second);
  16395. // ASSERT_EQ("CustomValue", custom_header->second);
  16396. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16397. handled = true;
  16398. });
  16399. thread t = thread([&] { svr.listen(HOST, PORT); });
  16400. auto se = detail::scope_exit([&] {
  16401. svr.stop();
  16402. t.join();
  16403. ASSERT_FALSE(svr.is_running());
  16404. ASSERT_TRUE(handled);
  16405. });
  16406. svr.wait_until_ready();
  16407. auto req = "POST /test HTTP/1.1\r\n"
  16408. "Host: localhost\r\n"
  16409. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16410. "Content-Length: 232\r\n"
  16411. "\r\n----------\r\n"
  16412. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16413. "Content-Length: 5\r\n"
  16414. "X-Test: 1\r\n"
  16415. "\r\n"
  16416. "text1"
  16417. "\r\n----------\r\n"
  16418. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16419. "Content-Type: text/plain\r\n"
  16420. "X-Whatever: CustomValue\r\n"
  16421. "\r\n"
  16422. "text2"
  16423. "\r\n------------\r\n"
  16424. "That should be disregarded. Not even read";
  16425. std::string response;
  16426. ASSERT_TRUE(send_request(1, req, &response));
  16427. ASSERT_EQ("200", response.substr(9, 3));
  16428. }
  16429. TEST(MultipartFormDataTest, LargeHeader) {
  16430. auto handled = false;
  16431. Server svr;
  16432. svr.Post("/test", [&](const Request &req, Response &) {
  16433. ASSERT_EQ(1u, req.form.fields.size());
  16434. const auto &text = req.form.get_field("name1");
  16435. ASSERT_EQ("text1", text);
  16436. handled = true;
  16437. });
  16438. thread t = thread([&] { svr.listen(HOST, PORT); });
  16439. auto se = detail::scope_exit([&] {
  16440. svr.stop();
  16441. t.join();
  16442. ASSERT_FALSE(svr.is_running());
  16443. ASSERT_TRUE(handled);
  16444. });
  16445. svr.wait_until_ready();
  16446. auto boundary = std::string("cpp-httplib-multipart-data");
  16447. std::string content = "--" + boundary +
  16448. "\r\n"
  16449. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16450. "\r\n"
  16451. "text1\r\n"
  16452. "--" +
  16453. boundary + "--\r\n";
  16454. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16455. "Host: localhost\r\n"
  16456. "Content-Type: multipart/form-data;boundary=" +
  16457. boundary +
  16458. "\r\n"
  16459. "Content-Length: " +
  16460. std::to_string(content.size()) +
  16461. "\r\n"
  16462. "Dummy-Header: ";
  16463. std::string header_suffix = "\r\n"
  16464. "\r\n";
  16465. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16466. size_t header_dummy_size =
  16467. read_buff_size -
  16468. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16469. auto header_dummy = std::string(header_dummy_size, '@');
  16470. auto req = header_prefix + header_dummy + header_suffix + content;
  16471. std::string response;
  16472. ASSERT_TRUE(send_request(1, req, &response));
  16473. ASSERT_EQ("200", response.substr(9, 3));
  16474. }
  16475. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16476. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16477. // (not chunked Transfer-Encoding) after the streaming refactor.
  16478. auto handled = false;
  16479. Server svr;
  16480. svr.Post("/upload", [&](const Request &req, Response &res) {
  16481. auto cl_it = req.headers.find("Content-Length");
  16482. EXPECT_TRUE(cl_it != req.headers.end());
  16483. auto te_it = req.headers.find("Transfer-Encoding");
  16484. EXPECT_TRUE(te_it == req.headers.end());
  16485. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16486. res.set_content("ok", "text/plain");
  16487. handled = true;
  16488. });
  16489. auto port = svr.bind_to_any_port(HOST);
  16490. auto t = thread([&] { svr.listen_after_bind(); });
  16491. auto se = detail::scope_exit([&] {
  16492. svr.stop();
  16493. t.join();
  16494. ASSERT_FALSE(svr.is_running());
  16495. ASSERT_TRUE(handled);
  16496. });
  16497. svr.wait_until_ready();
  16498. UploadFormDataItems items = {
  16499. {"field1", "hello", "", "text/plain"},
  16500. {"file1", "world", "test.txt", "application/octet-stream"},
  16501. };
  16502. Client cli(HOST, port);
  16503. auto res = cli.Post("/upload", {}, items);
  16504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16505. EXPECT_EQ(StatusCode::OK_200, res->status);
  16506. }
  16507. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16508. // Verify that make_multipart_content_provider coalesces many small segments
  16509. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16510. constexpr size_t kItemCount = 1000;
  16511. UploadFormDataItems items;
  16512. items.reserve(kItemCount);
  16513. for (size_t i = 0; i < kItemCount; i++) {
  16514. items.push_back(
  16515. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16516. }
  16517. const std::string boundary = "----test-boundary";
  16518. auto content_length = detail::get_multipart_content_length(items, boundary);
  16519. auto provider = detail::make_multipart_content_provider(items, boundary);
  16520. // Drive the provider the same way write_content_with_progress does
  16521. size_t write_count = 0;
  16522. size_t total_bytes = 0;
  16523. DataSink sink;
  16524. size_t offset = 0;
  16525. sink.write = [&](const char *d, size_t l) -> bool {
  16526. (void)d;
  16527. write_count++;
  16528. total_bytes += l;
  16529. offset += l;
  16530. return true;
  16531. };
  16532. sink.is_writable = []() -> bool { return true; };
  16533. while (offset < content_length) {
  16534. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16535. }
  16536. EXPECT_EQ(content_length, total_bytes);
  16537. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16538. // With buffering into 64KB blocks, write_count should be much smaller.
  16539. auto segment_count = 3 * kItemCount + 1;
  16540. EXPECT_LT(write_count, segment_count / 10);
  16541. }
  16542. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16543. // Integration test: send many UploadFormDataItems and verify the server
  16544. // receives all of them correctly (#2410).
  16545. constexpr size_t kItemCount = 500;
  16546. auto handled = false;
  16547. Server svr;
  16548. svr.Post("/upload", [&](const Request &req, Response &res) {
  16549. EXPECT_EQ(kItemCount, req.form.fields.size());
  16550. for (size_t i = 0; i < kItemCount; i++) {
  16551. auto key = "field" + std::to_string(i);
  16552. auto val = "value" + std::to_string(i);
  16553. auto it = req.form.fields.find(key);
  16554. if (it != req.form.fields.end()) {
  16555. EXPECT_EQ(val, it->second.content);
  16556. } else {
  16557. ADD_FAILURE() << "Missing field: " << key;
  16558. }
  16559. }
  16560. res.set_content("ok", "text/plain");
  16561. handled = true;
  16562. });
  16563. auto port = svr.bind_to_any_port(HOST);
  16564. auto t = thread([&] { svr.listen_after_bind(); });
  16565. auto se = detail::scope_exit([&] {
  16566. svr.stop();
  16567. t.join();
  16568. ASSERT_FALSE(svr.is_running());
  16569. ASSERT_TRUE(handled);
  16570. });
  16571. svr.wait_until_ready();
  16572. UploadFormDataItems items;
  16573. items.reserve(kItemCount);
  16574. for (size_t i = 0; i < kItemCount; i++) {
  16575. items.push_back(
  16576. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16577. }
  16578. Client cli(HOST, port);
  16579. auto res = cli.Post("/upload", items);
  16580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16581. EXPECT_EQ(StatusCode::OK_200, res->status);
  16582. }
  16583. TEST(MultipartFormDataTest, MakeFileProvider) {
  16584. // Verify make_file_provider sends a file's contents correctly.
  16585. const std::string file_content(4096, 'Z');
  16586. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16587. {
  16588. std::ofstream ofs(tmp_path, std::ios::binary);
  16589. ofs.write(file_content.data(),
  16590. static_cast<std::streamsize>(file_content.size()));
  16591. }
  16592. auto handled = false;
  16593. Server svr;
  16594. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16595. const ContentReader &content_reader) {
  16596. ASSERT_TRUE(req.is_multipart_form_data());
  16597. std::vector<FormData> items;
  16598. content_reader(
  16599. [&](const FormData &file) {
  16600. items.push_back(file);
  16601. return true;
  16602. },
  16603. [&](const char *data, size_t data_length) {
  16604. items.back().content.append(data, data_length);
  16605. return true;
  16606. });
  16607. ASSERT_EQ(1u, items.size());
  16608. EXPECT_EQ("myfile", items[0].name);
  16609. EXPECT_EQ("data.bin", items[0].filename);
  16610. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16611. EXPECT_EQ(file_content, items[0].content);
  16612. handled = true;
  16613. });
  16614. auto port = svr.bind_to_any_port(HOST);
  16615. auto t = thread([&] { svr.listen_after_bind(); });
  16616. auto se = detail::scope_exit([&] {
  16617. svr.stop();
  16618. t.join();
  16619. ASSERT_FALSE(svr.is_running());
  16620. ASSERT_TRUE(handled);
  16621. std::remove(tmp_path.c_str());
  16622. });
  16623. svr.wait_until_ready();
  16624. FormDataProviderItems providers;
  16625. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16626. "application/octet-stream"));
  16627. Client cli(HOST, port);
  16628. auto res = cli.Post("/upload", {}, {}, providers);
  16629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16630. EXPECT_EQ(StatusCode::OK_200, res->status);
  16631. }
  16632. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16633. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16634. // (100) headers is rejected with a 400 Bad Request response.
  16635. Server svr;
  16636. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16637. res.set_content("ok", "text/plain");
  16638. });
  16639. thread t = thread([&] { svr.listen(HOST, PORT); });
  16640. auto se = detail::scope_exit([&] {
  16641. svr.stop();
  16642. t.join();
  16643. ASSERT_FALSE(svr.is_running());
  16644. });
  16645. svr.wait_until_ready();
  16646. // Build a multipart part with 101 custom headers (exceeding
  16647. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16648. std::stringstream body;
  16649. body << "--simpleboundary\r\n"
  16650. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16651. for (int i = 0; i < 101; i++) {
  16652. body << "X-Custom-Header-" << i << ": value\r\n";
  16653. }
  16654. body << "\r\n"
  16655. << "value1\r\n"
  16656. << "--simpleboundary--\r\n";
  16657. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16658. Client cli(HOST, PORT);
  16659. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16661. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16662. }
  16663. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16664. // A body that never contains the declared boundary must not be accumulated
  16665. // while the parser waits for it. Buffering it would also make every read
  16666. // rescan everything seen so far, which is quadratic in the body size.
  16667. Server svr;
  16668. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16669. res.set_content("ok", "text/plain");
  16670. });
  16671. auto port = svr.bind_to_any_port(HOST);
  16672. thread t = thread([&] { svr.listen_after_bind(); });
  16673. auto se = detail::scope_exit([&] {
  16674. svr.stop();
  16675. t.join();
  16676. ASSERT_FALSE(svr.is_running());
  16677. });
  16678. svr.wait_until_ready();
  16679. Client cli(HOST, port);
  16680. cli.set_read_timeout(60, 0);
  16681. cli.set_write_timeout(60, 0);
  16682. // '-' is the worst case: it matches the first character of the boundary, so
  16683. // every position has to be checked against it.
  16684. auto post_dashes = [&](size_t size) {
  16685. const std::string body(size, '-');
  16686. auto start = std::chrono::steady_clock::now();
  16687. auto res =
  16688. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16689. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16690. std::chrono::steady_clock::now() - start)
  16691. .count();
  16692. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16693. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16694. return ms;
  16695. };
  16696. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16697. // Windows.
  16698. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16699. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16700. // Comparing the two sizes rather than checking an absolute duration keeps
  16701. // this meaningful across build types and CI load, both of which move the
  16702. // absolute numbers by more than an order of magnitude. Four times the bytes
  16703. // costs about four times the time when parsing is linear, and about sixteen
  16704. // times when the body is buffered and rescanned.
  16705. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16706. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16707. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16708. << "ms, which suggests the body is being buffered and rescanned";
  16709. }
  16710. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16711. // A boundary can only be followed by CRLF or by "--", so anything else is
  16712. // malformed no matter what comes next. The parser must say so right away
  16713. // instead of buffering the rest of the declared body.
  16714. Server svr;
  16715. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16716. res.set_content("ok", "text/plain");
  16717. });
  16718. auto port = svr.bind_to_any_port(HOST);
  16719. thread t = thread([&] { svr.listen_after_bind(); });
  16720. auto se = detail::scope_exit([&] {
  16721. svr.stop();
  16722. t.join();
  16723. ASSERT_FALSE(svr.is_running());
  16724. });
  16725. svr.wait_until_ready();
  16726. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16727. // buffers instead of failing would still be waiting for the remaining bytes.
  16728. const std::string body = "--zzzz\r\n"
  16729. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16730. "\r\n"
  16731. "text1"
  16732. "\r\n--zzzzXX";
  16733. const std::string req = "POST /post HTTP/1.1\r\n"
  16734. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16735. "Content-Length: 1048576\r\n"
  16736. "\r\n" +
  16737. body;
  16738. std::string response;
  16739. ASSERT_TRUE(send_request(3, req, &response, port));
  16740. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16741. EXPECT_EQ("400", response.substr(9, 3));
  16742. }
  16743. // Posts a multipart body split into two writes, so that the server sees the
  16744. // split at whatever offset the caller chose, and expects the single "text1"
  16745. // field to come through.
  16746. static void expect_split_multipart_ok(const std::string &body1,
  16747. const std::string &body2) {
  16748. auto handled = false;
  16749. Server svr;
  16750. svr.Post("/post", [&](const Request &req, Response &) {
  16751. EXPECT_EQ(1u, req.form.fields.size());
  16752. EXPECT_EQ("text1", req.form.get_field("text1"));
  16753. handled = true;
  16754. });
  16755. auto port = svr.bind_to_any_port(HOST);
  16756. thread t = thread([&] { svr.listen_after_bind(); });
  16757. auto se = detail::scope_exit([&] {
  16758. svr.stop();
  16759. t.join();
  16760. ASSERT_FALSE(svr.is_running());
  16761. ASSERT_TRUE(handled);
  16762. });
  16763. svr.wait_until_ready();
  16764. // "Connection: close" makes the server close once it has answered, so the
  16765. // response drain ends immediately instead of idling until the read timeout.
  16766. const std::string head =
  16767. "POST /post HTTP/1.1\r\n"
  16768. "Host: localhost\r\n"
  16769. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16770. "Connection: close\r\n"
  16771. "Content-Length: " +
  16772. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16773. std::string response;
  16774. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16775. ASSERT_GE(response.size(), 12u) << "no response";
  16776. EXPECT_EQ("200", response.substr(9, 3));
  16777. }
  16778. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16779. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16780. // ignored, including when it does not arrive in the same read as the
  16781. // close-delimiter itself.
  16782. expect_split_multipart_ok("--zzzz\r\n"
  16783. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16784. "\r\n"
  16785. "text1"
  16786. "\r\n--zzzz--",
  16787. "\r\nthis epilogue must be ignored\r\n");
  16788. }
  16789. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16790. // The initial boundary may be preceded by a preamble of any length and may
  16791. // straddle a read boundary. Discarding data while waiting for it must not
  16792. // throw away a partial boundary sitting at the end of the buffer.
  16793. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16794. "zz\r\n"
  16795. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16796. "\r\n"
  16797. "text1"
  16798. "\r\n--zzzz--\r\n");
  16799. }
  16800. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16801. // The received boundary was only checked for being non-empty, so it could be
  16802. // as long as a header is allowed to be. The parser scans the body for
  16803. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16804. // costs a nearly full comparison at nearly every position, making the
  16805. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16806. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16807. Server svr;
  16808. svr.Post("/post", [](const Request &req, Response &res) {
  16809. EXPECT_EQ(1u, req.form.fields.size());
  16810. EXPECT_EQ("text1", req.form.get_field("text1"));
  16811. res.set_content("ok", "text/plain");
  16812. });
  16813. auto port = svr.bind_to_any_port(HOST);
  16814. thread t = thread([&] { svr.listen_after_bind(); });
  16815. auto se = detail::scope_exit([&] {
  16816. svr.stop();
  16817. t.join();
  16818. ASSERT_FALSE(svr.is_running());
  16819. });
  16820. svr.wait_until_ready();
  16821. Client cli(HOST, port);
  16822. auto post_with_boundary_of_length = [&](size_t len) {
  16823. const std::string boundary(len, 'a');
  16824. const std::string body =
  16825. "--" + boundary +
  16826. "\r\n"
  16827. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16828. "\r\n"
  16829. "text1"
  16830. "\r\n--" +
  16831. boundary + "--\r\n";
  16832. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16833. };
  16834. auto res = post_with_boundary_of_length(70);
  16835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16836. EXPECT_EQ(StatusCode::OK_200, res->status);
  16837. res = post_with_boundary_of_length(71);
  16838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16839. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16840. }
  16841. TEST(MakeFileBodyTest, Basic) {
  16842. const std::string file_content(4096, 'Z');
  16843. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16844. {
  16845. std::ofstream ofs(tmp_path, std::ios::binary);
  16846. ofs.write(file_content.data(),
  16847. static_cast<std::streamsize>(file_content.size()));
  16848. }
  16849. auto handled = false;
  16850. Server svr;
  16851. svr.Post("/upload", [&](const Request &req, Response &res) {
  16852. EXPECT_EQ(file_content, req.body);
  16853. handled = true;
  16854. res.status = StatusCode::OK_200;
  16855. });
  16856. auto port = svr.bind_to_any_port(HOST);
  16857. auto t = thread([&] { svr.listen_after_bind(); });
  16858. auto se = detail::scope_exit([&] {
  16859. svr.stop();
  16860. t.join();
  16861. ASSERT_FALSE(svr.is_running());
  16862. ASSERT_TRUE(handled);
  16863. std::remove(tmp_path.c_str());
  16864. });
  16865. svr.wait_until_ready();
  16866. auto fb = make_file_body(tmp_path);
  16867. ASSERT_GT(fb.first, 0u);
  16868. Client cli(HOST, port);
  16869. auto res =
  16870. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16872. EXPECT_EQ(StatusCode::OK_200, res->status);
  16873. }
  16874. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16875. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16876. {
  16877. std::ofstream ofs(path, std::ios::binary);
  16878. const std::string content(100, 'A');
  16879. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16880. }
  16881. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16882. auto body = make_file_body(path);
  16883. ASSERT_EQ(100u, body.first);
  16884. ASSERT_TRUE(static_cast<bool>(body.second));
  16885. // Rewritten shorter after its length was measured - and, on a server, after
  16886. // that length has already gone out as Content-Length.
  16887. {
  16888. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16889. const std::string content(10, 'A');
  16890. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16891. }
  16892. std::string written;
  16893. DataSink sink;
  16894. sink.write = [&](const char *d, size_t l) {
  16895. written.append(d, l);
  16896. return true;
  16897. };
  16898. // The provider has to report failure. write_content_with_progress() advances
  16899. // its offset only by what was written, so a provider that returns true
  16900. // without completing the length it promised is called again straight away,
  16901. // and again.
  16902. EXPECT_FALSE(body.second(0, body.first, sink));
  16903. EXPECT_EQ(std::string(10, 'A'), written);
  16904. }
  16905. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16906. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16907. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16908. {
  16909. std::ofstream ofs(path, std::ios::binary);
  16910. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16911. }
  16912. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16913. auto body = make_file_body(path);
  16914. ASSERT_EQ(content.size(), body.first);
  16915. ASSERT_TRUE(static_cast<bool>(body.second));
  16916. std::string written;
  16917. DataSink sink;
  16918. sink.write = [&](const char *d, size_t l) {
  16919. written.append(d, l);
  16920. return true;
  16921. };
  16922. EXPECT_TRUE(body.second(0, body.first, sink));
  16923. EXPECT_EQ(content, written);
  16924. }
  16925. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16926. static constexpr unsigned int number_of_tasks{1000000};
  16927. std::atomic_uint count{0};
  16928. std::unique_ptr<TaskQueue> task_queue{
  16929. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16930. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16931. auto queued = task_queue->enqueue(
  16932. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16933. EXPECT_TRUE(queued);
  16934. }
  16935. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16936. task_queue->shutdown();
  16937. #else
  16938. EXPECT_NO_THROW(task_queue->shutdown());
  16939. #endif
  16940. EXPECT_EQ(number_of_tasks, count.load());
  16941. }
  16942. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16943. static constexpr unsigned int number_of_tasks{1000000};
  16944. static constexpr unsigned int qlimit{2};
  16945. unsigned int queued_count{0};
  16946. std::atomic_uint count{0};
  16947. std::unique_ptr<TaskQueue> task_queue{
  16948. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16949. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16950. if (task_queue->enqueue(
  16951. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16952. queued_count++;
  16953. }
  16954. }
  16955. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16956. task_queue->shutdown();
  16957. #else
  16958. EXPECT_NO_THROW(task_queue->shutdown());
  16959. #endif
  16960. EXPECT_EQ(queued_count, count.load());
  16961. EXPECT_TRUE(queued_count <= number_of_tasks);
  16962. EXPECT_TRUE(queued_count >= qlimit);
  16963. }
  16964. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16965. // Use a short idle timeout so a dynamic thread spawns, times out and
  16966. // exits during the test, and the pool keeps working afterwards.
  16967. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16968. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16969. /*idle_timeout_sec=*/1}};
  16970. std::atomic_uint count{0};
  16971. std::condition_variable cv;
  16972. std::mutex mtx;
  16973. bool release = false;
  16974. // Block the base thread so the second task spawns a dynamic thread.
  16975. EXPECT_TRUE(task_queue->enqueue([&] {
  16976. std::unique_lock<std::mutex> lock(mtx);
  16977. while (!release) {
  16978. cv.wait(lock);
  16979. }
  16980. count++;
  16981. }));
  16982. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16983. // Let the dynamic thread finish its task and exceed the idle timeout.
  16984. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16985. {
  16986. std::unique_lock<std::mutex> lock(mtx);
  16987. release = true;
  16988. }
  16989. cv.notify_all();
  16990. // The pool must still accept and run tasks after the dynamic thread exited.
  16991. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16992. task_queue->shutdown();
  16993. EXPECT_EQ(3u, count.load());
  16994. }
  16995. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16996. static constexpr size_t number_of_tasks{32};
  16997. std::unique_ptr<TaskQueue> task_queue{
  16998. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16999. // Let the base threads go idle so the burst below finds them waiting.
  17000. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17001. std::mutex mtx;
  17002. std::condition_variable cv;
  17003. size_t running = 0;
  17004. bool release = false;
  17005. for (size_t i = 0; i < number_of_tasks; i++) {
  17006. EXPECT_TRUE(task_queue->enqueue([&] {
  17007. std::unique_lock<std::mutex> lock(mtx);
  17008. running++;
  17009. cv.notify_all();
  17010. cv.wait(lock, [&] { return release; });
  17011. }));
  17012. }
  17013. {
  17014. std::unique_lock<std::mutex> lock(mtx);
  17015. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17016. [&] { return running == number_of_tasks; }));
  17017. release = true;
  17018. }
  17019. cv.notify_all();
  17020. task_queue->shutdown();
  17021. }
  17022. TEST(TaskQueueTest, MaxQueuedRequests) {
  17023. static constexpr unsigned int qlimit{3};
  17024. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17025. std::condition_variable sem_cv;
  17026. std::mutex sem_mtx;
  17027. int credits = 0;
  17028. bool queued;
  17029. /* Fill up the queue with tasks that will block until we give them credits to
  17030. * complete. */
  17031. for (unsigned int n = 0; n <= qlimit;) {
  17032. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17033. std::unique_lock<std::mutex> lock(sem_mtx);
  17034. while (credits <= 0) {
  17035. sem_cv.wait(lock);
  17036. }
  17037. /* Consume the credit and signal the test code if they are all gone. */
  17038. if (--credits == 0) { sem_cv.notify_one(); }
  17039. });
  17040. if (n < qlimit) {
  17041. /* The first qlimit enqueues must succeed. */
  17042. EXPECT_TRUE(queued);
  17043. } else {
  17044. /* The last one will succeed only when the worker thread
  17045. * starts and dequeues the first blocking task. Although
  17046. * not necessary for the correctness of this test, we sleep for
  17047. * a short while to avoid busy waiting. */
  17048. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17049. }
  17050. if (queued) { n++; }
  17051. }
  17052. /* Further enqueues must fail since the queue is full. */
  17053. for (auto i = 0; i < 4; i++) {
  17054. queued = task_queue->enqueue([] {});
  17055. EXPECT_FALSE(queued);
  17056. }
  17057. /* Give the credits to allow the previous tasks to complete. */
  17058. {
  17059. std::unique_lock<std::mutex> lock(sem_mtx);
  17060. credits += qlimit + 1;
  17061. }
  17062. sem_cv.notify_all();
  17063. /* Wait for all the credits to be consumed. */
  17064. {
  17065. std::unique_lock<std::mutex> lock(sem_mtx);
  17066. while (credits > 0) {
  17067. sem_cv.wait(lock);
  17068. }
  17069. }
  17070. /* Check that we are able again to enqueue at least qlimit tasks. */
  17071. for (unsigned int i = 0; i < qlimit; i++) {
  17072. queued = task_queue->enqueue([] {});
  17073. EXPECT_TRUE(queued);
  17074. }
  17075. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17076. task_queue->shutdown();
  17077. #else
  17078. EXPECT_NO_THROW(task_queue->shutdown());
  17079. #endif
  17080. }
  17081. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17082. Server svr;
  17083. std::string method;
  17084. std::string body;
  17085. auto has_content_length = false;
  17086. auto has_transfer_encoding = false;
  17087. std::atomic<int> bad_requests{0};
  17088. // Leftover body bytes get parsed as a malformed request and answered with
  17089. // 400
  17090. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17091. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17092. });
  17093. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17094. res.set_redirect("/down", StatusCode::SeeOther_303);
  17095. });
  17096. svr.Get("/down", [&](const Request &req, Response &res) {
  17097. method = req.method;
  17098. body = req.body;
  17099. has_content_length = req.has_header("Content-Length");
  17100. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17101. res.set_content("ok", "text/plain");
  17102. });
  17103. auto port = svr.bind_to_any_port(HOST);
  17104. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17105. auto se = detail::scope_exit([&] {
  17106. svr.stop();
  17107. thread.join();
  17108. ASSERT_FALSE(svr.is_running());
  17109. });
  17110. svr.wait_until_ready();
  17111. const std::string payload = "SECRET-BODY";
  17112. auto check = [&](Client &cli, const Result &res) {
  17113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17114. EXPECT_EQ(StatusCode::OK_200, res->status);
  17115. EXPECT_EQ("ok", res->body);
  17116. EXPECT_EQ("GET", method);
  17117. EXPECT_TRUE(body.empty());
  17118. EXPECT_FALSE(has_content_length);
  17119. EXPECT_FALSE(has_transfer_encoding);
  17120. // Nothing of the original body may be left on the connection
  17121. auto res2 = cli.Get("/down");
  17122. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17123. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17124. EXPECT_EQ("ok", res2->body);
  17125. EXPECT_EQ(0, bad_requests);
  17126. };
  17127. // With content length
  17128. {
  17129. Client cli(HOST, port);
  17130. cli.set_keep_alive(true);
  17131. cli.set_follow_location(true);
  17132. auto res = cli.Post(
  17133. "/up", payload.size(),
  17134. [&](size_t offset, size_t length, DataSink &sink) {
  17135. return sink.write(payload.data() + offset, length);
  17136. },
  17137. "text/plain");
  17138. check(cli, res);
  17139. }
  17140. // Without content length (chunked)
  17141. {
  17142. Client cli(HOST, port);
  17143. cli.set_keep_alive(true);
  17144. cli.set_follow_location(true);
  17145. auto res = cli.Post(
  17146. "/up",
  17147. [&](size_t /*offset*/, DataSink &sink) {
  17148. sink.write(payload.data(), payload.size());
  17149. sink.done();
  17150. return true;
  17151. },
  17152. "text/plain");
  17153. check(cli, res);
  17154. }
  17155. }
  17156. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17157. Server svr;
  17158. std::string target;
  17159. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17160. // Echo the still-encoded name back in the Location
  17161. const std::string prefix = "/start/";
  17162. res.status = StatusCode::Found_302;
  17163. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17164. });
  17165. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17166. target = req.target;
  17167. res.set_content("ok", "text/plain");
  17168. });
  17169. auto port = svr.bind_to_any_port(HOST);
  17170. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17171. auto se = detail::scope_exit([&] {
  17172. svr.stop();
  17173. thread.join();
  17174. ASSERT_FALSE(svr.is_running());
  17175. });
  17176. svr.wait_until_ready();
  17177. // Decoding the Location path would turn the first four into a path
  17178. // separator, a query delimiter, a fragment delimiter and a different
  17179. // percent-encoded octet. The rest must keep reaching the server as they are.
  17180. const std::vector<std::string> names = {
  17181. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17182. };
  17183. for (auto path_encode : {true, false}) {
  17184. Client cli(HOST, port);
  17185. cli.set_follow_location(true);
  17186. cli.set_path_encode(path_encode);
  17187. for (const auto &name : names) {
  17188. target.clear();
  17189. auto res = cli.Get("/start/" + name);
  17190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17191. EXPECT_EQ(StatusCode::OK_200, res->status);
  17192. EXPECT_EQ("/dest/" + name, target);
  17193. }
  17194. }
  17195. }
  17196. TEST(RedirectTest, NotModifiedIsReturned) {
  17197. Server svr;
  17198. svr.Get("/cached", [](const Request &, Response &res) {
  17199. res.status = StatusCode::NotModified_304;
  17200. });
  17201. auto port = svr.bind_to_any_port(HOST);
  17202. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17203. auto se = detail::scope_exit([&] {
  17204. svr.stop();
  17205. thread.join();
  17206. ASSERT_FALSE(svr.is_running());
  17207. });
  17208. svr.wait_until_ready();
  17209. Client cli(HOST, port);
  17210. cli.set_follow_location(true);
  17211. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17213. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17214. }
  17215. TEST(RedirectTest, NoLocationIsReturned) {
  17216. Server svr;
  17217. svr.Get("/no-location", [](const Request &, Response &res) {
  17218. res.status = StatusCode::Found_302;
  17219. res.set_content("no location", "text/plain");
  17220. });
  17221. auto port = svr.bind_to_any_port(HOST);
  17222. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17223. auto se = detail::scope_exit([&] {
  17224. svr.stop();
  17225. thread.join();
  17226. ASSERT_FALSE(svr.is_running());
  17227. });
  17228. svr.wait_until_ready();
  17229. Client cli(HOST, port);
  17230. cli.set_follow_location(true);
  17231. auto res = cli.Get("/no-location");
  17232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17233. EXPECT_EQ(StatusCode::Found_302, res->status);
  17234. EXPECT_EQ("no location", res->body);
  17235. // The callbacks see the body of the response that is returned
  17236. auto handler_called = false;
  17237. auto progress_called = false;
  17238. std::string body;
  17239. auto res2 = cli.Get(
  17240. "/no-location",
  17241. [&](const Response &) {
  17242. handler_called = true;
  17243. return true;
  17244. },
  17245. [&](const char *data, size_t data_length) {
  17246. body.append(data, data_length);
  17247. return true;
  17248. },
  17249. [&](size_t, size_t) {
  17250. progress_called = true;
  17251. return true;
  17252. });
  17253. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17254. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17255. EXPECT_TRUE(handler_called);
  17256. EXPECT_TRUE(progress_called);
  17257. EXPECT_EQ("no location", body);
  17258. }
  17259. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17260. Server svr;
  17261. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17262. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17263. });
  17264. svr.Get("/hello", [](const Request &req, Response &res) {
  17265. res.set_content(req.get_param_value("key"), "text/plain");
  17266. });
  17267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17268. auto se = detail::scope_exit([&] {
  17269. svr.stop();
  17270. thread.join();
  17271. ASSERT_FALSE(svr.is_running());
  17272. });
  17273. svr.wait_until_ready();
  17274. {
  17275. Client cli(HOST, PORT);
  17276. cli.set_follow_location(true);
  17277. auto res = cli.Get("/");
  17278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17279. EXPECT_EQ(StatusCode::OK_200, res->status);
  17280. EXPECT_EQ("val&key2=val2", res->body);
  17281. }
  17282. }
  17283. #endif
  17284. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17285. Server svr;
  17286. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17287. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17288. });
  17289. svr.Get("/hello", [](const Request &req, Response &res) {
  17290. res.set_content(req.get_param_value("key"), "text/plain");
  17291. });
  17292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17293. auto se = detail::scope_exit([&] {
  17294. svr.stop();
  17295. thread.join();
  17296. ASSERT_FALSE(svr.is_running());
  17297. });
  17298. svr.wait_until_ready();
  17299. {
  17300. Client cli(HOST, PORT);
  17301. cli.set_follow_location(true);
  17302. auto res = cli.Get("/");
  17303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17304. EXPECT_EQ(StatusCode::OK_200, res->status);
  17305. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17306. }
  17307. }
  17308. TEST(RedirectTest, RedirectWithPlusInPath) {
  17309. Server svr;
  17310. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17311. res.set_redirect("/a+b");
  17312. });
  17313. // Route pattern uses regex; escape + as \\+
  17314. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17315. res.set_content(req.path, "text/plain");
  17316. });
  17317. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17318. auto se = detail::scope_exit([&] {
  17319. svr.stop();
  17320. thread.join();
  17321. ASSERT_FALSE(svr.is_running());
  17322. });
  17323. svr.wait_until_ready();
  17324. {
  17325. Client cli(HOST, PORT);
  17326. cli.set_follow_location(true);
  17327. auto res = cli.Get("/");
  17328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17329. EXPECT_EQ(StatusCode::OK_200, res->status);
  17330. EXPECT_EQ("/a+b", res->body);
  17331. }
  17332. }
  17333. TEST(RedirectTest, ResolveRelativeLocation) {
  17334. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17335. const std::vector<std::pair<std::string, std::string>> cases = {
  17336. {"g", "/b/c/g"},
  17337. {"./g", "/b/c/g"},
  17338. {"g/", "/b/c/g/"},
  17339. {"?y", "/b/c/d;p?y"},
  17340. {"g?y", "/b/c/g?y"},
  17341. {"#s", "/b/c/d;p?q#s"},
  17342. {"g#s", "/b/c/g#s"},
  17343. {"g?y#s", "/b/c/g?y#s"},
  17344. {";x", "/b/c/;x"},
  17345. {"g;x", "/b/c/g;x"},
  17346. {".", "/b/c/"},
  17347. {"./", "/b/c/"},
  17348. {"..", "/b/"},
  17349. {"../", "/b/"},
  17350. {"../g", "/b/g"},
  17351. {"../..", "/"},
  17352. {"../../", "/"},
  17353. {"../../g", "/g"},
  17354. {"../../../g", "/g"},
  17355. {"g.", "/b/c/g."},
  17356. {".g", "/b/c/.g"},
  17357. {"g..", "/b/c/g.."},
  17358. {"..g", "/b/c/..g"},
  17359. {"./../g", "/b/g"},
  17360. {"./g/.", "/b/c/g/"},
  17361. {"g/./h", "/b/c/g/h"},
  17362. {"g/../h", "/b/c/h"},
  17363. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17364. {"g;x=1/../y", "/b/c/y"},
  17365. {"g?y/./x", "/b/c/g?y/./x"},
  17366. {"g#s/../x", "/b/c/g#s/../x"},
  17367. // Not relative-path references, so left for parse_url.
  17368. {"/g", "/g"},
  17369. {"//g", "//g"},
  17370. {"http://g/x", "http://g/x"},
  17371. {"g:h", "g:h"},
  17372. };
  17373. for (const auto &c : cases) {
  17374. EXPECT_EQ(c.second,
  17375. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17376. << c.first;
  17377. }
  17378. }
  17379. TEST(RedirectTest, RemoveDotSegments) {
  17380. // RFC 3986 section 5.2.4
  17381. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17382. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17383. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17384. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17385. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17386. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17387. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17388. }
  17389. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17390. Server svr;
  17391. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17392. res.set_redirect("/dir/../target?x=1");
  17393. });
  17394. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17395. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17396. "/dir/./../target");
  17397. });
  17398. svr.Get("/target", [](const Request &req, Response &res) {
  17399. res.set_content(req.path, "text/plain");
  17400. });
  17401. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17402. auto se = detail::scope_exit([&] {
  17403. svr.stop();
  17404. th.join();
  17405. ASSERT_FALSE(svr.is_running());
  17406. });
  17407. svr.wait_until_ready();
  17408. Client cli("localhost", PORT);
  17409. cli.set_follow_location(true);
  17410. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17411. auto res = cli.Get(path);
  17412. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17413. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17414. EXPECT_EQ("/target", res->body) << path;
  17415. }
  17416. }
  17417. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17418. Server svr;
  17419. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17420. res.set_redirect(req.get_param_value("to"));
  17421. });
  17422. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17423. res.set_content(req.target, "text/plain");
  17424. });
  17425. svr.Get("/other", [](const Request &req, Response &res) {
  17426. res.set_content(req.target, "text/plain");
  17427. });
  17428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17429. auto se = detail::scope_exit([&] {
  17430. svr.stop();
  17431. thread.join();
  17432. ASSERT_FALSE(svr.is_running());
  17433. });
  17434. svr.wait_until_ready();
  17435. const std::vector<std::pair<std::string, std::string>> cases = {
  17436. {"next", "/dir/next"},
  17437. {"./next?x=1", "/dir/next?x=1"},
  17438. {"../other", "/other"},
  17439. };
  17440. for (const auto &c : cases) {
  17441. Client cli(HOST, PORT);
  17442. cli.set_follow_location(true);
  17443. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17444. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17445. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17446. EXPECT_EQ(c.second, res->body) << c.first;
  17447. }
  17448. }
  17449. #ifdef CPPHTTPLIB_SSL_ENABLED
  17450. TEST(RedirectTest, Issue2185_Online) {
  17451. SSLClient client("github.com");
  17452. client.set_follow_location(true);
  17453. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17454. "Coollab-Windows.zip");
  17455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17456. EXPECT_EQ(StatusCode::OK_200, res->status);
  17457. EXPECT_EQ(9920427U, res->body.size());
  17458. }
  17459. #endif
  17460. TEST(VulnerabilityTest, CRLFInjection) {
  17461. Server svr;
  17462. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17463. res.set_content("Hello 1", "text/plain");
  17464. });
  17465. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17466. res.set_content("Hello 2", "text/plain");
  17467. });
  17468. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17469. res.set_content("Hello 3", "text/plain");
  17470. });
  17471. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17472. res.set_content("Hello 4", "text/plain");
  17473. });
  17474. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17475. for (const auto &x : req.headers) {
  17476. auto key = x.first;
  17477. EXPECT_STRNE("evil", key.c_str());
  17478. }
  17479. });
  17480. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17481. auto se = detail::scope_exit([&] {
  17482. svr.stop();
  17483. thread.join();
  17484. ASSERT_FALSE(svr.is_running());
  17485. });
  17486. svr.wait_until_ready();
  17487. {
  17488. Client cli(HOST, PORT);
  17489. cli.Post("/test1", "A=B",
  17490. "application/x-www-form-urlencoded\r\nevil: hello1");
  17491. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17492. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17493. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17494. }
  17495. }
  17496. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17497. auto server_thread = std::thread([] {
  17498. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17499. default_socket_options(srv);
  17500. sockaddr_in addr{};
  17501. addr.sin_family = AF_INET;
  17502. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17503. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17504. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17505. ::listen(srv, 1);
  17506. sockaddr_in cli_addr{};
  17507. socklen_t cli_len = sizeof(cli_addr);
  17508. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17509. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17510. std::string buf_all;
  17511. char buf[2048];
  17512. ssize_t n;
  17513. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17514. buf_all.append(buf, static_cast<size_t>(n));
  17515. size_t pos;
  17516. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17517. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17518. auto e = request_block.find("\r\n");
  17519. if (e != std::string::npos) {
  17520. auto request_line = request_block.substr(0, e);
  17521. std::string msg =
  17522. "CRLF injection detected in request line: '" + request_line + "'";
  17523. EXPECT_FALSE(true) << msg;
  17524. }
  17525. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17526. ::send(cli,
  17527. #ifdef _WIN32
  17528. static_cast<const char *>(resp.c_str()),
  17529. static_cast<int>(resp.size()),
  17530. #else
  17531. resp.c_str(), resp.size(),
  17532. #endif
  17533. 0);
  17534. buf_all.erase(0, pos + 4);
  17535. }
  17536. }
  17537. detail::close_socket(cli);
  17538. detail::close_socket(srv);
  17539. });
  17540. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17541. auto cli = Client("127.0.0.1", PORT + 1);
  17542. auto headers = Headers{
  17543. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17544. {"Connection", "keep-alive"}};
  17545. auto res = cli.Get("/hi", headers);
  17546. EXPECT_FALSE(res);
  17547. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17548. server_thread.join();
  17549. }
  17550. // A request rejected before any byte reaches the socket must fail right away
  17551. // instead of waiting for a response the server will never send.
  17552. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17553. // The kernel completes the TCP handshake from the listen backlog, so the
  17554. // client connects, but nothing ever reads, responds or closes.
  17555. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17556. default_socket_options(srv);
  17557. sockaddr_in addr{};
  17558. addr.sin_family = AF_INET;
  17559. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17560. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17561. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17562. ASSERT_EQ(0, ::listen(srv, 8));
  17563. auto cli = Client("127.0.0.1", PORT + 1);
  17564. cli.set_read_timeout(10, 0);
  17565. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17566. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17567. std::chrono::steady_clock::now() - start)
  17568. .count();
  17569. };
  17570. {
  17571. Request req;
  17572. req.method = "GE T";
  17573. req.path = "/";
  17574. auto start = std::chrono::steady_clock::now();
  17575. auto res = cli.send(req);
  17576. EXPECT_FALSE(res);
  17577. EXPECT_EQ(Error::Write, res.error());
  17578. EXPECT_LT(elapsed_ms(start), 1000);
  17579. }
  17580. {
  17581. auto start = std::chrono::steady_clock::now();
  17582. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17583. EXPECT_FALSE(res);
  17584. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17585. EXPECT_LT(elapsed_ms(start), 1000);
  17586. }
  17587. EXPECT_FALSE(cli.is_socket_open());
  17588. detail::close_socket(srv);
  17589. }
  17590. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17591. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17592. default_socket_options(srv);
  17593. sockaddr_in addr{};
  17594. addr.sin_family = AF_INET;
  17595. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17596. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17597. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17598. ASSERT_EQ(0, ::listen(srv, 1));
  17599. std::string received;
  17600. auto server_thread = std::thread([&] {
  17601. auto sock = ::accept(srv, nullptr, nullptr);
  17602. if (sock == INVALID_SOCKET) { return; }
  17603. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17604. char buf[2048];
  17605. ssize_t n;
  17606. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17607. received.append(buf, static_cast<size_t>(n));
  17608. }
  17609. detail::close_socket(sock);
  17610. });
  17611. {
  17612. auto cli = Client("127.0.0.1", PORT + 1);
  17613. // "Z" sorts after the default headers, so writing straight to the socket
  17614. // would have sent the request line and those headers before the rejection.
  17615. auto handle =
  17616. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17617. EXPECT_FALSE(handle.is_valid());
  17618. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17619. }
  17620. server_thread.join();
  17621. detail::close_socket(srv);
  17622. EXPECT_TRUE(received.empty()) << received;
  17623. }
  17624. TEST(PathParamsTest, StaticMatch) {
  17625. const auto pattern = "/users/all";
  17626. detail::PathParamsMatcher matcher(pattern);
  17627. Request request;
  17628. request.path = "/users/all";
  17629. ASSERT_TRUE(matcher.match(request));
  17630. std::unordered_map<std::string, std::string> expected_params = {};
  17631. EXPECT_EQ(request.path_params, expected_params);
  17632. }
  17633. TEST(PathParamsTest, StaticMismatch) {
  17634. const auto pattern = "/users/all";
  17635. detail::PathParamsMatcher matcher(pattern);
  17636. Request request;
  17637. request.path = "/users/1";
  17638. ASSERT_FALSE(matcher.match(request));
  17639. }
  17640. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17641. const auto pattern = "/users/:id/subscriptions";
  17642. detail::PathParamsMatcher matcher(pattern);
  17643. Request request;
  17644. request.path = "/users/42/subscriptions";
  17645. ASSERT_TRUE(matcher.match(request));
  17646. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17647. EXPECT_EQ(request.path_params, expected_params);
  17648. }
  17649. TEST(PathParamsTest, SingleParamInTheEnd) {
  17650. const auto pattern = "/users/:id";
  17651. detail::PathParamsMatcher matcher(pattern);
  17652. Request request;
  17653. request.path = "/users/24";
  17654. ASSERT_TRUE(matcher.match(request));
  17655. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17656. EXPECT_EQ(request.path_params, expected_params);
  17657. }
  17658. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17659. const auto pattern = "/users/:id/";
  17660. detail::PathParamsMatcher matcher(pattern);
  17661. Request request;
  17662. request.path = "/users/42/";
  17663. ASSERT_TRUE(matcher.match(request));
  17664. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17665. EXPECT_EQ(request.path_params, expected_params);
  17666. }
  17667. TEST(PathParamsTest, EmptyParam) {
  17668. const auto pattern = "/users/:id/";
  17669. detail::PathParamsMatcher matcher(pattern);
  17670. Request request;
  17671. request.path = "/users//";
  17672. ASSERT_TRUE(matcher.match(request));
  17673. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17674. EXPECT_EQ(request.path_params, expected_params);
  17675. }
  17676. TEST(PathParamsTest, FragmentMismatch) {
  17677. const auto pattern = "/users/:id/";
  17678. detail::PathParamsMatcher matcher(pattern);
  17679. Request request;
  17680. request.path = "/admins/24/";
  17681. ASSERT_FALSE(matcher.match(request));
  17682. }
  17683. TEST(PathParamsTest, ExtraFragments) {
  17684. const auto pattern = "/users/:id";
  17685. detail::PathParamsMatcher matcher(pattern);
  17686. Request request;
  17687. request.path = "/users/42/subscriptions";
  17688. ASSERT_FALSE(matcher.match(request));
  17689. }
  17690. TEST(PathParamsTest, MissingTrailingParam) {
  17691. const auto pattern = "/users/:id";
  17692. detail::PathParamsMatcher matcher(pattern);
  17693. Request request;
  17694. request.path = "/users";
  17695. ASSERT_FALSE(matcher.match(request));
  17696. }
  17697. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17698. const auto pattern = "/users/:id/subscriptions";
  17699. detail::PathParamsMatcher matcher(pattern);
  17700. Request request;
  17701. request.path = "/users/subscriptions";
  17702. ASSERT_FALSE(matcher.match(request));
  17703. }
  17704. TEST(PathParamsTest, MultipleParams) {
  17705. const auto pattern = "/users/:userid/subscriptions/:subid";
  17706. detail::PathParamsMatcher matcher(pattern);
  17707. Request request;
  17708. request.path = "/users/42/subscriptions/2";
  17709. ASSERT_TRUE(matcher.match(request));
  17710. std::unordered_map<std::string, std::string> expected_params = {
  17711. {"userid", "42"}, {"subid", "2"}};
  17712. EXPECT_EQ(request.path_params, expected_params);
  17713. }
  17714. TEST(PathParamsTest, SequenceOfParams) {
  17715. const auto pattern = "/values/:x/:y/:z";
  17716. detail::PathParamsMatcher matcher(pattern);
  17717. Request request;
  17718. request.path = "/values/1/2/3";
  17719. ASSERT_TRUE(matcher.match(request));
  17720. std::unordered_map<std::string, std::string> expected_params = {
  17721. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17722. EXPECT_EQ(request.path_params, expected_params);
  17723. }
  17724. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17725. const auto pattern = "/prefix:suffix";
  17726. detail::PathParamsMatcher matcher(pattern);
  17727. Request request;
  17728. request.path = "/prefix:suffix";
  17729. ASSERT_TRUE(matcher.match(request));
  17730. const std::unordered_map<std::string, std::string> expected_params = {};
  17731. EXPECT_EQ(request.path_params, expected_params);
  17732. }
  17733. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17734. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17735. // calling thread's stack on a long enough path for a quantified pattern;
  17736. // RegexMatcher must refuse to run regex matching on paths beyond
  17737. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17738. detail::RegexMatcher matcher("/files/(.*)");
  17739. Request within_limit;
  17740. within_limit.path = "/files/" + std::string(10, 'A');
  17741. EXPECT_TRUE(matcher.match(within_limit));
  17742. Request over_limit;
  17743. over_limit.path =
  17744. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17745. EXPECT_FALSE(matcher.match(over_limit));
  17746. }
  17747. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17748. Server svr;
  17749. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17750. res.set_content("ok", "text/plain");
  17751. });
  17752. auto port = svr.bind_to_any_port(HOST);
  17753. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17754. auto se = detail::scope_exit([&] {
  17755. svr.stop();
  17756. thread.join();
  17757. ASSERT_FALSE(svr.is_running());
  17758. });
  17759. svr.wait_until_ready();
  17760. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17761. // request URI limit; this used to be able to crash the process.
  17762. std::string path =
  17763. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17764. std::string req = "GET " + path +
  17765. " HTTP/1.1\r\n"
  17766. "Host: " +
  17767. std::string(HOST) + ":" + std::to_string(port) +
  17768. "\r\n"
  17769. "Connection: close\r\n"
  17770. "\r\n";
  17771. std::string response;
  17772. ASSERT_TRUE(send_request(5, req, &response, port));
  17773. EXPECT_NE(std::string::npos, response.find("404"));
  17774. }
  17775. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17776. Server svr;
  17777. auto handler = [](const Request & /*req*/, Response &res) {
  17778. res.set_content("hit", "text/plain");
  17779. };
  17780. // No regex metacharacter, so this one is compared literally
  17781. svr.Get("/literal/route", handler);
  17782. // '.' is a regex metacharacter, so this one must keep regex semantics
  17783. svr.Get("/a.c", handler);
  17784. auto port = svr.bind_to_any_port(HOST);
  17785. std::thread t([&]() { svr.listen_after_bind(); });
  17786. auto se = detail::scope_exit([&] {
  17787. svr.stop();
  17788. t.join();
  17789. ASSERT_FALSE(svr.is_running());
  17790. });
  17791. svr.wait_until_ready();
  17792. Client cli(HOST, port);
  17793. struct {
  17794. const char *path;
  17795. int status;
  17796. } cases[] = {
  17797. {"/literal/route", StatusCode::OK_200},
  17798. {"/literal/routes", StatusCode::NotFound_404},
  17799. {"/literal/rout", StatusCode::NotFound_404},
  17800. {"/abc", StatusCode::OK_200},
  17801. {"/a.c", StatusCode::OK_200},
  17802. };
  17803. for (const auto &x : cases) {
  17804. auto res = cli.Get(x.path);
  17805. ASSERT_TRUE(res) << x.path;
  17806. EXPECT_EQ(x.status, res->status) << x.path;
  17807. }
  17808. }
  17809. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17810. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17811. // from exhausting the stack, so it must only constrain routes that actually
  17812. // run a regular expression. A literal route is matched by comparison and
  17813. // stays usable at any length.
  17814. Server svr;
  17815. const std::string pattern =
  17816. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17817. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17818. res.set_content("hit", "text/plain");
  17819. });
  17820. auto port = svr.bind_to_any_port(HOST);
  17821. std::thread t([&]() { svr.listen_after_bind(); });
  17822. auto se = detail::scope_exit([&] {
  17823. svr.stop();
  17824. t.join();
  17825. ASSERT_FALSE(svr.is_running());
  17826. });
  17827. svr.wait_until_ready();
  17828. Client cli(HOST, port);
  17829. auto res = cli.Get(pattern);
  17830. ASSERT_TRUE(res);
  17831. EXPECT_EQ(StatusCode::OK_200, res->status);
  17832. }
  17833. TEST(ParseUrlTest, VariousPatterns) {
  17834. {
  17835. detail::UrlComponents uc;
  17836. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17837. EXPECT_EQ("http", uc.scheme);
  17838. EXPECT_EQ("example.com", uc.host);
  17839. EXPECT_EQ("8080", uc.port);
  17840. EXPECT_EQ("/path", uc.path);
  17841. EXPECT_EQ("?q=1", uc.query);
  17842. }
  17843. {
  17844. detail::UrlComponents uc;
  17845. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17846. EXPECT_EQ("https", uc.scheme);
  17847. EXPECT_EQ("example.com", uc.host);
  17848. EXPECT_TRUE(uc.port.empty());
  17849. EXPECT_EQ("/path", uc.path);
  17850. }
  17851. {
  17852. detail::UrlComponents uc;
  17853. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17854. EXPECT_EQ("::1", uc.host);
  17855. EXPECT_EQ("8080", uc.port);
  17856. EXPECT_EQ("/path", uc.path);
  17857. }
  17858. {
  17859. detail::UrlComponents uc;
  17860. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17861. }
  17862. {
  17863. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17864. // the path while the connection still targets the bracketed host.
  17865. detail::UrlComponents uc;
  17866. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17867. }
  17868. {
  17869. detail::UrlComponents uc;
  17870. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17871. }
  17872. {
  17873. detail::UrlComponents uc;
  17874. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17875. EXPECT_EQ("::1", uc.host);
  17876. EXPECT_TRUE(uc.port.empty());
  17877. EXPECT_EQ("/path", uc.path);
  17878. }
  17879. {
  17880. detail::UrlComponents uc;
  17881. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17882. EXPECT_TRUE(uc.scheme.empty());
  17883. EXPECT_EQ("example.com", uc.host);
  17884. EXPECT_EQ("/path", uc.path);
  17885. EXPECT_EQ("?q=1", uc.query);
  17886. }
  17887. {
  17888. detail::UrlComponents uc;
  17889. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17890. EXPECT_TRUE(uc.host.empty());
  17891. EXPECT_EQ("/path", uc.path);
  17892. EXPECT_EQ("?q=1", uc.query);
  17893. }
  17894. {
  17895. detail::UrlComponents uc;
  17896. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17897. EXPECT_EQ("example.com", uc.host);
  17898. EXPECT_EQ("8080", uc.port);
  17899. }
  17900. {
  17901. // Unix socket path — must not be parsed as host
  17902. detail::UrlComponents uc;
  17903. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17904. EXPECT_TRUE(uc.host.empty());
  17905. }
  17906. {
  17907. detail::UrlComponents uc;
  17908. ASSERT_TRUE(detail::parse_url("", uc));
  17909. EXPECT_TRUE(uc.host.empty());
  17910. EXPECT_TRUE(uc.path.empty());
  17911. }
  17912. {
  17913. detail::UrlComponents uc;
  17914. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17915. }
  17916. {
  17917. detail::UrlComponents uc;
  17918. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17919. }
  17920. {
  17921. // Accepted by parse_url; callers restrict to http/https
  17922. detail::UrlComponents uc;
  17923. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17924. EXPECT_EQ("ftp", uc.scheme);
  17925. }
  17926. {
  17927. detail::UrlComponents uc;
  17928. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17929. }
  17930. {
  17931. detail::UrlComponents uc;
  17932. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17933. }
  17934. }
  17935. TEST(ParseUrlTest, FragmentHandling) {
  17936. {
  17937. detail::UrlComponents uc;
  17938. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17939. EXPECT_EQ("/path", uc.path);
  17940. EXPECT_TRUE(uc.query.empty());
  17941. }
  17942. {
  17943. detail::UrlComponents uc;
  17944. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17945. EXPECT_TRUE(uc.path.empty());
  17946. EXPECT_TRUE(uc.query.empty());
  17947. }
  17948. }
  17949. TEST(ParseUrlTest, UserinfoHandling) {
  17950. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17951. // parsers would see evil.com as the host.
  17952. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17953. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17954. for (auto url : urls) {
  17955. detail::UrlComponents uc;
  17956. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17957. }
  17958. }
  17959. TEST(ParseUrlTest, IPv6EdgeCases) {
  17960. {
  17961. detail::UrlComponents uc;
  17962. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17963. EXPECT_TRUE(uc.scheme.empty());
  17964. EXPECT_EQ("::1", uc.host);
  17965. EXPECT_EQ("8080", uc.port);
  17966. }
  17967. {
  17968. // Zone ID '%25' is not in [a-fA-F0-9:]
  17969. detail::UrlComponents uc;
  17970. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17971. }
  17972. }
  17973. TEST(ParseUrlTest, SchemeEdgeCases) {
  17974. {
  17975. detail::UrlComponents uc;
  17976. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17977. }
  17978. {
  17979. detail::UrlComponents uc;
  17980. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17981. }
  17982. {
  17983. detail::UrlComponents uc;
  17984. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17985. }
  17986. }
  17987. TEST(ParseUrlTest, PortEdgeCases) {
  17988. {
  17989. detail::UrlComponents uc;
  17990. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17991. EXPECT_TRUE(uc.port.empty());
  17992. EXPECT_EQ("/path", uc.path);
  17993. }
  17994. {
  17995. // parse_url accepts any port string; validation is done by parse_port
  17996. detail::UrlComponents uc;
  17997. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17998. EXPECT_EQ("abc", uc.port);
  17999. }
  18000. }
  18001. TEST(ParseUrlTest, WebSocketPatterns) {
  18002. {
  18003. detail::UrlComponents uc;
  18004. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18005. EXPECT_EQ("ws", uc.scheme);
  18006. EXPECT_EQ("echo.example.com", uc.host);
  18007. EXPECT_EQ("8080", uc.port);
  18008. EXPECT_EQ("/ws", uc.path);
  18009. }
  18010. {
  18011. detail::UrlComponents uc;
  18012. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18013. EXPECT_EQ("wss", uc.scheme);
  18014. EXPECT_EQ("echo.example.com", uc.host);
  18015. EXPECT_TRUE(uc.port.empty());
  18016. EXPECT_EQ("/ws", uc.path);
  18017. }
  18018. }
  18019. TEST(ParseUrlTest, QueryOnly) {
  18020. detail::UrlComponents uc;
  18021. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18022. EXPECT_TRUE(uc.host.empty());
  18023. EXPECT_TRUE(uc.path.empty());
  18024. EXPECT_EQ("?q=1&r=2", uc.query);
  18025. }
  18026. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18027. detail::UrlComponents uc;
  18028. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18029. EXPECT_TRUE(uc.scheme.empty());
  18030. EXPECT_EQ("example.com", uc.host);
  18031. EXPECT_EQ("443", uc.port);
  18032. EXPECT_EQ("/path", uc.path);
  18033. }
  18034. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18035. // If ipv6 regex working, regex match codepath is taken.
  18036. // else port will default to 80 in Client impl
  18037. int clientImplMagicPort = 80;
  18038. int port = 4321;
  18039. // above ports must be different to avoid false negative
  18040. EXPECT_NE(clientImplMagicPort, port);
  18041. std::string ipV6TestURL = "http://[ff06::c3]";
  18042. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18043. CLIENT_PRIVATE_KEY_FILE);
  18044. EXPECT_EQ(cli.port(), port);
  18045. }
  18046. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18047. auto file_path = "./www/dir/index.html";
  18048. auto dir_path = "./www/dir";
  18049. detail::FileStat stat_file(file_path);
  18050. EXPECT_TRUE(stat_file.is_file());
  18051. EXPECT_FALSE(stat_file.is_dir());
  18052. detail::FileStat stat_dir(dir_path);
  18053. EXPECT_FALSE(stat_dir.is_file());
  18054. EXPECT_TRUE(stat_dir.is_dir());
  18055. }
  18056. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18057. // IPv4 with default HTTP port (80)
  18058. EXPECT_EQ("example.com",
  18059. detail::make_host_and_port_string("example.com", 80, false));
  18060. // IPv4 with default HTTPS port (443)
  18061. EXPECT_EQ("example.com",
  18062. detail::make_host_and_port_string("example.com", 443, true));
  18063. // IPv4 with non-default HTTP port
  18064. EXPECT_EQ("example.com:8080",
  18065. detail::make_host_and_port_string("example.com", 8080, false));
  18066. // IPv4 with non-default HTTPS port
  18067. EXPECT_EQ("example.com:8443",
  18068. detail::make_host_and_port_string("example.com", 8443, true));
  18069. // IPv6 with default HTTP port (80)
  18070. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18071. // IPv6 with default HTTPS port (443)
  18072. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18073. // IPv6 with non-default HTTP port
  18074. EXPECT_EQ("[::1]:8080",
  18075. detail::make_host_and_port_string("::1", 8080, false));
  18076. // IPv6 with non-default HTTPS port
  18077. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18078. // IPv6 full address with default port
  18079. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18080. detail::make_host_and_port_string(
  18081. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18082. // IPv6 full address with non-default port
  18083. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18084. detail::make_host_and_port_string(
  18085. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18086. // IPv6 localhost with non-default port
  18087. EXPECT_EQ("[::1]:3000",
  18088. detail::make_host_and_port_string("::1", 3000, false));
  18089. // IPv6 with zone ID (link-local address) with default port
  18090. EXPECT_EQ("[fe80::1%eth0]",
  18091. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18092. // IPv6 with zone ID (link-local address) with non-default port
  18093. EXPECT_EQ("[fe80::1%eth0]:8080",
  18094. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18095. // Edge case: Port 443 with is_ssl=false (should add port)
  18096. EXPECT_EQ("example.com:443",
  18097. detail::make_host_and_port_string("example.com", 443, false));
  18098. // Edge case: Port 80 with is_ssl=true (should add port)
  18099. EXPECT_EQ("example.com:80",
  18100. detail::make_host_and_port_string("example.com", 80, true));
  18101. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18102. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18103. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18104. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18105. // Security fix: Already bracketed IPv6 should not get double brackets
  18106. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18107. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18108. EXPECT_EQ("[::1]:8080",
  18109. detail::make_host_and_port_string("[::1]", 8080, false));
  18110. EXPECT_EQ("[2001:db8::1]:8080",
  18111. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18112. EXPECT_EQ("[fe80::1%eth0]",
  18113. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18114. EXPECT_EQ("[fe80::1%eth0]:8080",
  18115. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18116. // Edge case: Empty host (should return as-is)
  18117. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18118. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18119. // This is a known limitation but shouldn't crash
  18120. EXPECT_EQ("[host:name]",
  18121. detail::make_host_and_port_string("host:name", 80, false));
  18122. // Port number edge cases (no validation, but should not crash)
  18123. EXPECT_EQ("example.com:0",
  18124. detail::make_host_and_port_string("example.com", 0, false));
  18125. EXPECT_EQ("example.com:-1",
  18126. detail::make_host_and_port_string("example.com", -1, false));
  18127. EXPECT_EQ("example.com:65535",
  18128. detail::make_host_and_port_string("example.com", 65535, false));
  18129. EXPECT_EQ("example.com:65536",
  18130. detail::make_host_and_port_string("example.com", 65536, false));
  18131. }
  18132. #ifdef CPPHTTPLIB_SSL_ENABLED
  18133. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18134. httplib::SSLClient cli("roblox.com", 443);
  18135. cli.set_follow_location(true);
  18136. auto res = cli.Get("/");
  18137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18138. EXPECT_EQ(StatusCode::OK_200, res->status);
  18139. }
  18140. #endif
  18141. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18142. Server svr;
  18143. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18144. EXPECT_EQ(res.status, 400);
  18145. });
  18146. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18147. auto se = detail::scope_exit([&] {
  18148. svr.stop();
  18149. thread.join();
  18150. ASSERT_FALSE(svr.is_running());
  18151. });
  18152. svr.wait_until_ready();
  18153. Client cli(HOST, PORT);
  18154. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18155. }
  18156. TEST(InvalidHeaderCharsTest, is_field_name) {
  18157. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18158. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18159. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18160. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18161. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18162. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18163. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18164. EXPECT_FALSE(detail::fields::is_field_name(""));
  18165. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18166. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18167. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18168. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18169. }
  18170. TEST(InvalidHeaderCharsTest, is_field_value) {
  18171. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18172. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18173. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18174. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18175. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18176. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18177. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18178. EXPECT_TRUE(detail::fields::is_field_value(""));
  18179. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18180. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18181. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18182. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18183. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18184. }
  18185. TEST(InvalidHeaderCharsTest, OnServer) {
  18186. Server svr;
  18187. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18188. std::string header = "Not Set";
  18189. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18190. res.set_header(header, "value");
  18191. res.set_content("Page Content Page Content", "text/plain");
  18192. });
  18193. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18194. std::string header = "Not Set";
  18195. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18196. res.set_header("X-Test", header);
  18197. res.set_content("Page Content Page Content", "text/plain");
  18198. });
  18199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18200. auto se = detail::scope_exit([&] {
  18201. svr.stop();
  18202. thread.join();
  18203. ASSERT_FALSE(svr.is_running());
  18204. });
  18205. svr.wait_until_ready();
  18206. Client cli(HOST, PORT);
  18207. {
  18208. auto res = cli.Get(
  18209. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18211. EXPECT_EQ("Page Content Page Content", res->body);
  18212. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18213. }
  18214. {
  18215. auto res = cli.Get(
  18216. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18218. EXPECT_EQ("Page Content Page Content", res->body);
  18219. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18220. }
  18221. }
  18222. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18223. auto handled = false;
  18224. Server svr;
  18225. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18226. thread t = thread([&] { svr.listen(HOST, PORT); });
  18227. auto se = detail::scope_exit([&] {
  18228. svr.stop();
  18229. t.join();
  18230. ASSERT_FALSE(svr.is_running());
  18231. ASSERT_FALSE(handled);
  18232. });
  18233. svr.wait_until_ready();
  18234. auto req = "POST /test HTTP/1.1\r\n"
  18235. "Content-Length: x\r\n"
  18236. "\r\n";
  18237. std::string response;
  18238. ASSERT_TRUE(send_request(1, req, &response));
  18239. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18240. response.substr(0, response.find("\r\n")));
  18241. }
  18242. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18243. // case-insensitive, and a server that receives a 100-continue expectation in
  18244. // an HTTP/1.0 request MUST ignore it.
  18245. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18246. std::string response;
  18247. ASSERT_TRUE(send_request(1, req, &response, port));
  18248. *got_100 = response.find("100 Continue") != std::string::npos;
  18249. }
  18250. class ExpectTokenTest : public ::testing::Test {
  18251. protected:
  18252. void SetUp() override {
  18253. svr_.Post("/p", [](const Request &, Response &res) {
  18254. res.set_content("ok", "text/plain");
  18255. });
  18256. port_ = svr_.bind_to_any_port(HOST);
  18257. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18258. svr_.wait_until_ready();
  18259. }
  18260. void TearDown() override {
  18261. svr_.stop();
  18262. if (thread_.joinable()) { thread_.join(); }
  18263. }
  18264. std::string request(const char *version, const char *expect_value) const {
  18265. return std::string("POST /p ") + version +
  18266. "\r\n"
  18267. "Host: localhost\r\n"
  18268. "Content-Length: 2\r\n"
  18269. "Connection: close\r\n"
  18270. "Expect: " +
  18271. expect_value +
  18272. "\r\n"
  18273. "\r\n"
  18274. "hi";
  18275. }
  18276. Server svr_;
  18277. int port_ = 0;
  18278. thread thread_;
  18279. };
  18280. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18281. bool got_100 = false;
  18282. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18283. EXPECT_TRUE(got_100);
  18284. }
  18285. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18286. bool got_100 = true;
  18287. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18288. EXPECT_FALSE(got_100);
  18289. }
  18290. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18291. bool got_100 = false;
  18292. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18293. EXPECT_TRUE(got_100);
  18294. }
  18295. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18296. bool got_100 = false;
  18297. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18298. EXPECT_TRUE(got_100);
  18299. }
  18300. // `100 Continue` is sent only when the server starts reading the body, so a
  18301. // request rejected before that never invites the client to send it. The
  18302. // requests below carry the expectation but withhold the body, as a client
  18303. // waiting for `100 Continue` would.
  18304. // A POST that expects `100 Continue` and withholds its two-byte body.
  18305. static std::string expect_headers_only(const std::string &path) {
  18306. return "POST " + path +
  18307. " HTTP/1.1\r\n"
  18308. "Host: localhost\r\n"
  18309. "Content-Length: 2\r\n"
  18310. "Expect: 100-continue\r\n"
  18311. "\r\n";
  18312. }
  18313. class ExpectLazyContinueTest : public ::testing::Test {
  18314. protected:
  18315. void SetUp() override {
  18316. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18317. if (req.path == "/pre-routing") {
  18318. res.status = StatusCode::Unauthorized_401;
  18319. return Server::HandlerResponse::Handled;
  18320. }
  18321. return Server::HandlerResponse::Unhandled;
  18322. });
  18323. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18324. if (req.matched_route == "/pre-request") {
  18325. res.status = StatusCode::Forbidden_403;
  18326. return Server::HandlerResponse::Handled;
  18327. }
  18328. return Server::HandlerResponse::Unhandled;
  18329. });
  18330. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18331. res.set_content("ok", "text/plain");
  18332. });
  18333. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18334. res.set_content("ok", "text/plain");
  18335. });
  18336. svr_.Post("/reader-used", [](const Request &, Response &res,
  18337. const ContentReader &content_reader) {
  18338. std::string body;
  18339. content_reader([&](const char *data, size_t len) {
  18340. body.append(data, len);
  18341. return true;
  18342. });
  18343. res.set_content(body, "text/plain");
  18344. });
  18345. svr_.Post("/reader-unused",
  18346. [](const Request &, Response &res, const ContentReader &) {
  18347. res.set_content("ignored", "text/plain");
  18348. });
  18349. port_ = svr_.bind_to_any_port(HOST);
  18350. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18351. svr_.wait_until_ready();
  18352. }
  18353. void TearDown() override {
  18354. svr_.stop();
  18355. if (thread_.joinable()) { thread_.join(); }
  18356. }
  18357. // Sends `req` and reads until the server closes the connection. Returns
  18358. // false if the read had to wait for the client-side timeout instead.
  18359. bool send_until_closed(const std::string &req, std::string *resp) const {
  18360. auto start = std::chrono::steady_clock::now();
  18361. if (!send_request(3, req, resp, port_)) { return false; }
  18362. auto elapsed = std::chrono::steady_clock::now() - start;
  18363. return elapsed < std::chrono::seconds(2);
  18364. }
  18365. // The final response comes without `100 Continue`, and the server closes
  18366. // the connection since the body may or may not follow.
  18367. void expect_final_without_interim(const std::string &path,
  18368. const char *status_line) const {
  18369. std::string resp;
  18370. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18371. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18372. EXPECT_EQ(0u, resp.find(status_line));
  18373. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18374. }
  18375. Server svr_;
  18376. int port_ = 0;
  18377. thread thread_;
  18378. };
  18379. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18380. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18381. }
  18382. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18383. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18384. }
  18385. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18386. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18387. }
  18388. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18389. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18390. }
  18391. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18392. // The body follows once `100 Continue` has had time to arrive.
  18393. auto req = expect_headers_only("/reader-used");
  18394. req.insert(req.size() - 2, "Connection: close\r\n");
  18395. std::string resp;
  18396. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18397. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18398. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18399. EXPECT_NE(std::string::npos, resp.find("hi"));
  18400. }
  18401. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18402. // Large enough for the client to add `Expect: 100-continue` itself.
  18403. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18404. std::atomic<bool> body_sent{false};
  18405. Client cli(HOST, port_);
  18406. auto res = cli.Post(
  18407. "/pre-request", length,
  18408. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18409. body_sent = true;
  18410. std::string chunk(len, 'x');
  18411. sink.write(chunk.data(), chunk.size());
  18412. return true;
  18413. },
  18414. "application/octet-stream");
  18415. ASSERT_TRUE(res);
  18416. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18417. EXPECT_FALSE(body_sent);
  18418. }
  18419. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18420. Server svr;
  18421. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18422. return StatusCode::ExpectationFailed_417;
  18423. });
  18424. svr.Post("/p", [](const Request &, Response &res) {
  18425. res.set_content("ok", "text/plain");
  18426. });
  18427. auto port = svr.bind_to_any_port(HOST);
  18428. thread t = thread([&] { svr.listen_after_bind(); });
  18429. auto se = detail::scope_exit([&] {
  18430. svr.stop();
  18431. t.join();
  18432. });
  18433. svr.wait_until_ready();
  18434. std::string resp;
  18435. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18436. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18437. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18438. // Exactly one response: the route handler must not run after the 417.
  18439. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18440. }
  18441. #ifndef _WIN32
  18442. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18443. static constexpr char reject[] = "Unauthorized";
  18444. static constexpr char accept[] = "Upload accepted";
  18445. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18446. Server svr;
  18447. svr.set_expect_100_continue_handler(
  18448. [](const Request & /*req*/, Response &res) {
  18449. res.status = StatusCode::Unauthorized_401;
  18450. res.set_content(reject, "text/plain");
  18451. return res.status;
  18452. });
  18453. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18454. res.set_content(accept, "text/plain");
  18455. });
  18456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18457. auto se = detail::scope_exit([&] {
  18458. svr.stop();
  18459. thread.join();
  18460. ASSERT_FALSE(svr.is_running());
  18461. });
  18462. svr.wait_until_ready();
  18463. {
  18464. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18465. curl_easy_init(), &curl_easy_cleanup};
  18466. ASSERT_NE(curl, nullptr);
  18467. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18468. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18469. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18470. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18471. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18472. &curl_slist_free_all};
  18473. ASSERT_NE(list, nullptr);
  18474. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18475. struct read_data {
  18476. uint64_t read_size;
  18477. uint64_t total_size;
  18478. } data = {0, total_size};
  18479. using read_callback_t =
  18480. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18481. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18482. void *userdata) -> size_t {
  18483. read_data *d = (read_data *)userdata;
  18484. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18485. std::fill_n(ptr, size * nmemb, 'A');
  18486. d->read_size += size * nmemb;
  18487. return size * nmemb;
  18488. };
  18489. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18490. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18491. std::vector<char> buffer;
  18492. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18493. using write_callback_t =
  18494. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18495. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18496. void *userdata) -> size_t {
  18497. std::vector<char> *buf = (std::vector<char> *)userdata;
  18498. buf->reserve(buf->size() + size * nmemb + 1);
  18499. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18500. return size * nmemb;
  18501. };
  18502. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18503. {
  18504. const auto res = curl_easy_perform(curl.get());
  18505. ASSERT_EQ(res, CURLE_OK);
  18506. }
  18507. {
  18508. auto response_code = long{};
  18509. const auto res =
  18510. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18511. ASSERT_EQ(res, CURLE_OK);
  18512. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18513. }
  18514. {
  18515. auto dl = curl_off_t{};
  18516. const auto res =
  18517. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18518. ASSERT_EQ(res, CURLE_OK);
  18519. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18520. }
  18521. {
  18522. buffer.push_back('\0');
  18523. ASSERT_STRCASEEQ(buffer.data(), reject);
  18524. }
  18525. }
  18526. }
  18527. #endif
  18528. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18529. // Regression test for #2458.
  18530. //
  18531. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18532. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18533. // ticket can make the client socket spuriously readable during the
  18534. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18535. // the client withholds the body and then blocks reading a response that never
  18536. // comes, failing with `Failed to read connection`.
  18537. //
  18538. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18539. // within the timeout. This raw OpenSSL server deliberately never sends
  18540. // `100 Continue`; the client must still deliver the body and receive 200.
  18541. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18542. signal(SIGPIPE, SIG_IGN);
  18543. const auto port = PORT + 4;
  18544. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18545. ASSERT_NE(srv, INVALID_SOCKET);
  18546. int opt = 1;
  18547. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18548. sockaddr_in addr{};
  18549. addr.sin_family = AF_INET;
  18550. addr.sin_port = htons(static_cast<uint16_t>(port));
  18551. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18552. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18553. ASSERT_EQ(0, ::listen(srv, 1));
  18554. std::atomic<size_t> server_body_bytes{0};
  18555. auto server_thread = std::thread([&] {
  18556. sockaddr_in cli_addr{};
  18557. socklen_t cli_len = sizeof(cli_addr);
  18558. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18559. if (cli == INVALID_SOCKET) { return; }
  18560. // Bound the lifetime of the server side so a buggy client (which never
  18561. // sends the body) cannot make this thread block forever on join.
  18562. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18563. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18564. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18565. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18566. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18567. SSL *ssl = SSL_new(ctx);
  18568. SSL_set_fd(ssl, static_cast<int>(cli));
  18569. if (SSL_accept(ssl) > 0) {
  18570. // Read the request headers. Reading here also flushes the TLS 1.3
  18571. // session tickets to the client. Deliberately do NOT send
  18572. // `100 Continue`.
  18573. std::string buf;
  18574. char tmp[1024];
  18575. while (buf.find("\r\n\r\n") == std::string::npos) {
  18576. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18577. if (n <= 0) { break; }
  18578. buf.append(tmp, static_cast<size_t>(n));
  18579. }
  18580. // A correct client sends the body now; count what arrives.
  18581. auto pos = buf.find("\r\n\r\n");
  18582. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18583. while (body < 4096) {
  18584. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18585. if (n <= 0) { break; }
  18586. body += static_cast<size_t>(n);
  18587. }
  18588. server_body_bytes = body;
  18589. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18590. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18591. SSL_shutdown(ssl);
  18592. }
  18593. SSL_free(ssl);
  18594. detail::close_socket(cli);
  18595. SSL_CTX_free(ctx);
  18596. });
  18597. auto se = detail::scope_exit([&] {
  18598. server_thread.join();
  18599. detail::close_socket(srv);
  18600. });
  18601. SSLClient cli("127.0.0.1", port);
  18602. cli.enable_server_certificate_verification(false);
  18603. cli.set_connection_timeout(5, 0);
  18604. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18605. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18606. std::string body(4096, 'A');
  18607. auto res = cli.Put("/api/test", body, "application/json");
  18608. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18609. EXPECT_EQ(StatusCode::OK_200, res->status);
  18610. EXPECT_EQ(body.size(), server_body_bytes.load());
  18611. }
  18612. #endif
  18613. template <typename S, typename C>
  18614. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18615. svr.Get("/stream", [&](const Request &, Response &res) {
  18616. auto data = new std::string("01234567890123456789");
  18617. res.set_content_provider(
  18618. data->size(), "text/plain",
  18619. [&, data](size_t offset, size_t length, DataSink &sink) {
  18620. const size_t DATA_CHUNK_SIZE = 4;
  18621. const auto &d = *data;
  18622. std::this_thread::sleep_for(std::chrono::seconds(1));
  18623. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18624. return true;
  18625. },
  18626. [data](bool success) {
  18627. EXPECT_FALSE(success);
  18628. delete data;
  18629. });
  18630. });
  18631. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18632. auto i = new size_t(0);
  18633. res.set_content_provider(
  18634. "text/plain",
  18635. [i](size_t, DataSink &sink) {
  18636. if (*i < 5) {
  18637. std::this_thread::sleep_for(std::chrono::seconds(1));
  18638. sink.write("abcd", 4);
  18639. (*i)++;
  18640. } else {
  18641. sink.done();
  18642. }
  18643. return true;
  18644. },
  18645. [i](bool success) {
  18646. EXPECT_FALSE(success);
  18647. delete i;
  18648. });
  18649. });
  18650. svr.Get("/chunked", [&](const Request &, Response &res) {
  18651. auto i = new size_t(0);
  18652. res.set_chunked_content_provider(
  18653. "text/plain",
  18654. [i](size_t, DataSink &sink) {
  18655. if (*i < 5) {
  18656. std::this_thread::sleep_for(std::chrono::seconds(1));
  18657. sink.os << "abcd";
  18658. (*i)++;
  18659. } else {
  18660. sink.done();
  18661. }
  18662. return true;
  18663. },
  18664. [i](bool success) {
  18665. EXPECT_FALSE(success);
  18666. delete i;
  18667. });
  18668. });
  18669. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18670. auto se = detail::scope_exit([&] {
  18671. svr.stop();
  18672. listen_thread.join();
  18673. ASSERT_FALSE(svr.is_running());
  18674. });
  18675. svr.wait_until_ready();
  18676. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18677. {
  18678. auto start = std::chrono::steady_clock::now();
  18679. auto res = cli.Get("/stream");
  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("/stream_without_length");
  18691. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18692. std::chrono::steady_clock::now() - start)
  18693. .count();
  18694. ASSERT_FALSE(res);
  18695. EXPECT_EQ(Error::Read, res.error());
  18696. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18697. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18698. }
  18699. {
  18700. auto start = std::chrono::steady_clock::now();
  18701. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18702. EXPECT_EQ("abcd", string(data, data_length));
  18703. return true;
  18704. });
  18705. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18706. std::chrono::steady_clock::now() - start)
  18707. .count();
  18708. ASSERT_FALSE(res);
  18709. EXPECT_EQ(Error::Read, res.error());
  18710. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18711. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18712. }
  18713. }
  18714. TEST(MaxTimeoutTest, ContentStream) {
  18715. time_t timeout = 2000;
  18716. time_t threshold = 200;
  18717. Server svr;
  18718. Client cli("localhost", PORT);
  18719. max_timeout_test(svr, cli, timeout, threshold);
  18720. }
  18721. #ifdef CPPHTTPLIB_SSL_ENABLED
  18722. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18723. time_t timeout = 2000;
  18724. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18726. SSLClient cli("localhost", PORT);
  18727. cli.enable_server_certificate_verification(false);
  18728. max_timeout_test(svr, cli, timeout, threshold);
  18729. }
  18730. #endif
  18731. class EventDispatcher {
  18732. public:
  18733. EventDispatcher() {}
  18734. bool wait_event(DataSink *sink) {
  18735. unique_lock<mutex> lk(m_);
  18736. int id = id_;
  18737. // Wait with timeout to prevent hanging if client disconnects
  18738. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18739. [&] { return cid_ == id; })) {
  18740. return false; // Timeout occurred
  18741. }
  18742. sink->write(message_.data(), message_.size());
  18743. return true;
  18744. }
  18745. void send_event(const string &message) {
  18746. lock_guard<mutex> lk(m_);
  18747. cid_ = id_++;
  18748. message_ = message;
  18749. cv_.notify_all();
  18750. }
  18751. private:
  18752. mutex m_;
  18753. condition_variable cv_;
  18754. atomic_int id_{0};
  18755. atomic_int cid_{-1};
  18756. string message_;
  18757. };
  18758. TEST(ClientInThreadTest, Issue2068) {
  18759. EventDispatcher ed;
  18760. Server svr;
  18761. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18762. res.set_chunked_content_provider("text/event-stream",
  18763. [&](size_t /*offset*/, DataSink &sink) {
  18764. return ed.wait_event(&sink);
  18765. });
  18766. });
  18767. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18768. svr.wait_until_ready();
  18769. thread event_thread([&] {
  18770. int id = 0;
  18771. while (svr.is_running()) {
  18772. this_thread::sleep_for(chrono::milliseconds(500));
  18773. std::stringstream ss;
  18774. ss << "data: " << id << "\n\n";
  18775. ed.send_event(ss.str());
  18776. id++;
  18777. }
  18778. });
  18779. auto se = detail::scope_exit([&] {
  18780. svr.stop();
  18781. listen_thread.join();
  18782. event_thread.join();
  18783. ASSERT_FALSE(svr.is_running());
  18784. });
  18785. {
  18786. auto client = detail::make_unique<Client>(HOST, PORT);
  18787. client->set_read_timeout(std::chrono::minutes(10));
  18788. std::atomic<bool> stop{false};
  18789. std::thread t([&] {
  18790. client->Get("/event1",
  18791. [&](const char *, size_t) -> bool { return !stop; });
  18792. });
  18793. std::this_thread::sleep_for(std::chrono::seconds(2));
  18794. stop = true;
  18795. client->stop();
  18796. t.join();
  18797. // Reset client after thread has finished
  18798. client.reset();
  18799. }
  18800. }
  18801. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18802. auto handled = false;
  18803. Server svr;
  18804. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18805. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18806. auto se = detail::scope_exit([&] {
  18807. svr.stop();
  18808. t.join();
  18809. ASSERT_FALSE(svr.is_running());
  18810. ASSERT_FALSE(handled);
  18811. });
  18812. svr.wait_until_ready();
  18813. // Two Content-Length headers with different values — must be rejected
  18814. auto req = "POST /test HTTP/1.1\r\n"
  18815. "Content-Length: 5\r\n"
  18816. "Content-Length: 10\r\n"
  18817. "\r\n"
  18818. "hello";
  18819. std::string response;
  18820. ASSERT_TRUE(send_request(1, req, &response));
  18821. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18822. response.substr(0, response.find("\r\n")));
  18823. }
  18824. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18825. auto handled = false;
  18826. Server svr;
  18827. svr.Post("/test", [&](const Request &, Response &res) {
  18828. handled = true;
  18829. res.set_content("ok", "text/plain");
  18830. });
  18831. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18832. auto se = detail::scope_exit([&] {
  18833. svr.stop();
  18834. t.join();
  18835. ASSERT_FALSE(svr.is_running());
  18836. ASSERT_TRUE(handled);
  18837. });
  18838. svr.wait_until_ready();
  18839. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18840. auto req = "POST /test HTTP/1.1\r\n"
  18841. "Host: localhost\r\n"
  18842. "Content-Length: 5\r\n"
  18843. "Content-Length: 5\r\n"
  18844. "\r\n"
  18845. "hello";
  18846. std::string response;
  18847. ASSERT_TRUE(send_request(1, req, &response));
  18848. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18849. }
  18850. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18851. Server svr;
  18852. svr.Get("/test", [](const Request &, Response &res) {
  18853. res.set_content("ok", "text/plain");
  18854. });
  18855. auto port = svr.bind_to_any_port(HOST);
  18856. thread t = thread([&] { svr.listen_after_bind(); });
  18857. auto se = detail::scope_exit([&] {
  18858. svr.stop();
  18859. t.join();
  18860. ASSERT_FALSE(svr.is_running());
  18861. });
  18862. svr.wait_until_ready();
  18863. auto status_line = [&](const std::string &host_lines) {
  18864. std::string res;
  18865. send_request(
  18866. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18867. &res, port);
  18868. return res.substr(0, res.find("\r\n"));
  18869. };
  18870. const char *accepted[] = {
  18871. "Host: localhost\r\n",
  18872. "Host: a.example:8080\r\n",
  18873. "Host: my_service\r\n",
  18874. "Host: [::1]:8080\r\n",
  18875. "Host: [fe80::1%25eth0]\r\n",
  18876. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18877. };
  18878. for (auto host_lines : accepted) {
  18879. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18880. }
  18881. const char *rejected[] = {
  18882. "Host: a.example\r\nHost: b.example\r\n",
  18883. "Host: a.example\r\nHost: a.example\r\n",
  18884. "Host: a@b.example\r\n",
  18885. "Host: a.example/b\r\n",
  18886. "Host: a.example\\b\r\n",
  18887. "Host: a.example?b\r\n",
  18888. "Host: a.example#b\r\n",
  18889. "Host: a.example b.example\r\n",
  18890. };
  18891. for (auto host_lines : rejected) {
  18892. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18893. << host_lines;
  18894. }
  18895. }
  18896. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18897. Server svr;
  18898. svr.Get("/", [](const Request &req, Response &res) {
  18899. EXPECT_EQ(2U, req.trailers.size());
  18900. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18901. // Denied
  18902. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18903. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18904. // Accepted
  18905. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18906. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18907. EXPECT_TRUE(req.has_trailer("X-World"));
  18908. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18909. res.set_content("ok", "text/plain");
  18910. });
  18911. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18912. auto se = detail::scope_exit([&] {
  18913. svr.stop();
  18914. t.join();
  18915. ASSERT_FALSE(svr.is_running());
  18916. });
  18917. svr.wait_until_ready();
  18918. const std::string req = "GET / HTTP/1.1\r\n"
  18919. "Transfer-Encoding: chunked\r\n"
  18920. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18921. "\r\n"
  18922. "0\r\n"
  18923. "Content-Length: 10\r\n"
  18924. "Host: internal.local\r\n"
  18925. "Content-Type: malicious/content\r\n"
  18926. "Cookie: any\r\n"
  18927. "Set-Cookie: any\r\n"
  18928. "X-Forwarded-For: attacker.com\r\n"
  18929. "X-Real-Ip: 1.1.1.1\r\n"
  18930. "X-Hello: hello\r\n"
  18931. "X-World: world\r\n"
  18932. "\r\n";
  18933. std::string res;
  18934. ASSERT_TRUE(send_request(1, req, &res));
  18935. }
  18936. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18937. // several field lines, and the combined value is what has to be parsed. A
  18938. // Trailer field split across lines therefore declares every name it lists;
  18939. // reading only the first line silently drops the trailers the later lines
  18940. // declare. The prohibited-trailer filter still applies to every line.
  18941. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18942. Server svr;
  18943. size_t observed_trailer_count = 0;
  18944. std::string observed_hello;
  18945. std::string observed_world;
  18946. bool observed_content_length = true;
  18947. svr.Get("/", [&](const Request &req, Response &res) {
  18948. observed_trailer_count = req.trailers.size();
  18949. observed_hello = req.get_trailer_value("X-Hello");
  18950. observed_world = req.get_trailer_value("X-World");
  18951. observed_content_length = req.has_trailer("Content-Length");
  18952. res.set_content("ok", "text/plain");
  18953. });
  18954. auto port = svr.bind_to_any_port(HOST);
  18955. thread t = thread([&]() { svr.listen_after_bind(); });
  18956. auto se = detail::scope_exit([&] {
  18957. svr.stop();
  18958. t.join();
  18959. ASSERT_FALSE(svr.is_running());
  18960. });
  18961. svr.wait_until_ready();
  18962. const std::string req = "GET / HTTP/1.1\r\n"
  18963. "Host: localhost\r\n"
  18964. "Transfer-Encoding: chunked\r\n"
  18965. "Trailer: X-Hello\r\n"
  18966. "Trailer: X-World, Content-Length\r\n"
  18967. "\r\n"
  18968. "0\r\n"
  18969. "X-Hello: hello\r\n"
  18970. "X-World: world\r\n"
  18971. "Content-Length: 10\r\n"
  18972. "\r\n";
  18973. std::string res;
  18974. ASSERT_TRUE(send_request(1, req, &res, port));
  18975. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18976. // Accepted: both field lines contribute to the declared set
  18977. EXPECT_EQ(2U, observed_trailer_count);
  18978. EXPECT_EQ(observed_hello, "hello");
  18979. EXPECT_EQ(observed_world, "world");
  18980. // Denied: a prohibited name stays prohibited on a later field line
  18981. EXPECT_FALSE(observed_content_length);
  18982. }
  18983. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18984. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18985. // unbounded run of fields that are never declared, because the counter would
  18986. // only advance for declared fields.
  18987. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18988. Server svr;
  18989. bool handler_called = false;
  18990. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18991. handler_called = true;
  18992. res.set_content("ok", "text/plain");
  18993. });
  18994. auto port = svr.bind_to_any_port(HOST);
  18995. thread t = thread([&]() { svr.listen_after_bind(); });
  18996. auto se = detail::scope_exit([&] {
  18997. svr.stop();
  18998. t.join();
  18999. ASSERT_FALSE(svr.is_running());
  19000. });
  19001. svr.wait_until_ready();
  19002. // Declare nothing, then send far more undeclared trailer fields than the
  19003. // header-count limit. Parsing must stop and reject the request rather than
  19004. // read every line.
  19005. std::string req = "GET / HTTP/1.1\r\n"
  19006. "Transfer-Encoding: chunked\r\n"
  19007. "\r\n"
  19008. "0\r\n";
  19009. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19010. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19011. }
  19012. req += "\r\n";
  19013. std::string res;
  19014. ASSERT_TRUE(send_request(1, req, &res, port));
  19015. // The request is rejected before the handler runs.
  19016. EXPECT_FALSE(handler_called);
  19017. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19018. }
  19019. // The set of declared trailer names is capped so a peer cannot grow it without
  19020. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19021. // declared past the cap is not honored, even if the field is actually sent.
  19022. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19023. Server svr;
  19024. // One name inside the cap and one past it, so the test tracks the cap rather
  19025. // than a fixed count.
  19026. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19027. const std::string within_cap_name = "X-T-0";
  19028. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19029. bool observed_within_cap = false;
  19030. bool observed_past_cap = false;
  19031. svr.Get("/", [&](const Request &req, Response &res) {
  19032. observed_within_cap = req.has_trailer(within_cap_name);
  19033. observed_past_cap = req.has_trailer(past_cap_name);
  19034. res.set_content("ok", "text/plain");
  19035. });
  19036. auto port = svr.bind_to_any_port(HOST);
  19037. thread t = thread([&]() { svr.listen_after_bind(); });
  19038. auto se = detail::scope_exit([&] {
  19039. svr.stop();
  19040. t.join();
  19041. ASSERT_FALSE(svr.is_running());
  19042. });
  19043. svr.wait_until_ready();
  19044. // Declare more trailer names than the cap in a single Trailer field, then
  19045. // actually send the first (within the cap) and the last (past it).
  19046. std::string trailer_decl = "Trailer: ";
  19047. for (int i = 0; i < declared_count; i++) {
  19048. if (i != 0) { trailer_decl += ", "; }
  19049. trailer_decl += "X-T-" + std::to_string(i);
  19050. }
  19051. trailer_decl += "\r\n";
  19052. const std::string req = "GET / HTTP/1.1\r\n"
  19053. "Host: localhost\r\n"
  19054. "Transfer-Encoding: chunked\r\n" +
  19055. trailer_decl +
  19056. "\r\n"
  19057. "0\r\n" +
  19058. within_cap_name + ": a\r\n" + past_cap_name +
  19059. ": b\r\n"
  19060. "\r\n";
  19061. std::string res;
  19062. ASSERT_TRUE(send_request(1, req, &res, port));
  19063. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19064. // A name within the cap is honored; one declared past the cap is dropped.
  19065. EXPECT_TRUE(observed_within_cap);
  19066. EXPECT_FALSE(observed_past_cap);
  19067. }
  19068. // A direct client that is not listed in trusted_proxies must not be able to
  19069. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19070. // the peer address on the actual TCP connection determines whether the
  19071. // header is honored.
  19072. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19073. Server svr;
  19074. // Deliberately does NOT include the loopback address the test client
  19075. // actually connects from, so the direct connection is not a trusted proxy.
  19076. svr.set_trusted_proxies({"203.0.113.66"});
  19077. std::string observed_remote_addr;
  19078. svr.Get("/ip", [&](const Request &req, Response &res) {
  19079. observed_remote_addr = req.remote_addr;
  19080. res.set_content("ok", "text/plain");
  19081. });
  19082. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19083. auto se = detail::scope_exit([&] {
  19084. svr.stop();
  19085. t.join();
  19086. ASSERT_FALSE(svr.is_running());
  19087. });
  19088. svr.wait_until_ready();
  19089. Client cli(HOST, PORT);
  19090. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19092. EXPECT_EQ(StatusCode::OK_200, res->status);
  19093. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19094. // ignored entirely and the real connection-level address retained.
  19095. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19096. observed_remote_addr == "127.0.0.1");
  19097. }
  19098. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19099. Server svr;
  19100. std::string observed_remote_addr;
  19101. std::string observed_xff;
  19102. svr.Get("/ip", [&](const Request &req, Response &res) {
  19103. observed_remote_addr = req.remote_addr;
  19104. observed_xff = req.get_header_value("X-Forwarded-For");
  19105. res.set_content("ok", "text/plain");
  19106. });
  19107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19108. auto se = detail::scope_exit([&] {
  19109. svr.stop();
  19110. t.join();
  19111. ASSERT_FALSE(svr.is_running());
  19112. });
  19113. svr.wait_until_ready();
  19114. Client cli(HOST, PORT);
  19115. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19117. EXPECT_EQ(StatusCode::OK_200, res->status);
  19118. EXPECT_EQ(observed_xff, "203.0.113.66");
  19119. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19120. observed_remote_addr == "127.0.0.1");
  19121. }
  19122. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19123. Server svr;
  19124. svr.set_trusted_proxies({"203.0.113.66"});
  19125. std::string observed_remote_addr;
  19126. std::string observed_xff;
  19127. svr.Get("/ip", [&](const Request &req, Response &res) {
  19128. observed_remote_addr = req.remote_addr;
  19129. observed_xff = req.get_header_value("X-Forwarded-For");
  19130. res.set_content("ok", "text/plain");
  19131. });
  19132. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19133. auto se = detail::scope_exit([&] {
  19134. svr.stop();
  19135. t.join();
  19136. ASSERT_FALSE(svr.is_running());
  19137. });
  19138. svr.wait_until_ready();
  19139. Client cli(HOST, PORT);
  19140. auto res = cli.Get("/ip");
  19141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19142. EXPECT_EQ(StatusCode::OK_200, res->status);
  19143. EXPECT_EQ(observed_xff, "");
  19144. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19145. observed_remote_addr == "127.0.0.1");
  19146. }
  19147. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19148. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19149. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19150. Server svr;
  19151. svr.set_trusted_proxies({"127.0.0.1"});
  19152. svr.Get("/ip", [](const Request &req, Response &res) {
  19153. res.set_content(req.remote_addr, "text/plain");
  19154. });
  19155. auto port = svr.bind_to_any_port("::");
  19156. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19157. thread t = thread([&] { svr.listen_after_bind(); });
  19158. auto se = detail::scope_exit([&] {
  19159. svr.stop();
  19160. t.join();
  19161. ASSERT_FALSE(svr.is_running());
  19162. });
  19163. svr.wait_until_ready();
  19164. Client cli("127.0.0.1", port);
  19165. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19167. EXPECT_EQ("198.51.100.23", res->body);
  19168. }
  19169. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19170. Server svr;
  19171. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19172. svr.Get("/ip", [](const Request &req, Response &res) {
  19173. res.set_content(req.remote_addr, "text/plain");
  19174. });
  19175. auto port = svr.bind_to_any_port(HOST);
  19176. ASSERT_GT(port, 0);
  19177. thread t = thread([&] { svr.listen_after_bind(); });
  19178. auto se = detail::scope_exit([&] {
  19179. svr.stop();
  19180. t.join();
  19181. ASSERT_FALSE(svr.is_running());
  19182. });
  19183. svr.wait_until_ready();
  19184. Client cli(HOST, port);
  19185. auto res = cli.Get(
  19186. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19188. EXPECT_EQ("198.51.100.23", res->body);
  19189. }
  19190. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19191. Server svr;
  19192. // Include the loopback address the test client actually connects from, so
  19193. // the direct connection itself is recognized as the trusted proxy hop.
  19194. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19195. std::string observed_remote_addr;
  19196. std::string observed_xff;
  19197. svr.Get("/ip", [&](const Request &req, Response &res) {
  19198. observed_remote_addr = req.remote_addr;
  19199. observed_xff = req.get_header_value("X-Forwarded-For");
  19200. res.set_content("ok", "text/plain");
  19201. });
  19202. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19203. auto se = detail::scope_exit([&] {
  19204. svr.stop();
  19205. t.join();
  19206. ASSERT_FALSE(svr.is_running());
  19207. });
  19208. svr.wait_until_ready();
  19209. Client cli(HOST, PORT);
  19210. auto res = cli.Get(
  19211. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19213. EXPECT_EQ(StatusCode::OK_200, res->status);
  19214. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19215. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19216. }
  19217. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19218. Server svr;
  19219. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19220. std::string observed_remote_addr;
  19221. std::string observed_xff;
  19222. svr.Get("/ip", [&](const Request &req, Response &res) {
  19223. observed_remote_addr = req.remote_addr;
  19224. observed_xff = req.get_header_value("X-Forwarded-For");
  19225. res.set_content("ok", "text/plain");
  19226. });
  19227. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19228. auto se = detail::scope_exit([&] {
  19229. svr.stop();
  19230. t.join();
  19231. ASSERT_FALSE(svr.is_running());
  19232. });
  19233. svr.wait_until_ready();
  19234. Client cli(HOST, PORT);
  19235. auto res = cli.Get(
  19236. "/ip",
  19237. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19239. EXPECT_EQ(StatusCode::OK_200, res->status);
  19240. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19241. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19242. }
  19243. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19244. Server svr;
  19245. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19246. std::string observed_remote_addr;
  19247. std::string observed_xff;
  19248. svr.Get("/ip", [&](const Request &req, Response &res) {
  19249. observed_remote_addr = req.remote_addr;
  19250. observed_xff = req.get_header_value("X-Forwarded-For");
  19251. res.set_content("ok", "text/plain");
  19252. });
  19253. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19254. auto se = detail::scope_exit([&] {
  19255. svr.stop();
  19256. t.join();
  19257. ASSERT_FALSE(svr.is_running());
  19258. });
  19259. svr.wait_until_ready();
  19260. Client cli(HOST, PORT);
  19261. auto res = cli.Get(
  19262. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19264. EXPECT_EQ(StatusCode::OK_200, res->status);
  19265. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19266. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19267. // and must not be selected.
  19268. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19269. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19270. }
  19271. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19272. Server svr;
  19273. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19274. std::string observed_remote_addr;
  19275. svr.Get("/ip", [&](const Request &req, Response &res) {
  19276. observed_remote_addr = req.remote_addr;
  19277. res.set_content("ok", "text/plain");
  19278. });
  19279. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19280. auto se = detail::scope_exit([&] {
  19281. svr.stop();
  19282. t.join();
  19283. ASSERT_FALSE(svr.is_running());
  19284. });
  19285. svr.wait_until_ready();
  19286. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19287. // a forged address and the trusted proxy's own address; the forged value must
  19288. // not win over the address the trusted proxy actually recorded.
  19289. Client cli(HOST, PORT);
  19290. auto res = cli.Get(
  19291. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19293. EXPECT_EQ(StatusCode::OK_200, res->status);
  19294. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19295. }
  19296. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19297. Server svr;
  19298. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19299. std::string observed_remote_addr;
  19300. std::string observed_xff;
  19301. svr.Get("/ip", [&](const Request &req, Response &res) {
  19302. observed_remote_addr = req.remote_addr;
  19303. observed_xff = req.get_header_value("X-Forwarded-For");
  19304. res.set_content("ok", "text/plain");
  19305. });
  19306. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19307. auto se = detail::scope_exit([&] {
  19308. svr.stop();
  19309. t.join();
  19310. ASSERT_FALSE(svr.is_running());
  19311. });
  19312. svr.wait_until_ready();
  19313. Client cli(HOST, PORT);
  19314. auto res = cli.Get(
  19315. "/ip",
  19316. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19318. EXPECT_EQ(StatusCode::OK_200, res->status);
  19319. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19320. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19321. }
  19322. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19323. Server svr;
  19324. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19325. std::string observed_remote_addr;
  19326. std::string observed_xff;
  19327. svr.Get("/ip", [&](const Request &req, Response &res) {
  19328. observed_remote_addr = req.remote_addr;
  19329. observed_xff = req.get_header_value("X-Forwarded-For");
  19330. res.set_content("ok", "text/plain");
  19331. });
  19332. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19333. auto se = detail::scope_exit([&] {
  19334. svr.stop();
  19335. t.join();
  19336. ASSERT_FALSE(svr.is_running());
  19337. });
  19338. svr.wait_until_ready();
  19339. std::string raw_req =
  19340. "GET /ip HTTP/1.1\r\n"
  19341. "Host: localhost\r\n"
  19342. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19343. "Connection: close\r\n"
  19344. "\r\n";
  19345. std::string out;
  19346. ASSERT_TRUE(send_request(5, raw_req, &out));
  19347. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19348. // Header parser trims surrounding whitespace of the header value
  19349. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19350. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19351. }
  19352. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19353. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19354. // their own X-Forwarded-For as a separate field line rather than extending the
  19355. // one the client sent, so every occurrence has to be taken into account.
  19356. // Reading only the first one hands back the address the client chose.
  19357. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19358. Server svr;
  19359. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19360. std::string observed_remote_addr;
  19361. size_t observed_xff_count = 0;
  19362. svr.Get("/ip", [&](const Request &req, Response &res) {
  19363. observed_remote_addr = req.remote_addr;
  19364. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19365. res.set_content("ok", "text/plain");
  19366. });
  19367. auto port = svr.bind_to_any_port(HOST);
  19368. thread t = thread([&]() { svr.listen_after_bind(); });
  19369. auto se = detail::scope_exit([&] {
  19370. svr.stop();
  19371. t.join();
  19372. ASSERT_FALSE(svr.is_running());
  19373. });
  19374. svr.wait_until_ready();
  19375. // The client supplies the first field line; the trusted proxy appends the
  19376. // address it observed as a second one.
  19377. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19378. "Host: localhost\r\n"
  19379. "X-Forwarded-For: 1.2.3.4\r\n"
  19380. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19381. "Connection: close\r\n"
  19382. "\r\n";
  19383. std::string out;
  19384. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19385. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19386. EXPECT_EQ(observed_xff_count, 2U);
  19387. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19388. // The same chain spread over one field line per hop derives the same client
  19389. // address, i.e. the split and the comma-joined representations agree.
  19390. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19391. "Host: localhost\r\n"
  19392. "X-Forwarded-For: 1.2.3.4\r\n"
  19393. "X-Forwarded-For: 198.51.100.23\r\n"
  19394. "X-Forwarded-For: 192.0.2.45\r\n"
  19395. "Connection: close\r\n"
  19396. "\r\n";
  19397. out.clear();
  19398. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19399. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19400. EXPECT_EQ(observed_xff_count, 3U);
  19401. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19402. }
  19403. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19404. // crash the server (it used to call front() on an empty vector inside
  19405. // get_client_ip). The connection-level remote address must be retained instead.
  19406. static void run_malformed_xff_test(const std::string &xff_value) {
  19407. Server svr;
  19408. svr.set_trusted_proxies({"192.0.2.45"});
  19409. std::string observed_remote_addr;
  19410. svr.Get("/ip", [&](const Request &req, Response &res) {
  19411. observed_remote_addr = req.remote_addr;
  19412. res.set_content("ok", "text/plain");
  19413. });
  19414. int port = 0;
  19415. thread t = thread([&]() {
  19416. port = svr.bind_to_any_port(HOST);
  19417. svr.listen_after_bind();
  19418. });
  19419. auto se = detail::scope_exit([&] {
  19420. svr.stop();
  19421. t.join();
  19422. ASSERT_FALSE(svr.is_running());
  19423. });
  19424. svr.wait_until_ready();
  19425. Client cli(HOST, port);
  19426. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19428. EXPECT_EQ(StatusCode::OK_200, res->status);
  19429. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19430. observed_remote_addr == "127.0.0.1");
  19431. }
  19432. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19433. run_malformed_xff_test("");
  19434. }
  19435. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19436. run_malformed_xff_test(",");
  19437. }
  19438. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19439. run_malformed_xff_test(", , ,");
  19440. }
  19441. // The same rule applies to Accept: a request whose acceptable types are spread
  19442. // over several field lines must be negotiated against all of them.
  19443. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19444. // case-insensitive connection options. Comparing the whole field value against
  19445. // one option misses a client that sends several of them, and misses every
  19446. // casing but the one written in the comparison.
  19447. //
  19448. // Sends req, reads the response, then reuses the same socket for a second
  19449. // request to find out whether the server kept the connection.
  19450. static void probe_connection_reuse(int port, const std::string &req,
  19451. bool *announced_close, bool *reusable) {
  19452. auto error = Error::Success;
  19453. auto sock = detail::create_client_socket(
  19454. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19455. /*connection_timeout_sec=*/5, 0,
  19456. /*read_timeout_sec=*/1, 0,
  19457. /*write_timeout_sec=*/5, 0, std::string(), error);
  19458. ASSERT_NE(sock, INVALID_SOCKET);
  19459. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19460. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19461. "Host: localhost\r\n"
  19462. "Connection: close\r\n"
  19463. "\r\n";
  19464. std::string first_response;
  19465. std::string second_response;
  19466. detail::process_client_socket(
  19467. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19468. [&](Stream &strm) {
  19469. if (strm.write(req.data(), req.size()) !=
  19470. static_cast<ssize_t>(req.size())) {
  19471. return false;
  19472. }
  19473. char buf[512];
  19474. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19475. // Headers plus the two-byte body of the handler below
  19476. while (reader.getline()) {
  19477. first_response += reader.ptr();
  19478. if (first_response.find("ok") != std::string::npos) { break; }
  19479. }
  19480. if (strm.write(second.data(), second.size()) !=
  19481. static_cast<ssize_t>(second.size())) {
  19482. return true;
  19483. }
  19484. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19485. while (reader2.getline()) {
  19486. second_response += reader2.ptr();
  19487. if (second_response.find("ok") != std::string::npos) { break; }
  19488. }
  19489. return true;
  19490. });
  19491. *announced_close =
  19492. first_response.find("Connection: close") != std::string::npos;
  19493. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19494. }
  19495. class ConnectionTokenTest : public ::testing::Test {
  19496. protected:
  19497. void SetUp() override {
  19498. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19499. res.set_content("ok", "text/plain");
  19500. });
  19501. port_ = svr_.bind_to_any_port(HOST);
  19502. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19503. svr_.wait_until_ready();
  19504. }
  19505. void TearDown() override {
  19506. svr_.stop();
  19507. if (thread_.joinable()) { thread_.join(); }
  19508. }
  19509. Server svr_;
  19510. int port_ = 0;
  19511. thread thread_;
  19512. };
  19513. // "close" alongside another option still closes the connection, and the
  19514. // response says so rather than leaving the peer to discover it.
  19515. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19516. bool announced_close = false;
  19517. bool reusable = true;
  19518. probe_connection_reuse(port_,
  19519. "GET /keepalive HTTP/1.1\r\n"
  19520. "Host: localhost\r\n"
  19521. "Connection: keep-alive, close\r\n"
  19522. "\r\n",
  19523. &announced_close, &reusable);
  19524. EXPECT_TRUE(announced_close);
  19525. EXPECT_FALSE(reusable);
  19526. }
  19527. // "close" split over two field lines is the same list, so it is honored too.
  19528. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19529. bool announced_close = false;
  19530. bool reusable = true;
  19531. probe_connection_reuse(port_,
  19532. "GET /keepalive HTTP/1.1\r\n"
  19533. "Host: localhost\r\n"
  19534. "Connection: keep-alive\r\n"
  19535. "Connection: close\r\n"
  19536. "\r\n",
  19537. &announced_close, &reusable);
  19538. EXPECT_TRUE(announced_close);
  19539. EXPECT_FALSE(reusable);
  19540. }
  19541. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19542. // keep-alive in the spelling everyone actually sends keeps its connection.
  19543. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19544. bool announced_close = false;
  19545. bool reusable = false;
  19546. probe_connection_reuse(port_,
  19547. "GET /keepalive HTTP/1.0\r\n"
  19548. "Host: localhost\r\n"
  19549. "Connection: keep-alive\r\n"
  19550. "\r\n",
  19551. &announced_close, &reusable);
  19552. EXPECT_FALSE(announced_close);
  19553. EXPECT_TRUE(reusable);
  19554. }
  19555. // A token the value merely contains is not the token itself.
  19556. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19557. bool announced_close = false;
  19558. bool reusable = false;
  19559. probe_connection_reuse(port_,
  19560. "GET /keepalive HTTP/1.1\r\n"
  19561. "Host: localhost\r\n"
  19562. "Connection: notclose\r\n"
  19563. "\r\n",
  19564. &announced_close, &reusable);
  19565. EXPECT_FALSE(announced_close);
  19566. EXPECT_TRUE(reusable);
  19567. }
  19568. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19569. Server svr;
  19570. std::vector<std::string> observed_types;
  19571. svr.Get("/", [&](const Request &req, Response &res) {
  19572. observed_types = req.accept_content_types;
  19573. res.set_content("ok", "text/plain");
  19574. });
  19575. auto port = svr.bind_to_any_port(HOST);
  19576. thread t = thread([&]() { svr.listen_after_bind(); });
  19577. auto se = detail::scope_exit([&] {
  19578. svr.stop();
  19579. t.join();
  19580. ASSERT_FALSE(svr.is_running());
  19581. });
  19582. svr.wait_until_ready();
  19583. Client cli(HOST, port);
  19584. Headers headers;
  19585. headers.emplace("Accept", "text/plain;q=0.5");
  19586. headers.emplace("Accept", "application/json");
  19587. auto res = cli.Get("/", headers);
  19588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19589. EXPECT_EQ(StatusCode::OK_200, res->status);
  19590. // Sorted by q-value, so the second field line's type comes first
  19591. ASSERT_EQ(2U, observed_types.size());
  19592. EXPECT_EQ("application/json", observed_types[0]);
  19593. EXPECT_EQ("text/plain", observed_types[1]);
  19594. }
  19595. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19596. // empty field line must not contribute a bare comma to the combined value.
  19597. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19598. Server svr;
  19599. std::vector<std::string> observed_types;
  19600. svr.Get("/", [&](const Request &req, Response &res) {
  19601. observed_types = req.accept_content_types;
  19602. res.set_content("ok", "text/plain");
  19603. });
  19604. auto port = svr.bind_to_any_port(HOST);
  19605. thread t = thread([&]() { svr.listen_after_bind(); });
  19606. auto se = detail::scope_exit([&] {
  19607. svr.stop();
  19608. t.join();
  19609. ASSERT_FALSE(svr.is_running());
  19610. });
  19611. svr.wait_until_ready();
  19612. // Empty first field line, then a real one
  19613. std::string raw_req = "GET / HTTP/1.1\r\n"
  19614. "Host: localhost\r\n"
  19615. "Accept:\r\n"
  19616. "Accept: application/json\r\n"
  19617. "Connection: close\r\n"
  19618. "\r\n";
  19619. std::string out;
  19620. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19621. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19622. ASSERT_EQ(1U, observed_types.size());
  19623. EXPECT_EQ("application/json", observed_types[0]);
  19624. }
  19625. // The skip in get_combined_header_value() is what keeps an empty field line
  19626. // from contributing a bare comma. Only a trailing empty field line exercises
  19627. // it: a leading one is already covered by the "combined is still empty" check,
  19628. // and parse_accept_header() now ignores the empty element either way, so the
  19629. // request-level test above can no longer tell the two apart.
  19630. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19631. Headers headers;
  19632. headers.emplace("Accept", "text/html");
  19633. headers.emplace("Accept", "");
  19634. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19635. headers.clear();
  19636. headers.emplace("Accept", "");
  19637. headers.emplace("Accept", "application/json");
  19638. EXPECT_EQ("application/json",
  19639. detail::get_combined_header_value(headers, "Accept"));
  19640. }
  19641. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19642. // An encoding offered on a later Accept-Encoding field line is still offered.
  19643. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19644. Server svr;
  19645. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19646. res.set_content(std::string(1024, 'x'), "text/plain");
  19647. });
  19648. auto port = svr.bind_to_any_port(HOST);
  19649. thread t = thread([&]() { svr.listen_after_bind(); });
  19650. auto se = detail::scope_exit([&] {
  19651. svr.stop();
  19652. t.join();
  19653. ASSERT_FALSE(svr.is_running());
  19654. });
  19655. svr.wait_until_ready();
  19656. Client cli(HOST, port);
  19657. cli.set_decompress(false);
  19658. Headers headers;
  19659. headers.emplace("Accept-Encoding", "identity");
  19660. headers.emplace("Accept-Encoding", "gzip");
  19661. auto res = cli.Get("/", headers);
  19662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19663. EXPECT_EQ(StatusCode::OK_200, res->status);
  19664. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19665. }
  19666. #endif
  19667. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19668. // Transfer-Encoding is not its body.
  19669. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19670. Server svr;
  19671. svr.set_payload_max_length(8);
  19672. svr.Post("/test", [](const Request &, Response &res) {
  19673. res.set_content("ok", "text/plain");
  19674. });
  19675. auto port = svr.bind_to_any_port(HOST);
  19676. ASSERT_GT(port, 0);
  19677. thread t = thread([&] { svr.listen_after_bind(); });
  19678. auto se = detail::scope_exit([&] {
  19679. svr.stop();
  19680. t.join();
  19681. ASSERT_FALSE(svr.is_running());
  19682. });
  19683. svr.wait_until_ready();
  19684. std::string resp;
  19685. ASSERT_TRUE(send_request(1,
  19686. "POST /test HTTP/1.1\r\n"
  19687. "Host: localhost\r\n"
  19688. "Connection: close\r\n"
  19689. "\r\n" +
  19690. std::string(16, 'X'),
  19691. &resp, port));
  19692. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19693. }
  19694. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19695. Server svr;
  19696. svr.Post("/post", [&](const Request &req, Response &res) {
  19697. res.set_content(req.body, "text/plain");
  19698. });
  19699. svr.Put("/put", [&](const Request &req, Response &res) {
  19700. res.set_content(req.body, "text/plain");
  19701. });
  19702. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19703. res.set_content(req.body, "text/plain");
  19704. });
  19705. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19706. res.set_content(req.body, "text/plain");
  19707. });
  19708. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19709. auto se = detail::scope_exit([&] {
  19710. svr.stop();
  19711. t.join();
  19712. ASSERT_FALSE(svr.is_running());
  19713. });
  19714. svr.wait_until_ready();
  19715. std::string resp;
  19716. // POST without Content-Length
  19717. ASSERT_TRUE(send_request(5,
  19718. "POST /post HTTP/1.1\r\n"
  19719. "Host: localhost\r\n"
  19720. "Connection: close\r\n"
  19721. "\r\n",
  19722. &resp));
  19723. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19724. // PUT without Content-Length
  19725. resp.clear();
  19726. ASSERT_TRUE(send_request(5,
  19727. "PUT /put HTTP/1.1\r\n"
  19728. "Host: localhost\r\n"
  19729. "Connection: close\r\n"
  19730. "\r\n",
  19731. &resp));
  19732. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19733. // PATCH without Content-Length
  19734. resp.clear();
  19735. ASSERT_TRUE(send_request(5,
  19736. "PATCH /patch HTTP/1.1\r\n"
  19737. "Host: localhost\r\n"
  19738. "Connection: close\r\n"
  19739. "\r\n",
  19740. &resp));
  19741. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19742. // DELETE without Content-Length
  19743. resp.clear();
  19744. ASSERT_TRUE(send_request(5,
  19745. "DELETE /delete HTTP/1.1\r\n"
  19746. "Host: localhost\r\n"
  19747. "Connection: close\r\n"
  19748. "\r\n",
  19749. &resp));
  19750. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19751. }
  19752. //==============================================================================
  19753. // open_stream() Tests
  19754. //==============================================================================
  19755. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19756. std::string result;
  19757. char buf[8192];
  19758. ssize_t n;
  19759. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19760. result.append(buf, static_cast<size_t>(n));
  19761. }
  19762. return result;
  19763. }
  19764. // Mock stream for unit tests
  19765. class MockStream : public Stream {
  19766. public:
  19767. std::string data;
  19768. size_t pos = 0;
  19769. ssize_t error_after = -1; // -1 = no error
  19770. explicit MockStream(const std::string &d, ssize_t err = -1)
  19771. : data(d), error_after(err) {}
  19772. bool is_readable() const override { return true; }
  19773. bool wait_readable() const override { return true; }
  19774. bool wait_writable() const override { return true; }
  19775. ssize_t read(char *ptr, size_t size) override {
  19776. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19777. if (pos >= data.size()) return 0;
  19778. size_t limit =
  19779. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19780. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19781. std::memcpy(ptr, data.data() + pos, to_read);
  19782. pos += to_read;
  19783. return static_cast<ssize_t>(to_read);
  19784. }
  19785. ssize_t write(const char *, size_t) override { return -1; }
  19786. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19787. ip = "127.0.0.1";
  19788. port = 0;
  19789. }
  19790. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19791. ip = "127.0.0.1";
  19792. port = 0;
  19793. }
  19794. socket_t socket() const override { return INVALID_SOCKET; }
  19795. time_t duration() const override { return 0; }
  19796. };
  19797. TEST(StreamHandleTest, Basic) {
  19798. ClientImpl::StreamHandle handle;
  19799. EXPECT_FALSE(handle.is_valid());
  19800. handle.response = detail::make_unique<Response>();
  19801. handle.error = Error::Connection;
  19802. EXPECT_FALSE(handle.is_valid());
  19803. handle.error = Error::Success;
  19804. EXPECT_TRUE(handle.is_valid());
  19805. }
  19806. TEST(BodyReaderTest, Basic) {
  19807. MockStream stream("Hello, World!");
  19808. detail::BodyReader reader;
  19809. reader.stream = &stream;
  19810. reader.content_length = 13;
  19811. char buf[32];
  19812. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19813. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19814. EXPECT_TRUE(reader.eof);
  19815. }
  19816. TEST(BodyReaderTest, NoStream) {
  19817. detail::BodyReader reader;
  19818. char buf[32];
  19819. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19820. EXPECT_EQ(Error::Connection, reader.last_error);
  19821. }
  19822. TEST(BodyReaderTest, Error) {
  19823. MockStream stream("Hello, World!", 5);
  19824. detail::BodyReader reader;
  19825. reader.stream = &stream;
  19826. reader.content_length = 13;
  19827. char buf[32];
  19828. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19829. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19830. EXPECT_EQ(Error::Read, reader.last_error);
  19831. }
  19832. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19833. // Mock-based StreamHandle tests relying on private internals are removed.
  19834. class OpenStreamTest : public ::testing::Test {
  19835. protected:
  19836. void SetUp() override {
  19837. svr_.Get("/hello", [](const Request &, Response &res) {
  19838. res.set_content("Hello World!", "text/plain");
  19839. });
  19840. svr_.Get("/large", [](const Request &, Response &res) {
  19841. res.set_content(std::string(10000, 'X'), "text/plain");
  19842. });
  19843. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19844. res.set_content("Hello World!", "image/jpeg");
  19845. res.set_header("Content-Encoding", "UTF-8");
  19846. });
  19847. svr_.Get("/chunked", [](const Request &, Response &res) {
  19848. res.set_chunked_content_provider("text/plain",
  19849. [](size_t offset, DataSink &sink) {
  19850. if (offset < 15) {
  19851. sink.write("chunk", 5);
  19852. return true;
  19853. }
  19854. sink.done();
  19855. return true;
  19856. });
  19857. });
  19858. svr_.Get("/compressible", [](const Request &, Response &res) {
  19859. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19860. DataSink &sink) {
  19861. if (offset < 100 * 1024) {
  19862. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19863. sink.write(chunk.data(), chunk.size());
  19864. return true;
  19865. }
  19866. sink.done();
  19867. return true;
  19868. });
  19869. });
  19870. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19871. [](const Request & /*req*/, Response &res) {
  19872. auto i = new int(0);
  19873. res.set_header("Trailer", "Content-Length, X-Allowed");
  19874. res.set_chunked_content_provider(
  19875. "text/plain",
  19876. [i](size_t /*offset*/, DataSink &sink) {
  19877. switch (*i) {
  19878. case 0: sink.os << "123"; break;
  19879. case 1: sink.os << "456"; break;
  19880. case 2: sink.os << "789"; break;
  19881. case 3: {
  19882. sink.done_with_trailer(
  19883. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19884. } break;
  19885. }
  19886. (*i)++;
  19887. return true;
  19888. },
  19889. [i](bool success) {
  19890. EXPECT_TRUE(success);
  19891. delete i;
  19892. });
  19893. });
  19894. // Echo headers endpoint for header-related tests
  19895. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19896. std::string body;
  19897. for (const auto &h : req.headers) {
  19898. body.append(h.first);
  19899. body.push_back(':');
  19900. body.append(h.second);
  19901. body.push_back('\n');
  19902. }
  19903. res.set_content(body, "text/plain");
  19904. });
  19905. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19906. std::string body;
  19907. for (const auto &h : req.headers) {
  19908. body.append(h.first);
  19909. body.push_back(':');
  19910. body.append(h.second);
  19911. body.push_back('\n');
  19912. }
  19913. res.set_content(body, "text/plain");
  19914. });
  19915. port_ = svr_.bind_to_any_port("127.0.0.1");
  19916. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19917. svr_.wait_until_ready();
  19918. }
  19919. void TearDown() override {
  19920. svr_.stop();
  19921. if (thread_.joinable()) thread_.join();
  19922. }
  19923. Server svr_;
  19924. std::thread thread_;
  19925. int port_ = 0;
  19926. };
  19927. TEST_F(OpenStreamTest, Basic) {
  19928. Client cli("127.0.0.1", port_);
  19929. auto handle = cli.open_stream("GET", "/hello");
  19930. EXPECT_TRUE(handle.is_valid());
  19931. EXPECT_EQ("Hello World!", read_all(handle));
  19932. }
  19933. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19934. Client cli("127.0.0.1", port_);
  19935. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19936. ASSERT_TRUE(handle.is_valid());
  19937. EXPECT_EQ("Hello World!", read_all(handle));
  19938. }
  19939. TEST_F(OpenStreamTest, SmallBuffer) {
  19940. Client cli("127.0.0.1", port_);
  19941. auto handle = cli.open_stream("GET", "/hello");
  19942. std::string result;
  19943. char buf[4];
  19944. ssize_t n;
  19945. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19946. result.append(buf, static_cast<size_t>(n));
  19947. EXPECT_EQ("Hello World!", result);
  19948. }
  19949. TEST_F(OpenStreamTest, DefaultHeaders) {
  19950. Client cli("127.0.0.1", port_);
  19951. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19952. {
  19953. auto handle = cli.open_stream("GET", "/echo-headers");
  19954. ASSERT_TRUE(handle.is_valid());
  19955. auto body = read_all(handle);
  19956. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19957. std::string::npos);
  19958. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19959. std::string::npos);
  19960. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19961. }
  19962. // open_stream POST with body and no explicit content_type should NOT add
  19963. // text/plain Content-Type (behavior differs from non-streaming path), but
  19964. // should include Content-Length
  19965. {
  19966. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19967. ASSERT_TRUE(handle.is_valid());
  19968. auto body = read_all(handle);
  19969. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19970. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19971. }
  19972. // open_stream POST with explicit Content-Type should preserve it
  19973. {
  19974. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19975. {{"Content-Type", "application/custom"}},
  19976. "{}", "application/custom");
  19977. ASSERT_TRUE(handle.is_valid());
  19978. auto body = read_all(handle);
  19979. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19980. }
  19981. // User-specified User-Agent must not be overwritten for stream API
  19982. {
  19983. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19984. {{"User-Agent", "MyAgent/1.2"}});
  19985. ASSERT_TRUE(handle.is_valid());
  19986. auto body = read_all(handle);
  19987. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19988. }
  19989. }
  19990. TEST_F(OpenStreamTest, Large) {
  19991. Client cli("127.0.0.1", port_);
  19992. auto handle = cli.open_stream("GET", "/large");
  19993. EXPECT_EQ(10000u, read_all(handle).size());
  19994. }
  19995. TEST_F(OpenStreamTest, ConnectionError) {
  19996. Client cli("127.0.0.1", 9999);
  19997. auto handle = cli.open_stream("GET", "/hello");
  19998. EXPECT_FALSE(handle.is_valid());
  19999. }
  20000. TEST_F(OpenStreamTest, Chunked) {
  20001. Client cli("127.0.0.1", port_);
  20002. auto handle = cli.open_stream("GET", "/chunked");
  20003. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20004. "Transfer-Encoding") == "chunked");
  20005. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20006. }
  20007. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20008. Client cli("127.0.0.1", port_);
  20009. auto handle =
  20010. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20011. ASSERT_TRUE(handle.is_valid());
  20012. // Consume body to allow trailers to be received/parsed
  20013. auto body = read_all(handle);
  20014. // Explicitly parse trailers (ensure trailers are available for assertion)
  20015. handle.parse_trailers_if_needed();
  20016. EXPECT_EQ(std::string("123456789"), body);
  20017. // The response should include a Trailer header declaring both names
  20018. ASSERT_TRUE(handle.response);
  20019. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20020. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20021. handle.response->get_header_value("Trailer"));
  20022. // Prohibited trailer must not be present
  20023. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20024. // Allowed trailer should be present
  20025. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20026. EXPECT_EQ(std::string("yes"),
  20027. handle.response->get_trailer_value("X-Allowed"));
  20028. // Verify trailers are NOT present as regular headers
  20029. EXPECT_EQ(std::string(""),
  20030. handle.response->get_header_value("Content-Length"));
  20031. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20032. }
  20033. // Accepts one connection on an OS-assigned port, which it hands over through
  20034. // port_promise, reads the request head and sends back response. after_send,
  20035. // if given, runs on the connection before it is closed.
  20036. static std::thread
  20037. serve_single_response(std::promise<int> &port_promise,
  20038. const std::string &response,
  20039. std::function<void(socket_t)> after_send = nullptr) {
  20040. return std::thread([&port_promise, response, after_send] {
  20041. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20042. default_socket_options(srv);
  20043. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20044. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20045. sockaddr_in addr{};
  20046. addr.sin_family = AF_INET;
  20047. addr.sin_port = htons(0); // Let OS assign a free port
  20048. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20049. int opt = 1;
  20050. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20051. #ifdef _WIN32
  20052. reinterpret_cast<const char *>(&opt),
  20053. #else
  20054. &opt,
  20055. #endif
  20056. sizeof(opt));
  20057. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20058. ::listen(srv, 1) != 0) {
  20059. port_promise.set_value(-1);
  20060. detail::close_socket(srv);
  20061. return;
  20062. }
  20063. socklen_t addr_len = sizeof(addr);
  20064. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20065. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20066. sockaddr_in cli_addr{};
  20067. socklen_t cli_len = sizeof(cli_addr);
  20068. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20069. if (cli != INVALID_SOCKET) {
  20070. // Read the complete HTTP request (until the blank line that terminates
  20071. // headers) before sending the response. If the server closes the socket
  20072. // while the client's request data is still unread in the kernel receive
  20073. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20074. // connection on both sides: it discards the client's receive buffer
  20075. // (which already holds our response) and causes any in-progress write on
  20076. // the client to fail with ECONNRESET. Reading all request data first
  20077. // ensures close() emits a graceful FIN.
  20078. {
  20079. char rbuf[256];
  20080. std::string req;
  20081. while (req.find("\r\n\r\n") == std::string::npos) {
  20082. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20083. if (n <= 0) { break; }
  20084. req.append(rbuf, static_cast<size_t>(n));
  20085. }
  20086. }
  20087. ::send(cli,
  20088. #ifdef _WIN32
  20089. static_cast<const char *>(response.c_str()),
  20090. static_cast<int>(response.size()),
  20091. #else
  20092. response.c_str(), response.size(),
  20093. #endif
  20094. 0);
  20095. if (after_send) { after_send(cli); }
  20096. detail::close_socket(cli);
  20097. }
  20098. detail::close_socket(srv);
  20099. });
  20100. }
  20101. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20102. #ifndef _WIN32
  20103. signal(SIGPIPE, SIG_IGN);
  20104. #endif
  20105. std::promise<int> port_promise;
  20106. auto port_future = port_promise.get_future();
  20107. auto server_thread =
  20108. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20109. "Content-Type: text/plain\r\n"
  20110. "Content-Length: not-a-number\r\n"
  20111. "Connection: close\r\n"
  20112. "\r\n"
  20113. "hello");
  20114. auto port = port_future.get();
  20115. ASSERT_GT(port, 0);
  20116. Client cli("127.0.0.1", port);
  20117. auto handle = cli.open_stream("GET", "/");
  20118. EXPECT_FALSE(handle.is_valid());
  20119. server_thread.join();
  20120. }
  20121. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20122. #ifndef _WIN32
  20123. signal(SIGPIPE, SIG_IGN);
  20124. #endif
  20125. std::promise<int> port_promise;
  20126. auto port_future = port_promise.get_future();
  20127. auto server_thread = serve_single_response(
  20128. port_promise, "HTTP/1.1 200 OK\r\n"
  20129. "Content-Type: text/plain\r\n"
  20130. "Content-Length: 99999999999999999999999999\r\n"
  20131. "Connection: close\r\n"
  20132. "\r\n"
  20133. "hello");
  20134. auto port = port_future.get();
  20135. ASSERT_GT(port, 0);
  20136. // Historically std::stoull would throw std::out_of_range here and crash
  20137. // the process, then parsing silently clamped to a bogus framing length and
  20138. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20139. // so the stream fails to open, matching the not-a-number case above. The
  20140. // process still must NOT terminate.
  20141. Client cli("127.0.0.1", port);
  20142. auto handle = cli.open_stream("GET", "/");
  20143. EXPECT_FALSE(handle.is_valid());
  20144. server_thread.join();
  20145. }
  20146. #ifndef _WIN32
  20147. // As above for the body of a streamed request: a send() cut short by the write
  20148. // timeout must not leave the rest of the body unsent.
  20149. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20150. signal(SIGPIPE, SIG_IGN);
  20151. Server svr;
  20152. svr.set_socket_options([](socket_t sock) {
  20153. int size = 8192;
  20154. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20155. reinterpret_cast<const char *>(&size), sizeof(size));
  20156. });
  20157. svr.Post("/size", [](const Request &, Response &res,
  20158. const ContentReader &content_reader) {
  20159. // Outlast the client's write timeout before reading the body.
  20160. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20161. size_t received = 0;
  20162. content_reader([&](const char *, size_t len) {
  20163. received += len;
  20164. return true;
  20165. });
  20166. res.set_content(std::to_string(received), "text/plain");
  20167. });
  20168. auto port = svr.bind_to_any_port(HOST);
  20169. std::thread t([&]() { svr.listen_after_bind(); });
  20170. auto se = detail::scope_exit([&] {
  20171. svr.stop();
  20172. t.join();
  20173. });
  20174. svr.wait_until_ready();
  20175. Client cli(HOST, port);
  20176. cli.set_write_timeout(0, 500000);
  20177. cli.set_socket_options([](socket_t sock) {
  20178. int size = 8192;
  20179. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20180. reinterpret_cast<const char *>(&size), sizeof(size));
  20181. });
  20182. const std::string body(4 * 1024 * 1024, 'A');
  20183. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20184. "application/octet-stream");
  20185. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20186. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20187. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20188. }
  20189. #endif
  20190. // Serves `response` to the single request `fn` makes with a fresh client.
  20191. template <typename Fn>
  20192. static void with_single_response(const std::string &response, Fn fn) {
  20193. #ifndef _WIN32
  20194. signal(SIGPIPE, SIG_IGN);
  20195. #endif
  20196. std::promise<int> port_promise;
  20197. auto port_future = port_promise.get_future();
  20198. auto server_thread = serve_single_response(port_promise, response);
  20199. auto se = detail::scope_exit([&] { server_thread.join(); });
  20200. auto port = port_future.get();
  20201. ASSERT_GT(port, 0);
  20202. Client cli("127.0.0.1", port);
  20203. fn(cli);
  20204. }
  20205. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20206. // too, also in a build without the decoder for the advertised coding.
  20207. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20208. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20209. const auto response = "HTTP/1.1 200 OK\r\n"
  20210. "Content-Encoding: gzip\r\n"
  20211. "Content-Length: " +
  20212. std::to_string(gzipped.size()) +
  20213. "\r\n"
  20214. "Connection: close\r\n\r\n" +
  20215. gzipped;
  20216. with_single_response(response, [&](Client &cli) {
  20217. cli.set_decompress(false);
  20218. auto handle = cli.open_stream("GET", "/");
  20219. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20220. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20221. EXPECT_EQ(gzipped, read_all(handle));
  20222. EXPECT_FALSE(handle.has_read_error());
  20223. });
  20224. with_single_response(response, [&](Client &cli) {
  20225. cli.set_decompress(false);
  20226. auto res = stream::Get(cli, "/", 7);
  20227. ASSERT_TRUE(res) << to_string(res.error());
  20228. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20229. EXPECT_EQ(gzipped, res.read_all());
  20230. EXPECT_FALSE(res.has_read_error());
  20231. });
  20232. }
  20233. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20234. // Neither Content-Length nor chunked: the body ends at the close
  20235. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20236. "Connection: close\r\n"
  20237. "\r\n"
  20238. "hello";
  20239. with_single_response(close_delimited, [](Client &cli) {
  20240. auto handle = cli.open_stream("GET", "/");
  20241. ASSERT_TRUE(handle.is_valid());
  20242. EXPECT_EQ("hello", read_all(handle));
  20243. EXPECT_FALSE(handle.has_read_error());
  20244. });
  20245. // A close before the end of the Content-Length is still an error
  20246. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20247. "Content-Length: 10\r\n"
  20248. "\r\n"
  20249. "hello";
  20250. with_single_response(short_content_length, [](Client &cli) {
  20251. auto handle = cli.open_stream("GET", "/");
  20252. ASSERT_TRUE(handle.is_valid());
  20253. read_all(handle);
  20254. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20255. });
  20256. // So is a close before the last chunk
  20257. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20258. "Transfer-Encoding: chunked\r\n"
  20259. "\r\n"
  20260. "5\r\nhello\r\n";
  20261. with_single_response(short_chunked, [](Client &cli) {
  20262. auto handle = cli.open_stream("GET", "/");
  20263. ASSERT_TRUE(handle.is_valid());
  20264. read_all(handle);
  20265. EXPECT_TRUE(handle.has_read_error());
  20266. });
  20267. }
  20268. #ifdef CPPHTTPLIB_SSL_ENABLED
  20269. // Serves `response` to one request, then closes with or without a close_notify
  20270. template <typename Fn>
  20271. static void with_single_tls_response(const std::string &response,
  20272. bool close_notify, Fn fn) {
  20273. #ifndef _WIN32
  20274. signal(SIGPIPE, SIG_IGN);
  20275. #endif
  20276. std::promise<int> port_promise;
  20277. auto port_future = port_promise.get_future();
  20278. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20279. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20280. default_socket_options(srv);
  20281. sockaddr_in addr{};
  20282. addr.sin_family = AF_INET;
  20283. addr.sin_port = htons(0);
  20284. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20285. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20286. ::listen(srv, 1) != 0) {
  20287. port_promise.set_value(-1);
  20288. detail::close_socket(srv);
  20289. return;
  20290. }
  20291. socklen_t addr_len = sizeof(addr);
  20292. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20293. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20294. auto cli = ::accept(srv, nullptr, nullptr);
  20295. if (cli != INVALID_SOCKET) {
  20296. auto ctx = tls::create_server_context();
  20297. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20298. nullptr);
  20299. auto session = tls::create_session(ctx, cli);
  20300. tls::TlsError err;
  20301. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20302. // The request head first, so that closing the socket sends a FIN
  20303. // rather than an RST for the unread bytes.
  20304. std::string req;
  20305. char buf[256];
  20306. while (req.find("\r\n\r\n") == std::string::npos) {
  20307. auto n = tls::read(session, buf, sizeof(buf), err);
  20308. if (n <= 0) { break; }
  20309. req.append(buf, static_cast<size_t>(n));
  20310. }
  20311. size_t sent = 0;
  20312. while (sent < response.size()) {
  20313. auto n = tls::write(session, response.data() + sent,
  20314. response.size() - sent, err);
  20315. if (n <= 0) { break; }
  20316. sent += static_cast<size_t>(n);
  20317. }
  20318. if (close_notify) { tls::shutdown(session, true); }
  20319. }
  20320. tls::free_session(session);
  20321. detail::close_socket(cli);
  20322. tls::free_context(ctx);
  20323. }
  20324. detail::close_socket(srv);
  20325. });
  20326. auto se = detail::scope_exit([&] { server_thread.join(); });
  20327. auto port = port_future.get();
  20328. ASSERT_GT(port, 0);
  20329. SSLClient cli("127.0.0.1", port);
  20330. cli.enable_server_certificate_verification(false);
  20331. fn(cli);
  20332. }
  20333. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20334. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20335. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20336. "Connection: close\r\n"
  20337. "\r\n"
  20338. "hello";
  20339. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20340. auto res = cli.Get("/");
  20341. ASSERT_TRUE(res) << to_string(res.error());
  20342. EXPECT_EQ("hello", res->body);
  20343. });
  20344. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20345. auto res = cli.Get("/");
  20346. ASSERT_FALSE(res);
  20347. EXPECT_EQ(Error::Read, res.error());
  20348. });
  20349. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20350. auto handle = cli.open_stream("GET", "/");
  20351. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20352. read_all(handle);
  20353. EXPECT_TRUE(handle.has_read_error());
  20354. });
  20355. // A framed body ends where its framing says, with or without the alert
  20356. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20357. "Content-Length: 5\r\n"
  20358. "Connection: close\r\n"
  20359. "\r\n"
  20360. "hello";
  20361. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20362. auto res = cli.Get("/");
  20363. ASSERT_TRUE(res) << to_string(res.error());
  20364. EXPECT_EQ("hello", res->body);
  20365. });
  20366. }
  20367. #endif
  20368. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20369. const char *responses[] = {
  20370. "HTTP/1.1 103 Early Hints\r\n"
  20371. "Link: </style.css>; rel=preload\r\n"
  20372. "\r\n"
  20373. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20374. "HTTP/1.1 100 Continue\r\n"
  20375. "X-Note: interim\r\n"
  20376. "\r\n"
  20377. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20378. };
  20379. for (auto response : responses) {
  20380. with_single_response(response, [](Client &cli) {
  20381. auto res = cli.Get("/");
  20382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20383. EXPECT_EQ(StatusCode::OK_200, res->status);
  20384. EXPECT_EQ("ok", res->body);
  20385. });
  20386. }
  20387. }
  20388. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20389. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20390. const std::string final_response =
  20391. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20392. std::string interims;
  20393. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20394. interims += interim;
  20395. }
  20396. with_single_response(interims + final_response, [](Client &cli) {
  20397. auto res = cli.Get("/");
  20398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20399. EXPECT_EQ("ok", res->body);
  20400. });
  20401. with_single_response(interims + interim + final_response, [](Client &cli) {
  20402. auto res = cli.Get("/");
  20403. ASSERT_FALSE(res);
  20404. EXPECT_EQ(Error::Read, res.error());
  20405. });
  20406. }
  20407. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20408. #ifndef _WIN32
  20409. signal(SIGPIPE, SIG_IGN);
  20410. #endif
  20411. // The server answers the head without asking for the body. Bytes it then
  20412. // reads on the connection would be taken for the body the request declared.
  20413. auto closed_by_client = false;
  20414. std::promise<int> port_promise;
  20415. auto server_thread = serve_single_response(
  20416. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20417. [&](socket_t sock) {
  20418. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20419. char buf[256];
  20420. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20421. });
  20422. Client cli("127.0.0.1", port_promise.get_future().get());
  20423. cli.set_keep_alive(true);
  20424. cli.set_read_timeout(1, 0);
  20425. // Long enough for the client to send Expect: 100-continue.
  20426. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20428. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20429. cli.Get("/second");
  20430. server_thread.join();
  20431. EXPECT_TRUE(closed_by_client);
  20432. }
  20433. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20434. // Long enough for the client to send Expect: 100-continue
  20435. with_single_response(
  20436. "HTTP/1.1 103 Early Hints\r\n"
  20437. "Link: </style.css>; rel=preload\r\n"
  20438. "\r\n"
  20439. "HTTP/1.1 401 Unauthorized\r\n"
  20440. "Content-Length: 0\r\n\r\n",
  20441. [](Client &cli) {
  20442. cli.set_read_timeout(2, 0);
  20443. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20445. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20446. });
  20447. }
  20448. #ifdef CPPHTTPLIB_SSL_ENABLED
  20449. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20450. #ifndef _WIN32
  20451. signal(SIGPIPE, SIG_IGN);
  20452. #endif
  20453. auto reused = false;
  20454. std::promise<int> port_promise;
  20455. auto server_thread = serve_single_response(
  20456. port_promise,
  20457. "HTTP/1.1 401 Unauthorized\r\n"
  20458. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20459. "Content-Length: 0\r\n\r\n",
  20460. [&](socket_t sock) {
  20461. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20462. char buf[256];
  20463. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20464. });
  20465. Client cli("127.0.0.1", port_promise.get_future().get());
  20466. cli.set_keep_alive(true);
  20467. cli.set_digest_auth("user", "pass");
  20468. cli.set_read_timeout(1, 0);
  20469. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20470. server_thread.join();
  20471. EXPECT_FALSE(reused);
  20472. }
  20473. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20474. // Any other answer to CONNECT would read as the origin's response.
  20475. struct {
  20476. const char *response;
  20477. bool passed_on;
  20478. } cases[] = {
  20479. {"HTTP/1.1 201 Created\r\n"
  20480. "Set-Cookie: session=from-proxy\r\n"
  20481. "Content-Length: 0\r\n\r\n",
  20482. false},
  20483. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20484. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20485. "Content-Length: 0\r\n\r\n",
  20486. true},
  20487. };
  20488. for (const auto &c : cases) {
  20489. std::promise<int> port_promise;
  20490. auto server_thread = serve_single_response(port_promise, c.response);
  20491. SSLClient cli("example.com", 443);
  20492. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20493. auto res = cli.Get("/");
  20494. server_thread.join();
  20495. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20496. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20497. if (res) {
  20498. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20499. }
  20500. }
  20501. }
  20502. #endif
  20503. // Records the client's error logger calls as "error METHOD path", or
  20504. // "error null" for a call without a request
  20505. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20506. return [&log](const Error &err, const Request *req) {
  20507. log.push_back(to_string(err) + " " +
  20508. (req ? req->method + " " + req->path : "null"));
  20509. };
  20510. }
  20511. // A failed request is reported once, with the request the caller made
  20512. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20513. Server svr;
  20514. svr.Get("/big", [](const Request &, Response &res) {
  20515. res.set_content(std::string(100000, 'b'), "text/plain");
  20516. });
  20517. auto port = svr.bind_to_any_port(HOST);
  20518. std::thread t([&]() { svr.listen_after_bind(); });
  20519. auto se = detail::scope_exit([&] {
  20520. svr.stop();
  20521. t.join();
  20522. });
  20523. svr.wait_until_ready();
  20524. Client cli(HOST, port);
  20525. std::vector<std::string> log;
  20526. cli.set_error_logger(record_errors(log));
  20527. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20528. cli.Get("/big", [](const char *, size_t) { return false; });
  20529. EXPECT_EQ(expected, log);
  20530. log.clear();
  20531. cli.Get("/big", [](size_t, size_t) { return false; });
  20532. EXPECT_EQ(expected, log);
  20533. }
  20534. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20535. // Fails while the body is read
  20536. auto broken = [](const Request &, Response &res) {
  20537. res.set_content_provider(10, "text/plain",
  20538. [](size_t, size_t, DataSink &) { return false; });
  20539. };
  20540. Server other;
  20541. other.Get("/broken", broken);
  20542. auto other_port = other.bind_to_any_port(HOST);
  20543. std::thread other_t([&]() { other.listen_after_bind(); });
  20544. auto other_se = detail::scope_exit([&] {
  20545. other.stop();
  20546. other_t.join();
  20547. });
  20548. other.wait_until_ready();
  20549. Server svr;
  20550. svr.Get("/broken", broken);
  20551. svr.Get("/same-origin",
  20552. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20553. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20554. res.set_redirect("http://" + std::string(HOST) + ":" +
  20555. std::to_string(other_port) + "/broken");
  20556. });
  20557. auto port = svr.bind_to_any_port(HOST);
  20558. std::thread t([&]() { svr.listen_after_bind(); });
  20559. auto se = detail::scope_exit([&] {
  20560. svr.stop();
  20561. t.join();
  20562. });
  20563. svr.wait_until_ready();
  20564. Client cli(HOST, port);
  20565. cli.set_follow_location(true);
  20566. std::vector<std::string> log;
  20567. cli.set_error_logger(record_errors(log));
  20568. for (auto path : {"/same-origin", "/cross-origin"}) {
  20569. log.clear();
  20570. auto res = cli.Get(path);
  20571. ASSERT_FALSE(res);
  20572. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20573. log);
  20574. }
  20575. }
  20576. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20577. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20578. std::vector<std::string> log;
  20579. cli.set_error_logger(record_errors(log));
  20580. auto handle = cli.open_stream("GET", "/x");
  20581. EXPECT_FALSE(handle.is_valid());
  20582. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20583. log);
  20584. });
  20585. }
  20586. #ifdef CPPHTTPLIB_SSL_ENABLED
  20587. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20588. // Not a TLS server, so the handshake fails. It waits for a request line in
  20589. // the handshake bytes, so a short read timeout lets it close quickly.
  20590. Server svr;
  20591. svr.set_read_timeout(0, 100000);
  20592. svr.Get("/x", [](const Request &, Response &res) {
  20593. res.set_content("x", "text/plain");
  20594. });
  20595. auto port = svr.bind_to_any_port(HOST);
  20596. std::thread t([&]() { svr.listen_after_bind(); });
  20597. auto se = detail::scope_exit([&] {
  20598. svr.stop();
  20599. t.join();
  20600. });
  20601. svr.wait_until_ready();
  20602. std::vector<std::string> log;
  20603. SSLClient cli(HOST, port);
  20604. cli.enable_server_certificate_verification(false);
  20605. cli.set_error_logger(record_errors(log));
  20606. auto res = cli.Get("/x");
  20607. ASSERT_FALSE(res);
  20608. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20609. log.clear();
  20610. auto handle = cli.open_stream("GET", "/x");
  20611. EXPECT_FALSE(handle.is_valid());
  20612. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20613. log.clear();
  20614. SSLClient no_ca(HOST, port);
  20615. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20616. no_ca.set_error_logger(record_errors(log));
  20617. res = no_ca.Get("/x");
  20618. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20619. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20620. }
  20621. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20622. #ifndef _WIN32
  20623. signal(SIGPIPE, SIG_IGN);
  20624. #endif
  20625. // Refused, answered with a challenge, or closed without an answer
  20626. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20627. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20628. "Content-Length: 0\r\n\r\n",
  20629. ""}) {
  20630. std::promise<int> port_promise;
  20631. auto server_thread = serve_single_response(port_promise, response);
  20632. SSLClient cli("example.com", 443);
  20633. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20634. std::vector<std::string> log;
  20635. cli.set_error_logger(record_errors(log));
  20636. auto res = cli.Get("/");
  20637. server_thread.join();
  20638. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20639. << response;
  20640. }
  20641. }
  20642. #endif
  20643. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20644. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20645. // the chunked coding and drop Content-Length, so a front-end that trusts
  20646. // Content-Length would disagree about where the body ends (response
  20647. // smuggling). The client must reject such a response.
  20648. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20649. for (const char *te : {"chunked", "gzip, chunked"}) {
  20650. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20651. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20652. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20653. "5\r\nhello\r\n0\r\n\r\n";
  20654. with_single_response(response, [&](Client &cli) {
  20655. auto res = cli.Get("/");
  20656. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20657. EXPECT_EQ(Error::Read, res.error()) << te;
  20658. });
  20659. with_single_response(response, [&](Client &cli) {
  20660. auto handle = cli.open_stream("GET", "/");
  20661. EXPECT_FALSE(handle.is_valid()) << te;
  20662. EXPECT_EQ(Error::Read, handle.error) << te;
  20663. });
  20664. }
  20665. }
  20666. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20667. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20668. // closing the connection (unlike a request, which must be rejected).
  20669. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20670. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20671. "Transfer-Encoding: chunked\r\n"
  20672. "Connection: close\r\n"
  20673. "\r\n"
  20674. "5\r\nhello\r\n0\r\n\r\n",
  20675. "HTTP/1.1 200 OK\r\n"
  20676. "Transfer-Encoding: gzip\r\n"
  20677. "Connection: close\r\n"
  20678. "\r\n"
  20679. "hello"}) {
  20680. with_single_response(response, [&](Client &cli) {
  20681. auto res = cli.Get("/");
  20682. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20683. EXPECT_EQ("hello", res->body);
  20684. });
  20685. with_single_response(response, [&](Client &cli) {
  20686. auto handle = cli.open_stream("GET", "/");
  20687. ASSERT_TRUE(handle.is_valid()) << response;
  20688. EXPECT_EQ("hello", read_all(handle));
  20689. });
  20690. }
  20691. }
  20692. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20693. // framing headers describe nothing to read and must not be rejected.
  20694. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20695. const std::string framing = "Content-Length: 5\r\n"
  20696. "Transfer-Encoding: chunked\r\n"
  20697. "Connection: close\r\n"
  20698. "\r\n";
  20699. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20700. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20701. });
  20702. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20703. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20704. });
  20705. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20706. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20707. with_single_response(response, [&](Client &cli) {
  20708. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20709. });
  20710. with_single_response(response, [&](Client &cli) {
  20711. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20712. });
  20713. }
  20714. }
  20715. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20716. // header section, so a stream opened on one has nothing to read, whatever
  20717. // framing or coding headers it carries.
  20718. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20719. struct Case {
  20720. const char *method;
  20721. const char *status;
  20722. };
  20723. // A reader of the declared body reports an early close when nothing
  20724. // follows, and hands back what does.
  20725. struct Framing {
  20726. const char *headers;
  20727. const char *after;
  20728. };
  20729. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20730. Case{"GET", "304 Not Modified"}}) {
  20731. for (const auto &f :
  20732. {Framing{"Content-Length: 5\r\n", ""},
  20733. Framing{"Content-Length: 5\r\n", "hello"},
  20734. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20735. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20736. // Not decoded, so a build without Brotli opens it too
  20737. Framing{"Content-Encoding: br\r\n", ""}}) {
  20738. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20739. "Connection: close\r\n"
  20740. "\r\n" +
  20741. f.after;
  20742. with_single_response(response, [&](Client &cli) {
  20743. auto handle = cli.open_stream(c.method, "/");
  20744. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20745. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20746. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20747. });
  20748. }
  20749. }
  20750. }
  20751. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20752. // response, is faulty framing, so the connection is not reused after it.
  20753. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20754. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20755. "Content-Length: 0\r\n"
  20756. "Transfer-Encoding: chunked\r\n"
  20757. "\r\n"
  20758. "5\r\nhello\r\n0\r\n\r\n",
  20759. "HTTP/1.0 200 Connection established\r\n"
  20760. "Connection: keep-alive\r\n"
  20761. "Transfer-Encoding: chunked\r\n"
  20762. "\r\n"
  20763. "5\r\nhello\r\n0\r\n\r\n"}) {
  20764. with_single_response(response, [&](Client &cli) {
  20765. cli.set_keep_alive(true);
  20766. auto res = cli.Get("/");
  20767. ASSERT_TRUE(res) << response;
  20768. EXPECT_EQ("hello", res->body);
  20769. EXPECT_FALSE(cli.is_socket_open()) << response;
  20770. });
  20771. }
  20772. }
  20773. // A payload max length of 0 means no limit, however the body is framed.
  20774. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20775. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20776. "Transfer-Encoding: chunked\r\n"
  20777. "\r\n"
  20778. "5\r\nhello\r\n0\r\n\r\n",
  20779. "HTTP/1.1 200 OK\r\n"
  20780. "Connection: close\r\n"
  20781. "\r\n"
  20782. "hello"}) {
  20783. with_single_response(response, [&](Client &cli) {
  20784. cli.set_payload_max_length(0);
  20785. auto res = cli.Get("/");
  20786. ASSERT_TRUE(res) << response;
  20787. EXPECT_EQ("hello", res->body) << response;
  20788. });
  20789. }
  20790. }
  20791. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20792. Server svr;
  20793. svr.set_payload_max_length(0);
  20794. svr.Post("/echo", [](const Request &req, Response &res) {
  20795. res.set_content(req.body, "text/plain");
  20796. });
  20797. auto port = svr.bind_to_any_port(HOST);
  20798. thread t = thread([&] { svr.listen_after_bind(); });
  20799. auto se = detail::scope_exit([&] {
  20800. svr.stop();
  20801. t.join();
  20802. ASSERT_FALSE(svr.is_running());
  20803. });
  20804. svr.wait_until_ready();
  20805. Client cli(HOST, port);
  20806. auto res = cli.Post(
  20807. "/echo",
  20808. [](size_t /*offset*/, DataSink &sink) {
  20809. sink.write("hello", 5);
  20810. sink.done();
  20811. return true;
  20812. },
  20813. "text/plain");
  20814. ASSERT_TRUE(res);
  20815. EXPECT_EQ(StatusCode::OK_200, res->status);
  20816. EXPECT_EQ("hello", res->body);
  20817. }
  20818. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20819. TEST_F(OpenStreamTest, Gzip) {
  20820. Client cli("127.0.0.1", port_);
  20821. auto handle = cli.open_stream("GET", "/compressible", {},
  20822. {{"Accept-Encoding", "gzip"}});
  20823. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20824. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20825. }
  20826. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20827. Client cli("127.0.0.1", port_);
  20828. auto handle =
  20829. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20830. {{"Accept-Encoding", "gzip"}});
  20831. ASSERT_TRUE(handle.is_valid());
  20832. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20833. EXPECT_EQ("123456789", read_all(handle));
  20834. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20835. }
  20836. #endif
  20837. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20838. TEST_F(OpenStreamTest, Brotli) {
  20839. Client cli("127.0.0.1", port_);
  20840. auto handle =
  20841. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20842. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20843. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20844. }
  20845. #endif
  20846. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20847. TEST_F(OpenStreamTest, Zstd) {
  20848. Client cli("127.0.0.1", port_);
  20849. auto handle = cli.open_stream("GET", "/compressible", {},
  20850. {{"Accept-Encoding", "zstd"}});
  20851. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20852. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20853. }
  20854. #endif
  20855. #ifdef CPPHTTPLIB_SSL_ENABLED
  20856. class SSLOpenStreamTest : public ::testing::Test {
  20857. protected:
  20858. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20859. void SetUp() override {
  20860. svr_.Get("/hello", [](const Request &, Response &res) {
  20861. res.set_content("Hello SSL World!", "text/plain");
  20862. });
  20863. svr_.Get("/chunked", [](const Request &, Response &res) {
  20864. res.set_chunked_content_provider("text/plain",
  20865. [](size_t offset, DataSink &sink) {
  20866. if (offset < 15) {
  20867. sink.write("chunk", 5);
  20868. return true;
  20869. }
  20870. sink.done();
  20871. return true;
  20872. });
  20873. });
  20874. svr_.Post("/echo", [](const Request &req, Response &res) {
  20875. res.set_content(req.body, req.get_header_value("Content-Type"));
  20876. });
  20877. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20878. std::string body = req.body;
  20879. res.set_chunked_content_provider(
  20880. "text/plain", [body](size_t offset, DataSink &sink) {
  20881. if (offset < body.size()) {
  20882. sink.write(body.data() + offset, body.size() - offset);
  20883. }
  20884. sink.done();
  20885. return true;
  20886. });
  20887. });
  20888. port_ = svr_.bind_to_any_port("127.0.0.1");
  20889. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20890. svr_.wait_until_ready();
  20891. }
  20892. void TearDown() override {
  20893. svr_.stop();
  20894. if (thread_.joinable()) thread_.join();
  20895. }
  20896. SSLServer svr_;
  20897. std::thread thread_;
  20898. int port_ = 0;
  20899. };
  20900. TEST_F(SSLOpenStreamTest, Basic) {
  20901. SSLClient cli("127.0.0.1", port_);
  20902. cli.enable_server_certificate_verification(false);
  20903. auto handle = cli.open_stream("GET", "/hello");
  20904. ASSERT_TRUE(handle.is_valid());
  20905. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20906. }
  20907. TEST_F(SSLOpenStreamTest, Chunked) {
  20908. SSLClient cli("127.0.0.1", port_);
  20909. cli.enable_server_certificate_verification(false);
  20910. auto handle = cli.open_stream("GET", "/chunked");
  20911. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20912. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20913. "Transfer-Encoding") == "chunked");
  20914. auto body = read_all(handle);
  20915. EXPECT_EQ("chunkchunkchunk", body);
  20916. }
  20917. TEST_F(SSLOpenStreamTest, Post) {
  20918. SSLClient cli("127.0.0.1", port_);
  20919. cli.enable_server_certificate_verification(false);
  20920. auto handle =
  20921. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20922. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20923. EXPECT_EQ(200, handle.response->status);
  20924. auto body = read_all(handle);
  20925. EXPECT_EQ("Hello SSL POST", body);
  20926. }
  20927. TEST_F(SSLOpenStreamTest, PostChunked) {
  20928. SSLClient cli("127.0.0.1", port_);
  20929. cli.enable_server_certificate_verification(false);
  20930. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20931. "Chunked SSL Data", "text/plain");
  20932. ASSERT_TRUE(handle.is_valid());
  20933. EXPECT_EQ(200, handle.response->status);
  20934. auto body = read_all(handle);
  20935. EXPECT_EQ("Chunked SSL Data", body);
  20936. }
  20937. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20938. // Content-Length is terminated by the server closing the connection. When the
  20939. // SSL peer sends a close_notify after the body, the client must treat it as a
  20940. // clean EOF and return a successful response rather than an error.
  20941. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20943. ASSERT_TRUE(svr.is_valid());
  20944. svr.set_keep_alive_max_count(1);
  20945. const std::string expected_body = "Hello from connection-close response!";
  20946. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20947. res.set_content_provider("text/plain",
  20948. [&](size_t offset, DataSink &sink) -> bool {
  20949. if (offset < expected_body.size()) {
  20950. sink.write(expected_body.data() + offset,
  20951. expected_body.size() - offset);
  20952. }
  20953. sink.done();
  20954. return true;
  20955. });
  20956. });
  20957. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20958. auto se = detail::scope_exit([&] {
  20959. svr.stop();
  20960. listen_thread.join();
  20961. ASSERT_FALSE(svr.is_running());
  20962. });
  20963. svr.wait_until_ready();
  20964. SSLClient cli(HOST, PORT);
  20965. cli.enable_server_certificate_verification(false);
  20966. auto res = cli.Get("/no-content-length");
  20967. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20968. EXPECT_EQ(StatusCode::OK_200, res->status);
  20969. EXPECT_EQ(expected_body, res->body);
  20970. }
  20971. #endif // CPPHTTPLIB_SSL_ENABLED
  20972. //==============================================================================
  20973. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20974. // results for various scenarios.
  20975. //==============================================================================
  20976. TEST(ParityTest, GetVsOpenStream) {
  20977. Server svr;
  20978. const std::string path = "/parity";
  20979. const std::string content = "Parity test content: hello world";
  20980. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20981. res.set_content(content, "text/plain");
  20982. });
  20983. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20984. auto se = detail::scope_exit([&] {
  20985. svr.stop();
  20986. t.join();
  20987. ASSERT_FALSE(svr.is_running());
  20988. });
  20989. svr.wait_until_ready();
  20990. Client cli(HOST, PORT);
  20991. // Non-stream path
  20992. auto r1 = cli.Get(path);
  20993. ASSERT_TRUE(r1);
  20994. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20995. // Stream path
  20996. auto h = cli.open_stream("GET", path);
  20997. ASSERT_TRUE(h.is_valid());
  20998. EXPECT_EQ(r1->body, read_all(h));
  20999. }
  21000. // Helper to compress data with provided compressor type T
  21001. template <typename Compressor>
  21002. static std::string compress_payload_for_parity(const std::string &in) {
  21003. std::string out;
  21004. Compressor compressor;
  21005. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21006. [&](const char *data, size_t n) {
  21007. out.append(data, n);
  21008. return true;
  21009. });
  21010. EXPECT_TRUE(ok);
  21011. return out;
  21012. }
  21013. // Helper function for compression parity tests
  21014. template <typename Compressor>
  21015. static void test_compression_parity(const std::string &original,
  21016. const std::string &path,
  21017. const std::string &encoding) {
  21018. const std::string compressed =
  21019. compress_payload_for_parity<Compressor>(original);
  21020. Server svr;
  21021. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21022. res.set_content(compressed, "application/octet-stream");
  21023. res.set_header("Content-Encoding", encoding);
  21024. });
  21025. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21026. auto se = detail::scope_exit([&] {
  21027. svr.stop();
  21028. t.join();
  21029. ASSERT_FALSE(svr.is_running());
  21030. });
  21031. svr.wait_until_ready();
  21032. Client cli(HOST, PORT);
  21033. // Non-streaming
  21034. {
  21035. auto res = cli.Get(path);
  21036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21037. EXPECT_EQ(StatusCode::OK_200, res->status);
  21038. EXPECT_EQ(original, res->body);
  21039. }
  21040. // Streaming
  21041. {
  21042. auto h = cli.open_stream("GET", path);
  21043. ASSERT_TRUE(h.is_valid());
  21044. EXPECT_EQ(original, read_all(h));
  21045. }
  21046. }
  21047. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21048. TEST(ParityTest, Gzip) {
  21049. test_compression_parity<detail::gzip_compressor>(
  21050. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21051. }
  21052. #endif
  21053. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21054. TEST(ParityTest, Brotli) {
  21055. test_compression_parity<detail::brotli_compressor>(
  21056. "Hello, brotli parity test payload", "/parity-br", "br");
  21057. }
  21058. #endif
  21059. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21060. TEST(ParityTest, Zstd) {
  21061. test_compression_parity<detail::zstd_compressor>(
  21062. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21063. }
  21064. #endif
  21065. //==============================================================================
  21066. // New Stream API Tests
  21067. //==============================================================================
  21068. inline std::string read_body(httplib::stream::Result &result) {
  21069. std::string body;
  21070. while (result.next()) {
  21071. body.append(result.data(), result.size());
  21072. }
  21073. return body;
  21074. }
  21075. TEST(ClientConnectionTest, Basic) {
  21076. httplib::ClientConnection conn;
  21077. EXPECT_FALSE(conn.is_open());
  21078. conn.sock = 1;
  21079. EXPECT_TRUE(conn.is_open());
  21080. httplib::ClientConnection conn2(std::move(conn));
  21081. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21082. conn2.sock = INVALID_SOCKET;
  21083. }
  21084. // Unified test server for all stream::* tests
  21085. class StreamApiTest : public ::testing::Test {
  21086. protected:
  21087. void SetUp() override {
  21088. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21089. res.set_content("Hello World!", "text/plain");
  21090. });
  21091. svr_.Get("/echo-params",
  21092. [](const httplib::Request &req, httplib::Response &res) {
  21093. std::string r;
  21094. for (const auto &p : req.params) {
  21095. if (!r.empty()) r += "&";
  21096. r += p.first + "=" + p.second;
  21097. }
  21098. res.set_content(r, "text/plain");
  21099. });
  21100. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21101. res.set_content(req.body, req.get_header_value("Content-Type"));
  21102. });
  21103. svr_.Post("/echo-headers",
  21104. [](const httplib::Request &req, httplib::Response &res) {
  21105. std::string r;
  21106. for (const auto &h : req.headers)
  21107. r += h.first + ": " + h.second + "\n";
  21108. res.set_content(r, "text/plain");
  21109. });
  21110. svr_.Post("/echo-params",
  21111. [](const httplib::Request &req, httplib::Response &res) {
  21112. std::string r = "params:";
  21113. for (const auto &p : req.params)
  21114. r += p.first + "=" + p.second + ";";
  21115. res.set_content(r + " body:" + req.body, "text/plain");
  21116. });
  21117. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21118. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21119. });
  21120. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21121. res.set_content("PUT:" + req.body, "text/plain");
  21122. });
  21123. svr_.Patch("/echo",
  21124. [](const httplib::Request &req, httplib::Response &res) {
  21125. res.set_content("PATCH:" + req.body, "text/plain");
  21126. });
  21127. svr_.Delete(
  21128. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21129. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21130. "text/plain");
  21131. });
  21132. svr_.Get("/head-test",
  21133. [](const httplib::Request &, httplib::Response &res) {
  21134. res.set_content("body for HEAD", "text/plain");
  21135. });
  21136. svr_.Options("/options",
  21137. [](const httplib::Request &, httplib::Response &res) {
  21138. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21139. });
  21140. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21141. svr_.wait_until_ready();
  21142. }
  21143. void TearDown() override {
  21144. svr_.stop();
  21145. if (thread_.joinable()) thread_.join();
  21146. }
  21147. httplib::Server svr_;
  21148. std::thread thread_;
  21149. };
  21150. // stream::Get tests
  21151. TEST_F(StreamApiTest, GetBasic) {
  21152. httplib::Client cli(HOST, PORT);
  21153. auto result = httplib::stream::Get(cli, "/hello");
  21154. ASSERT_TRUE(result.is_valid());
  21155. EXPECT_EQ(200, result.status());
  21156. EXPECT_EQ("Hello World!", read_body(result));
  21157. }
  21158. TEST_F(StreamApiTest, GetWithParams) {
  21159. httplib::Client cli(HOST, PORT);
  21160. httplib::Params params{{"foo", "bar"}};
  21161. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21162. ASSERT_TRUE(result.is_valid());
  21163. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21164. }
  21165. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21166. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21167. httplib::Client cli(HOST, PORT);
  21168. cli.set_payload_max_length(0);
  21169. auto result = httplib::stream::Get(cli, "/hello");
  21170. ASSERT_TRUE(result.is_valid());
  21171. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21172. EXPECT_EQ("Hello World!", read_body(result));
  21173. }
  21174. #endif
  21175. TEST_F(StreamApiTest, GetConnectionError) {
  21176. httplib::Client cli(HOST, 9999);
  21177. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21178. }
  21179. TEST_F(StreamApiTest, Get404) {
  21180. httplib::Client cli(HOST, PORT);
  21181. auto result = httplib::stream::Get(cli, "/nonexistent");
  21182. EXPECT_TRUE(result.is_valid());
  21183. EXPECT_EQ(404, result.status());
  21184. }
  21185. // stream::Post tests
  21186. TEST_F(StreamApiTest, PostBasic) {
  21187. httplib::Client cli(HOST, PORT);
  21188. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21189. "application/json");
  21190. ASSERT_TRUE(result.is_valid());
  21191. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21192. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21193. }
  21194. TEST_F(StreamApiTest, PostWithHeaders) {
  21195. httplib::Client cli(HOST, PORT);
  21196. httplib::Headers headers{{"X-Custom", "value"}};
  21197. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21198. "text/plain");
  21199. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21200. }
  21201. TEST_F(StreamApiTest, PostWithParams) {
  21202. httplib::Client cli(HOST, PORT);
  21203. httplib::Params params{{"k", "v"}};
  21204. auto result =
  21205. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21206. auto body = read_body(result);
  21207. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21208. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21209. }
  21210. TEST_F(StreamApiTest, PostLarge) {
  21211. httplib::Client cli(HOST, PORT);
  21212. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21213. size_t total = 0;
  21214. while (result.next()) {
  21215. total += result.size();
  21216. }
  21217. EXPECT_EQ(100u * 1024u, total);
  21218. }
  21219. // stream::Put/Patch tests
  21220. TEST_F(StreamApiTest, PutAndPatch) {
  21221. httplib::Client cli(HOST, PORT);
  21222. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21223. EXPECT_EQ("PUT:test", read_body(put));
  21224. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21225. EXPECT_EQ("PATCH:test", read_body(patch));
  21226. }
  21227. // stream::Delete tests
  21228. TEST_F(StreamApiTest, Delete) {
  21229. httplib::Client cli(HOST, PORT);
  21230. auto del1 = httplib::stream::Delete(cli, "/resource");
  21231. EXPECT_EQ("Deleted", read_body(del1));
  21232. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21233. EXPECT_EQ("Deleted:data", read_body(del2));
  21234. }
  21235. // stream::Head/Options tests
  21236. TEST_F(StreamApiTest, HeadAndOptions) {
  21237. httplib::Client cli(HOST, PORT);
  21238. auto head = httplib::stream::Head(cli, "/head-test");
  21239. EXPECT_TRUE(head.is_valid());
  21240. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21241. auto opts = httplib::stream::Options(cli, "/options");
  21242. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21243. }
  21244. // SSL stream::* tests
  21245. #ifdef CPPHTTPLIB_SSL_ENABLED
  21246. class SSLStreamApiTest : public ::testing::Test {
  21247. protected:
  21248. void SetUp() override {
  21249. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21250. res.set_content("Hello SSL!", "text/plain");
  21251. });
  21252. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21253. res.set_content(req.body, "text/plain");
  21254. });
  21255. port_ = svr_.bind_to_any_port("127.0.0.1");
  21256. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21257. svr_.wait_until_ready();
  21258. }
  21259. void TearDown() override {
  21260. svr_.stop();
  21261. if (thread_.joinable()) thread_.join();
  21262. }
  21263. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21264. std::thread thread_;
  21265. int port_ = 0;
  21266. };
  21267. TEST_F(SSLStreamApiTest, GetAndPost) {
  21268. httplib::SSLClient cli("127.0.0.1", port_);
  21269. cli.enable_server_certificate_verification(false);
  21270. auto get = httplib::stream::Get(cli, "/hello");
  21271. EXPECT_EQ("Hello SSL!", read_body(get));
  21272. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21273. EXPECT_EQ("test", read_body(post));
  21274. }
  21275. #endif
  21276. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21277. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21278. // BodyReader
  21279. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21280. // Test that read timeout during streaming is detected
  21281. // Use a large content-length response where server delays mid-stream
  21282. Server svr;
  21283. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21284. // Send a large response with delay in the middle
  21285. res.set_content_provider(
  21286. 1000, // content_length
  21287. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21288. if (offset < 100) {
  21289. // Send first 100 bytes immediately
  21290. std::string data(100, 'A');
  21291. sink.write(data.c_str(), data.size());
  21292. return true;
  21293. }
  21294. // Then delay longer than client timeout
  21295. std::this_thread::sleep_for(std::chrono::seconds(3));
  21296. std::string data(900, 'B');
  21297. sink.write(data.c_str(), data.size());
  21298. return true;
  21299. });
  21300. });
  21301. auto port = 8091;
  21302. std::thread t([&]() { svr.listen("localhost", port); });
  21303. svr.wait_until_ready();
  21304. Client cli("localhost", port);
  21305. cli.set_read_timeout(1, 0); // 1 second timeout
  21306. auto handle = cli.open_stream("GET", "/slow-stream");
  21307. ASSERT_TRUE(handle.is_valid());
  21308. char buf[256];
  21309. ssize_t total = 0;
  21310. ssize_t n;
  21311. bool got_error = false;
  21312. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21313. total += n;
  21314. }
  21315. if (n < 0) {
  21316. got_error = true;
  21317. // Should be timeout or read error
  21318. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21319. handle.get_read_error() == Error::Read)
  21320. << "Actual error: " << to_string(handle.get_read_error());
  21321. }
  21322. // Either we got an error, or we got less data than expected
  21323. EXPECT_TRUE(got_error || total < 1000)
  21324. << "Expected timeout but got all " << total << " bytes";
  21325. svr.stop();
  21326. t.join();
  21327. }
  21328. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21329. // Test connection closed detection via BodyReader
  21330. Server svr;
  21331. std::atomic<bool> close_now{false};
  21332. svr.Get("/will-close", [&](const Request &, Response &res) {
  21333. res.set_content_provider(
  21334. 10000, // Large content_length that we won't fully send
  21335. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21336. if (offset < 100) {
  21337. std::string data(100, 'X');
  21338. sink.write(data.c_str(), data.size());
  21339. return true;
  21340. }
  21341. // Wait for signal then abort
  21342. while (!close_now) {
  21343. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21344. }
  21345. return false; // Abort - server will close connection
  21346. });
  21347. });
  21348. auto port = 8092;
  21349. std::thread t([&]() { svr.listen("localhost", port); });
  21350. svr.wait_until_ready();
  21351. Client cli("localhost", port);
  21352. auto handle = cli.open_stream("GET", "/will-close");
  21353. ASSERT_TRUE(handle.is_valid());
  21354. char buf[256];
  21355. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21356. EXPECT_GT(n, 0) << "First read should succeed";
  21357. // Signal server to close
  21358. close_now = true;
  21359. // Keep reading until error or EOF
  21360. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21361. // Keep reading
  21362. }
  21363. // Should get an error since content_length wasn't satisfied
  21364. if (n < 0) {
  21365. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21366. handle.get_read_error() == Error::Read)
  21367. << "Actual error: " << to_string(handle.get_read_error());
  21368. }
  21369. svr.stop();
  21370. t.join();
  21371. }
  21372. #ifdef CPPHTTPLIB_SSL_ENABLED
  21373. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21374. // Test that read timeout during SSL streaming is detected
  21375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21376. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21377. res.set_content_provider(
  21378. 1000, "text/plain",
  21379. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21380. if (offset < 100) {
  21381. std::string data(100, 'A');
  21382. sink.write(data.c_str(), data.size());
  21383. return true;
  21384. }
  21385. std::this_thread::sleep_for(std::chrono::seconds(3));
  21386. std::string data(900, 'B');
  21387. sink.write(data.c_str(), data.size());
  21388. return true;
  21389. });
  21390. });
  21391. auto port = 8093;
  21392. std::thread t([&]() { svr.listen("localhost", port); });
  21393. svr.wait_until_ready();
  21394. SSLClient cli("localhost", port);
  21395. cli.enable_server_certificate_verification(false);
  21396. cli.set_read_timeout(1, 0); // 1 second timeout
  21397. auto handle = cli.open_stream("GET", "/slow-stream");
  21398. ASSERT_TRUE(handle.is_valid());
  21399. char buf[256];
  21400. ssize_t total = 0;
  21401. ssize_t n;
  21402. bool got_error = false;
  21403. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21404. total += n;
  21405. }
  21406. if (n < 0) {
  21407. got_error = true;
  21408. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21409. handle.get_read_error() == Error::Read)
  21410. << "Actual error: " << to_string(handle.get_read_error());
  21411. }
  21412. EXPECT_TRUE(got_error || total < 1000)
  21413. << "Expected timeout but got all " << total << " bytes";
  21414. svr.stop();
  21415. t.join();
  21416. }
  21417. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21418. // Test SSL connection closed detection
  21419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21420. std::atomic<bool> close_now{false};
  21421. svr.Get("/will-close", [&](const Request &, Response &res) {
  21422. res.set_content_provider(
  21423. 10000, "text/plain",
  21424. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21425. if (offset < 100) {
  21426. std::string data(100, 'X');
  21427. sink.write(data.c_str(), data.size());
  21428. return true;
  21429. }
  21430. while (!close_now) {
  21431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21432. }
  21433. return false;
  21434. });
  21435. });
  21436. auto port = 8094;
  21437. std::thread t([&]() { svr.listen("localhost", port); });
  21438. svr.wait_until_ready();
  21439. SSLClient cli("localhost", port);
  21440. cli.enable_server_certificate_verification(false);
  21441. auto handle = cli.open_stream("GET", "/will-close");
  21442. ASSERT_TRUE(handle.is_valid());
  21443. char buf[256];
  21444. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21445. EXPECT_GT(n, 0);
  21446. // Signal server to close
  21447. close_now = true;
  21448. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21449. // Keep reading
  21450. }
  21451. if (n < 0) {
  21452. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21453. handle.get_read_error() == Error::Read)
  21454. << "Actual error: " << to_string(handle.get_read_error());
  21455. }
  21456. svr.stop();
  21457. t.join();
  21458. }
  21459. #endif
  21460. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21461. using namespace httplib;
  21462. // Create a test file
  21463. const char *fname = "etag_testfile.txt";
  21464. const char *content = "etag-content";
  21465. {
  21466. std::ofstream ofs(fname);
  21467. ofs << content;
  21468. ASSERT_TRUE(ofs.good());
  21469. }
  21470. Server svr;
  21471. svr.set_mount_point("/static", ".");
  21472. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21473. svr.wait_until_ready();
  21474. Client cli(HOST, PORT);
  21475. // First request: should get 200 with ETag header
  21476. auto res1 = cli.Get("/static/etag_testfile.txt");
  21477. ASSERT_TRUE(res1);
  21478. ASSERT_EQ(200, res1->status);
  21479. ASSERT_TRUE(res1->has_header("ETag"));
  21480. std::string etag = res1->get_header_value("ETag");
  21481. EXPECT_FALSE(etag.empty());
  21482. // Verify ETag format: W/"hex-hex"
  21483. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21484. EXPECT_EQ('W', etag[0]);
  21485. EXPECT_EQ('/', etag[1]);
  21486. EXPECT_EQ('"', etag[2]);
  21487. EXPECT_EQ('"', etag.back());
  21488. // Exact match: expect 304 Not Modified
  21489. Headers h2 = {{"If-None-Match", etag}};
  21490. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21491. ASSERT_TRUE(res2);
  21492. EXPECT_EQ(304, res2->status);
  21493. // Wildcard match: expect 304 Not Modified
  21494. Headers h3 = {{"If-None-Match", "*"}};
  21495. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21496. ASSERT_TRUE(res3);
  21497. EXPECT_EQ(304, res3->status);
  21498. // Non-matching ETag: expect 200
  21499. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21500. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21501. ASSERT_TRUE(res4);
  21502. EXPECT_EQ(200, res4->status);
  21503. // Multiple ETags with one matching: expect 304
  21504. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21505. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21506. ASSERT_TRUE(res5);
  21507. EXPECT_EQ(304, res5->status);
  21508. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21509. // that equivalent to the single comma-separated list above, so the match on
  21510. // the second line must still be found.
  21511. Headers h6;
  21512. h6.emplace("If-None-Match", "W/\"other\"");
  21513. h6.emplace("If-None-Match", etag);
  21514. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21515. ASSERT_TRUE(res6);
  21516. EXPECT_EQ(304, res6->status);
  21517. svr.stop();
  21518. t.join();
  21519. std::remove(fname);
  21520. }
  21521. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21522. using namespace httplib;
  21523. Server svr;
  21524. svr.set_mount_point("/static", ".");
  21525. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21526. svr.wait_until_ready();
  21527. Client cli(HOST, PORT);
  21528. // Send If-None-Match: * to a non-existent file
  21529. Headers h = {{"If-None-Match", "*"}};
  21530. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21532. EXPECT_EQ(404, res->status);
  21533. svr.stop();
  21534. t.join();
  21535. }
  21536. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21537. using namespace httplib;
  21538. // Create a test file
  21539. const char *fname = "etag_boundary_testfile.txt";
  21540. const char *content = "boundary-test";
  21541. {
  21542. std::ofstream ofs(fname);
  21543. ofs << content;
  21544. ASSERT_TRUE(ofs.good());
  21545. }
  21546. Server svr;
  21547. svr.set_mount_point("/static", ".");
  21548. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21549. svr.wait_until_ready();
  21550. Client cli(HOST, PORT);
  21551. // Get the actual ETag
  21552. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21553. ASSERT_TRUE(res1);
  21554. ASSERT_EQ(200, res1->status);
  21555. ASSERT_TRUE(res1->has_header("ETag"));
  21556. std::string etag = res1->get_header_value("ETag");
  21557. // Test 1: Very long ETag value (longer than actual ETag)
  21558. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21559. Headers h1 = {{"If-None-Match", "W/"
  21560. "\"very-long-etag-value-that-is-much-longer-"
  21561. "than-the-actual-etag-value\""}};
  21562. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21563. ASSERT_TRUE(res2);
  21564. EXPECT_EQ(200, res2->status); // Should not match
  21565. // Test 2: Long string followed by wildcard
  21566. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21567. // string)
  21568. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21569. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21570. ASSERT_TRUE(res3);
  21571. EXPECT_EQ(304, res3->status); // Should match on "*"
  21572. // Test 3: Wildcard followed by long string
  21573. // Should match on "*" immediately and return 304
  21574. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21575. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21576. ASSERT_TRUE(res4);
  21577. EXPECT_EQ(304, res4->status); // Should match on "*"
  21578. // Test 4: Multiple long non-matching values
  21579. // Should NOT match and return 200 (test that all comparisons are safe)
  21580. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21581. "W/\"second-long-non-matching-value\", "
  21582. "W/\"third-long-non-matching-value\""}};
  21583. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21584. ASSERT_TRUE(res5);
  21585. EXPECT_EQ(200, res5->status); // Should not match
  21586. // Test 5: Single character that is not "*" (edge case)
  21587. Headers h5 = {{"If-None-Match", "X"}};
  21588. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21589. ASSERT_TRUE(res6);
  21590. EXPECT_EQ(200, res6->status); // Should not match
  21591. svr.stop();
  21592. t.join();
  21593. std::remove(fname);
  21594. }
  21595. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21596. using namespace httplib;
  21597. // Create a test file
  21598. const char *fname = "ims_testfile.txt";
  21599. const char *content = "if-modified-since-test";
  21600. {
  21601. std::ofstream ofs(fname);
  21602. ofs << content;
  21603. ASSERT_TRUE(ofs.good());
  21604. }
  21605. Server svr;
  21606. svr.set_mount_point("/static", ".");
  21607. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21608. svr.wait_until_ready();
  21609. Client cli(HOST, PORT);
  21610. // First request: should get 200 with Last-Modified header
  21611. auto res1 = cli.Get("/static/ims_testfile.txt");
  21612. ASSERT_TRUE(res1);
  21613. ASSERT_EQ(200, res1->status);
  21614. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21615. std::string last_modified = res1->get_header_value("Last-Modified");
  21616. EXPECT_FALSE(last_modified.empty());
  21617. // If-Modified-Since with same time: expect 304
  21618. Headers h2 = {{"If-Modified-Since", last_modified}};
  21619. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21620. ASSERT_TRUE(res2);
  21621. EXPECT_EQ(304, res2->status);
  21622. // If-Modified-Since with future time: expect 304
  21623. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21624. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21625. ASSERT_TRUE(res3);
  21626. EXPECT_EQ(304, res3->status);
  21627. // If-Modified-Since with past time: expect 200
  21628. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21629. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21630. ASSERT_TRUE(res4);
  21631. EXPECT_EQ(200, res4->status);
  21632. // If-None-Match takes precedence over If-Modified-Since
  21633. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21634. ASSERT_TRUE(res1->has_header("ETag"));
  21635. std::string etag = res1->get_header_value("ETag");
  21636. Headers h5 = {{"If-None-Match", etag},
  21637. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21638. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21639. ASSERT_TRUE(res5);
  21640. EXPECT_EQ(304, res5->status);
  21641. svr.stop();
  21642. t.join();
  21643. std::remove(fname);
  21644. }
  21645. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21646. using namespace httplib;
  21647. Server svr;
  21648. // Endpoint that returns compressible content
  21649. svr.Get("/compressible", [](const Request &, Response &res) {
  21650. // Return a large enough body to trigger compression
  21651. std::string body(1000, 'a');
  21652. res.set_content(body, "text/plain");
  21653. });
  21654. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21655. svr.wait_until_ready();
  21656. Client cli(HOST, PORT);
  21657. // Request with gzip support: should get Vary header when compressed
  21658. cli.set_compress(true);
  21659. auto res1 = cli.Get("/compressible");
  21660. ASSERT_TRUE(res1);
  21661. EXPECT_EQ(200, res1->status);
  21662. // If Content-Encoding is set, Vary should also be set
  21663. if (res1->has_header("Content-Encoding")) {
  21664. EXPECT_TRUE(res1->has_header("Vary"));
  21665. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21666. }
  21667. // Request without Accept-Encoding header: should not have compression
  21668. Headers h_no_compress;
  21669. auto res2 = cli.Get("/compressible", h_no_compress);
  21670. ASSERT_TRUE(res2);
  21671. EXPECT_EQ(200, res2->status);
  21672. // Verify Vary header is present when compression is applied
  21673. // (the exact behavior depends on server configuration)
  21674. svr.stop();
  21675. t.join();
  21676. }
  21677. TEST(ETagTest, IfRangeWithETag) {
  21678. using namespace httplib;
  21679. // Create a test file with known content
  21680. const char *fname = "if_range_testfile.txt";
  21681. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21682. {
  21683. std::ofstream ofs(fname);
  21684. ofs << content;
  21685. ASSERT_TRUE(ofs.good());
  21686. }
  21687. Server svr;
  21688. svr.set_mount_point("/static", ".");
  21689. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21690. svr.wait_until_ready();
  21691. Client cli(HOST, PORT);
  21692. // First request: get ETag
  21693. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21694. ASSERT_TRUE(res1);
  21695. ASSERT_EQ(200, res1->status);
  21696. ASSERT_TRUE(res1->has_header("ETag"));
  21697. std::string etag = res1->get_header_value("ETag");
  21698. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21699. // Since our server generates weak ETags (W/"..."), If-Range with our
  21700. // ETag should NOT result in partial content - it should return full content.
  21701. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21702. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21703. ASSERT_TRUE(res2);
  21704. // Weak ETag in If-Range -> full content (200), not partial (206)
  21705. EXPECT_EQ(200, res2->status);
  21706. EXPECT_EQ(content, res2->body);
  21707. EXPECT_FALSE(res2->has_header("Content-Range"));
  21708. // Range request with non-matching If-Range (ETag): should get 200 (full
  21709. // content)
  21710. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21711. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21712. ASSERT_TRUE(res3);
  21713. EXPECT_EQ(200, res3->status);
  21714. EXPECT_EQ(content, res3->body);
  21715. EXPECT_FALSE(res3->has_header("Content-Range"));
  21716. // Range request with strong ETag (hypothetical - our server doesn't generate
  21717. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21718. // should return full content)
  21719. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21720. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21721. ASSERT_TRUE(res4);
  21722. EXPECT_EQ(200, res4->status);
  21723. EXPECT_EQ(content, res4->body);
  21724. EXPECT_FALSE(res4->has_header("Content-Range"));
  21725. svr.stop();
  21726. t.join();
  21727. std::remove(fname);
  21728. }
  21729. TEST(ETagTest, IfRangeWithDate) {
  21730. using namespace httplib;
  21731. // Create a test file
  21732. const char *fname = "if_range_date_testfile.txt";
  21733. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21734. {
  21735. std::ofstream ofs(fname);
  21736. ofs << content;
  21737. ASSERT_TRUE(ofs.good());
  21738. }
  21739. Server svr;
  21740. svr.set_mount_point("/static", ".");
  21741. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21742. svr.wait_until_ready();
  21743. Client cli(HOST, PORT);
  21744. // First request: get Last-Modified
  21745. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21746. ASSERT_TRUE(res1);
  21747. ASSERT_EQ(200, res1->status);
  21748. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21749. std::string last_modified = res1->get_header_value("Last-Modified");
  21750. // Range request with matching If-Range (date): should get 206
  21751. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21752. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21753. ASSERT_TRUE(res2);
  21754. EXPECT_EQ(206, res2->status);
  21755. EXPECT_EQ("FGHIJ", res2->body);
  21756. // Range request with old If-Range date: should get 200 (full content)
  21757. Headers h3 = {{"Range", "bytes=5-9"},
  21758. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21759. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21760. ASSERT_TRUE(res3);
  21761. EXPECT_EQ(200, res3->status);
  21762. EXPECT_EQ(content, res3->body);
  21763. // Range request with future If-Range date: should get 206
  21764. Headers h4 = {{"Range", "bytes=0-4"},
  21765. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21766. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21767. ASSERT_TRUE(res4);
  21768. EXPECT_EQ(206, res4->status);
  21769. EXPECT_EQ("ABCDE", res4->body);
  21770. svr.stop();
  21771. t.join();
  21772. std::remove(fname);
  21773. }
  21774. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21775. using namespace httplib;
  21776. const char *fname = "etag_malformed.txt";
  21777. const char *content = "malformed-etag";
  21778. {
  21779. std::ofstream ofs(fname);
  21780. ofs << content;
  21781. ASSERT_TRUE(ofs.good());
  21782. }
  21783. Server svr;
  21784. svr.set_mount_point("/static", ".");
  21785. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21786. svr.wait_until_ready();
  21787. Client cli(HOST, PORT);
  21788. // baseline: should get 200 and an ETag
  21789. auto res1 = cli.Get("/static/etag_malformed.txt");
  21790. ASSERT_TRUE(res1);
  21791. ASSERT_EQ(200, res1->status);
  21792. ASSERT_TRUE(res1->has_header("ETag"));
  21793. // Malformed ETag value (missing quotes) should be treated as non-matching
  21794. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21795. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21796. ASSERT_TRUE(res_bad);
  21797. EXPECT_EQ(200, res_bad->status);
  21798. // Whitespace-only header value should be considered invalid / non-matching
  21799. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21800. "Host: localhost\r\n"
  21801. "If-None-Match: \r\n"
  21802. "Connection: close\r\n"
  21803. "\r\n";
  21804. std::string out;
  21805. ASSERT_TRUE(send_request(5, raw_req, &out));
  21806. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21807. svr.stop();
  21808. t.join();
  21809. std::remove(fname);
  21810. }
  21811. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21812. using namespace httplib;
  21813. const char *fname = "ims_invalid_format.txt";
  21814. const char *content = "ims-bad-format";
  21815. {
  21816. std::ofstream ofs(fname);
  21817. ofs << content;
  21818. ASSERT_TRUE(ofs.good());
  21819. }
  21820. Server svr;
  21821. svr.set_mount_point("/static", ".");
  21822. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21823. svr.wait_until_ready();
  21824. Client cli(HOST, PORT);
  21825. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21826. ASSERT_TRUE(res1);
  21827. ASSERT_EQ(200, res1->status);
  21828. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21829. // If-Modified-Since with invalid format should not result in 304
  21830. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21831. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21832. ASSERT_TRUE(res_bad);
  21833. EXPECT_EQ(200, res_bad->status);
  21834. // If-Range with invalid date format should be treated as mismatch -> full
  21835. // content (200)
  21836. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21837. {"If-Range", "invalid-date"}};
  21838. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21839. ASSERT_TRUE(res_ifrange);
  21840. EXPECT_EQ(200, res_ifrange->status);
  21841. svr.stop();
  21842. t.join();
  21843. std::remove(fname);
  21844. }
  21845. TEST(ETagTest, IfRangeWithMalformedETag) {
  21846. using namespace httplib;
  21847. const char *fname = "ifrange_malformed.txt";
  21848. const std::string content = "0123456789";
  21849. {
  21850. std::ofstream ofs(fname);
  21851. ofs << content;
  21852. ASSERT_TRUE(ofs.good());
  21853. }
  21854. Server svr;
  21855. svr.set_mount_point("/static", ".");
  21856. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21857. svr.wait_until_ready();
  21858. Client cli(HOST, PORT);
  21859. // First request: get ETag
  21860. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21861. ASSERT_TRUE(res1);
  21862. ASSERT_EQ(200, res1->status);
  21863. ASSERT_TRUE(res1->has_header("ETag"));
  21864. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21865. // full content (200)
  21866. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21867. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21868. ASSERT_TRUE(res2);
  21869. EXPECT_EQ(200, res2->status);
  21870. EXPECT_EQ(content, res2->body);
  21871. svr.stop();
  21872. t.join();
  21873. std::remove(fname);
  21874. }
  21875. TEST(ETagTest, ExtremeLargeDateValues) {
  21876. using namespace httplib;
  21877. const char *fname = "ims_extreme_date.txt";
  21878. const char *content = "ims-extreme-date";
  21879. {
  21880. std::ofstream ofs(fname);
  21881. ofs << content;
  21882. ASSERT_TRUE(ofs.good());
  21883. }
  21884. Server svr;
  21885. svr.set_mount_point("/static", ".");
  21886. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21887. svr.wait_until_ready();
  21888. Client cli(HOST, PORT);
  21889. auto res1 = cli.Get(std::string("/static/") + fname);
  21890. ASSERT_TRUE(res1);
  21891. ASSERT_EQ(200, res1->status);
  21892. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21893. // Extremely large year that may overflow date parsing routines.
  21894. Headers h_large_date = {
  21895. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21896. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21897. ASSERT_TRUE(res_bad);
  21898. // Expect server to treat this as invalid/mismatch and return full content
  21899. EXPECT_EQ(200, res_bad->status);
  21900. // If-Range with extremely large date should be treated as mismatch -> full
  21901. // content (200)
  21902. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21903. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21904. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21905. ASSERT_TRUE(res_ifrange);
  21906. EXPECT_EQ(200, res_ifrange->status);
  21907. svr.stop();
  21908. t.join();
  21909. std::remove(fname);
  21910. }
  21911. TEST(ETagTest, NegativeFileModificationTime) {
  21912. using namespace httplib;
  21913. const char *fname = "ims_negative_mtime.txt";
  21914. const std::string content = "negative-mtime";
  21915. {
  21916. std::ofstream ofs(fname);
  21917. ofs << content;
  21918. ASSERT_TRUE(ofs.good());
  21919. }
  21920. // Try to set file mtime to a negative value. This may fail on some
  21921. // platforms/filesystems; if it fails, the test will still verify server
  21922. // behaves safely by performing a regular conditional request.
  21923. #if defined(__APPLE__) || defined(__linux__)
  21924. bool set_negative = false;
  21925. do {
  21926. struct timeval times[2];
  21927. // access time: now
  21928. times[0].tv_sec = time(nullptr);
  21929. times[0].tv_usec = 0;
  21930. // modification time: negative (e.g., -1)
  21931. times[1].tv_sec = -1;
  21932. times[1].tv_usec = 0;
  21933. if (utimes(fname, times) == 0) { set_negative = true; }
  21934. } while (0);
  21935. #else
  21936. bool set_negative = false;
  21937. #endif
  21938. Server svr;
  21939. svr.set_mount_point("/static", ".");
  21940. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21941. svr.wait_until_ready();
  21942. Client cli(HOST, PORT);
  21943. auto res1 = cli.Get(std::string("/static/") + fname);
  21944. ASSERT_TRUE(res1);
  21945. ASSERT_EQ(200, res1->status);
  21946. bool has_last_modified = res1->has_header("Last-Modified");
  21947. std::string last_modified;
  21948. if (has_last_modified) {
  21949. last_modified = res1->get_header_value("Last-Modified");
  21950. }
  21951. if (set_negative) {
  21952. // If we successfully set a negative mtime, ensure server returns a
  21953. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21954. // with an old date and ensure server handles it without crash.
  21955. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21956. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21957. ASSERT_TRUE(res2);
  21958. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21959. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21960. } else {
  21961. // Could not set negative mtime on this platform; fall back to verifying
  21962. // that normal invalid/malformed dates are treated safely (non-304).
  21963. Headers h_bad_date = {
  21964. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21965. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21966. ASSERT_TRUE(res_bad);
  21967. EXPECT_EQ(200, res_bad->status);
  21968. }
  21969. svr.stop();
  21970. t.join();
  21971. std::remove(fname);
  21972. }
  21973. //==============================================================================
  21974. // Integration Tests with Server
  21975. //==============================================================================
  21976. class SSEIntegrationTest : public ::testing::Test {
  21977. protected:
  21978. void SetUp() override {
  21979. stop_server_.store(false);
  21980. events_.clear();
  21981. server_ = httplib::detail::make_unique<Server>();
  21982. setup_server();
  21983. start_server();
  21984. }
  21985. void TearDown() override {
  21986. stop_server_.store(true);
  21987. event_cv_.notify_all();
  21988. server_->stop();
  21989. if (server_thread_.joinable()) { server_thread_.join(); }
  21990. }
  21991. void setup_server() {
  21992. // Simple SSE endpoint
  21993. server_->Get("/events", [this](const Request &req, Response &res) {
  21994. auto last_id = req.get_header_value("Last-Event-ID");
  21995. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21996. res.set_chunked_content_provider(
  21997. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21998. std::unique_lock<std::mutex> lock(event_mutex_);
  21999. if (event_cv_.wait_for(
  22000. lock, std::chrono::milliseconds(200), [this] {
  22001. return !events_.empty() || stop_server_.load();
  22002. })) {
  22003. if (stop_server_.load()) { return false; }
  22004. if (!events_.empty()) {
  22005. std::string event = events_.front();
  22006. events_.erase(events_.begin());
  22007. sink.write(event.data(), event.size());
  22008. return true;
  22009. }
  22010. }
  22011. return !stop_server_.load();
  22012. });
  22013. });
  22014. // Endpoint that returns error
  22015. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22016. res.status = 500;
  22017. res.set_content("Internal Server Error", "text/plain");
  22018. });
  22019. // Endpoint for custom event types
  22020. server_->Get("/custom-events", [](const Request &, Response &res) {
  22021. res.set_chunked_content_provider(
  22022. "text/event-stream", [](size_t offset, DataSink &sink) {
  22023. if (offset == 0) {
  22024. std::string event = "event: update\ndata: updated\n\n"
  22025. "event: delete\ndata: deleted\n\n";
  22026. sink.write(event.data(), event.size());
  22027. }
  22028. return false; // End stream after sending
  22029. });
  22030. });
  22031. }
  22032. void start_server() {
  22033. port_ = server_->bind_to_any_port(HOST);
  22034. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22035. // Wait for server to start
  22036. while (!server_->is_running()) {
  22037. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22038. }
  22039. }
  22040. int get_port() const { return port_; }
  22041. void send_event(const std::string &event) {
  22042. std::lock_guard<std::mutex> lock(event_mutex_);
  22043. events_.push_back(event);
  22044. event_cv_.notify_all();
  22045. }
  22046. std::unique_ptr<Server> server_;
  22047. std::thread server_thread_;
  22048. std::mutex event_mutex_;
  22049. std::condition_variable event_cv_;
  22050. std::vector<std::string> events_;
  22051. std::atomic<bool> stop_server_{false};
  22052. std::string last_received_event_id_;
  22053. int port_ = 0;
  22054. };
  22055. //==============================================================================
  22056. // SSE Parsing Tests
  22057. //==============================================================================
  22058. class SSEParsingTest : public SSEIntegrationTest {
  22059. protected:
  22060. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  22061. // A trailing sentinel event tells when the whole stream has been parsed.
  22062. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  22063. auto body = stream + "event: end\ndata: end\n\n";
  22064. server_->Get("/parse", [body](const Request &, Response &res) {
  22065. res.set_content(body, "text/event-stream");
  22066. });
  22067. return collect("/parse");
  22068. }
  22069. // Runs SSEClient against path until an "end" event arrives and returns the
  22070. // messages dispatched before it
  22071. std::vector<sse::SSEMessage> collect(const std::string &path) {
  22072. Client client(HOST, get_port());
  22073. sse::SSEClient sse(client, path);
  22074. std::mutex mutex;
  22075. std::condition_variable cv;
  22076. std::vector<sse::SSEMessage> messages;
  22077. auto done = false;
  22078. sse.on_message([&](const sse::SSEMessage &msg) {
  22079. std::lock_guard<std::mutex> lock(mutex);
  22080. // Ignore a replay from a reconnect that races with stop()
  22081. if (!done) { messages.push_back(msg); }
  22082. });
  22083. sse.on_event("end", [&](const sse::SSEMessage &) {
  22084. std::lock_guard<std::mutex> lock(mutex);
  22085. done = true;
  22086. cv.notify_all();
  22087. });
  22088. sse.set_reconnect_interval(100);
  22089. sse.start_async();
  22090. {
  22091. std::unique_lock<std::mutex> lock(mutex);
  22092. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  22093. }
  22094. sse.stop();
  22095. EXPECT_TRUE(done);
  22096. return messages;
  22097. }
  22098. };
  22099. TEST_F(SSEParsingTest, SingleLineData) {
  22100. auto msgs = parse("data: hello\n\n");
  22101. ASSERT_EQ(msgs.size(), 1u);
  22102. EXPECT_EQ(msgs[0].data, "hello");
  22103. EXPECT_EQ(msgs[0].event, "message");
  22104. }
  22105. TEST_F(SSEParsingTest, MultiLineData) {
  22106. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  22107. ASSERT_EQ(msgs.size(), 1u);
  22108. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  22109. }
  22110. TEST_F(SSEParsingTest, CustomEventType) {
  22111. auto msgs = parse("event: update\ndata: payload\n\n");
  22112. ASSERT_EQ(msgs.size(), 1u);
  22113. EXPECT_EQ(msgs[0].event, "update");
  22114. EXPECT_EQ(msgs[0].data, "payload");
  22115. }
  22116. TEST_F(SSEParsingTest, EventIdHandling) {
  22117. auto msgs = parse("id: 12345\ndata: test\n\n");
  22118. ASSERT_EQ(msgs.size(), 1u);
  22119. EXPECT_EQ(msgs[0].id, "12345");
  22120. }
  22121. TEST_F(SSEParsingTest, EmptyEventId) {
  22122. auto msgs = parse("id:\ndata: test\n\n");
  22123. ASSERT_EQ(msgs.size(), 1u);
  22124. EXPECT_EQ(msgs[0].id, "");
  22125. }
  22126. TEST_F(SSEParsingTest, CommentsIgnored) {
  22127. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22128. ASSERT_EQ(msgs.size(), 1u);
  22129. EXPECT_EQ(msgs[0].data, "hello");
  22130. EXPECT_EQ(msgs[0].event, "message");
  22131. }
  22132. TEST_F(SSEParsingTest, ColonInValue) {
  22133. auto msgs = parse("data: hello:world:test\n\n");
  22134. ASSERT_EQ(msgs.size(), 1u);
  22135. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22136. }
  22137. TEST_F(SSEParsingTest, FieldNameOnly) {
  22138. // A line without a colon is a field name with an empty value
  22139. auto msgs = parse("data\n\n");
  22140. ASSERT_EQ(msgs.size(), 1u);
  22141. EXPECT_EQ(msgs[0].data, "");
  22142. }
  22143. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22144. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22145. ASSERT_EQ(msgs.size(), 1u);
  22146. EXPECT_EQ(msgs[0].event, "update");
  22147. EXPECT_EQ(msgs[0].data, "hello");
  22148. }
  22149. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22150. auto msgs = parse("data\r\n\r\n");
  22151. ASSERT_EQ(msgs.size(), 1u);
  22152. EXPECT_EQ(msgs[0].data, "");
  22153. }
  22154. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22155. auto msgs = parse("event: update\rdata: hello\r\r");
  22156. ASSERT_EQ(msgs.size(), 1u);
  22157. EXPECT_EQ(msgs[0].event, "update");
  22158. EXPECT_EQ(msgs[0].data, "hello");
  22159. }
  22160. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22161. // Chunk boundaries fall inside every \r\n and right before the first one
  22162. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22163. "\n\r", "\nevent: end\ndata: end\n\n"};
  22164. server_->Get("/split", [chunks](const Request &, Response &res) {
  22165. auto i = std::make_shared<size_t>(0);
  22166. res.set_chunked_content_provider(
  22167. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22168. if (*i == chunks.size()) {
  22169. sink.done();
  22170. } else {
  22171. sink.write(chunks[*i].data(), chunks[*i].size());
  22172. (*i)++;
  22173. }
  22174. return true;
  22175. });
  22176. });
  22177. auto msgs = collect("/split");
  22178. ASSERT_EQ(msgs.size(), 1u);
  22179. EXPECT_EQ(msgs[0].event, "update");
  22180. EXPECT_EQ(msgs[0].data, "hello");
  22181. }
  22182. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22183. // Only a BOM at the start of the stream is ignored
  22184. auto msgs = parse("\xEF\xBB\xBF"
  22185. "data: first\n\n"
  22186. "\xEF\xBB\xBF"
  22187. "data: second\n\n");
  22188. ASSERT_EQ(msgs.size(), 1u);
  22189. EXPECT_EQ(msgs[0].data, "first");
  22190. }
  22191. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22192. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22193. ASSERT_EQ(msgs.size(), 1u);
  22194. EXPECT_EQ(msgs[0].data, "hello");
  22195. EXPECT_EQ(msgs[0].event, "message");
  22196. }
  22197. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22198. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22199. ASSERT_EQ(msgs.size(), 2u);
  22200. EXPECT_EQ(msgs[0].data, "hello");
  22201. EXPECT_EQ(msgs[1].data, "hello");
  22202. }
  22203. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22204. // An event without data is not dispatched, and its type must not leak
  22205. // into the next event
  22206. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22207. ASSERT_EQ(msgs.size(), 1u);
  22208. EXPECT_EQ(msgs[0].event, "message");
  22209. EXPECT_EQ(msgs[0].data, "hello");
  22210. }
  22211. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22212. // Also when the empty field replaces an earlier type
  22213. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22214. ASSERT_EQ(msgs.size(), 2u);
  22215. EXPECT_EQ(msgs[0].event, "message");
  22216. EXPECT_EQ(msgs[1].event, "message");
  22217. }
  22218. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22219. // The first connection sends only an id; the second echoes back the
  22220. // Last-Event-ID it was reconnected with
  22221. std::atomic<int> connection_count{0};
  22222. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22223. if (connection_count++ == 0) {
  22224. res.set_content("id: 42\n\n", "text/event-stream");
  22225. } else {
  22226. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22227. "\n\nevent: end\ndata: end\n\n",
  22228. "text/event-stream");
  22229. }
  22230. });
  22231. auto msgs = collect("/id-only");
  22232. ASSERT_EQ(msgs.size(), 1u);
  22233. EXPECT_EQ(msgs[0].data, "42");
  22234. }
  22235. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22236. // The first connection sets an id and then clears it with an empty one; the
  22237. // second reports whether it was reconnected with a Last-Event-ID
  22238. std::atomic<int> connection_count{0};
  22239. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22240. if (connection_count++ == 0) {
  22241. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22242. "text/event-stream");
  22243. } else {
  22244. res.set_content(
  22245. std::string("data: ") +
  22246. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22247. "\n\nevent: end\ndata: end\n\n",
  22248. "text/event-stream");
  22249. }
  22250. });
  22251. auto msgs = collect("/id-clear");
  22252. ASSERT_EQ(msgs.size(), 3u);
  22253. EXPECT_EQ(msgs[0].id, "1");
  22254. EXPECT_EQ(msgs[1].id, "");
  22255. EXPECT_EQ(msgs[2].data, "not sent");
  22256. }
  22257. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22258. // The first connection sets an id and then sends ids that cannot be carried
  22259. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22260. // with
  22261. std::atomic<int> connection_count{0};
  22262. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22263. if (connection_count++ == 0) {
  22264. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22265. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22266. "text/event-stream");
  22267. } else {
  22268. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22269. "\n\nevent: end\ndata: end\n\n",
  22270. "text/event-stream");
  22271. }
  22272. });
  22273. auto msgs = collect("/id-unsendable");
  22274. ASSERT_EQ(msgs.size(), 1u);
  22275. EXPECT_EQ(msgs[0].data, "42");
  22276. }
  22277. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22278. auto msgs = parse("event: notification\nid: evt-42\n"
  22279. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22280. ASSERT_EQ(msgs.size(), 1u);
  22281. EXPECT_EQ(msgs[0].event, "notification");
  22282. EXPECT_EQ(msgs[0].id, "evt-42");
  22283. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22284. }
  22285. TEST(SSEMessageTest, Clear) {
  22286. sse::SSEMessage msg;
  22287. msg.event = "custom";
  22288. msg.data = "some data";
  22289. msg.id = "123";
  22290. msg.clear();
  22291. EXPECT_EQ(msg.event, "message");
  22292. EXPECT_EQ(msg.data, "");
  22293. EXPECT_EQ(msg.id, "");
  22294. }
  22295. //==============================================================================
  22296. // SSE Integration Tests
  22297. //==============================================================================
  22298. // Test: Successful connection and on_open callback
  22299. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22300. // Add a simple endpoint that sends one event and closes
  22301. server_->Get("/simple-event", [](const Request &, Response &res) {
  22302. res.set_chunked_content_provider(
  22303. "text/event-stream", [](size_t offset, DataSink &sink) {
  22304. if (offset == 0) {
  22305. std::string event = "data: hello\n\n";
  22306. sink.write(event.data(), event.size());
  22307. }
  22308. return false; // Close stream after sending
  22309. });
  22310. });
  22311. Client client("localhost", get_port());
  22312. sse::SSEClient sse(client, "/simple-event");
  22313. std::atomic<bool> open_called{false};
  22314. std::atomic<bool> message_received{false};
  22315. sse.on_open([&open_called]() { open_called.store(true); });
  22316. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22317. if (msg.data == "hello") { message_received.store(true); }
  22318. });
  22319. sse.set_reconnect_interval(100);
  22320. sse.set_max_reconnect_attempts(1);
  22321. // Start async
  22322. sse.start_async();
  22323. // Wait for message to be processed
  22324. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22325. sse.stop();
  22326. EXPECT_TRUE(open_called.load());
  22327. EXPECT_TRUE(message_received.load());
  22328. }
  22329. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22330. // A data line that never ends.
  22331. server_->Get("/endless-line", [](const Request &, Response &res) {
  22332. res.set_chunked_content_provider(
  22333. "text/event-stream", [](size_t offset, DataSink &sink) {
  22334. if (offset == 0) { sink.write("data: ", 6); }
  22335. std::string chunk(64 * 1024, 'A');
  22336. return sink.write(chunk.data(), chunk.size());
  22337. });
  22338. });
  22339. Client client("localhost", get_port());
  22340. sse::SSEClient sse(client, "/endless-line");
  22341. std::atomic<bool> too_long{false};
  22342. sse.on_error([&](Error err) {
  22343. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22344. });
  22345. sse.set_max_reconnect_attempts(1);
  22346. sse.start_async();
  22347. for (int i = 0; i < 500 && !too_long; i++) {
  22348. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22349. }
  22350. sse.stop();
  22351. EXPECT_TRUE(too_long);
  22352. }
  22353. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22354. // Far more in all than the client's payload limit below.
  22355. server_->Get("/many-events", [](const Request &, Response &res) {
  22356. res.set_chunked_content_provider(
  22357. "text/event-stream", [](size_t offset, DataSink &sink) {
  22358. if (offset == 0) {
  22359. std::string events;
  22360. for (int i = 0; i < 1000; i++) {
  22361. events += "data: message\n\n";
  22362. }
  22363. sink.write(events.data(), events.size());
  22364. }
  22365. return false;
  22366. });
  22367. });
  22368. Client client("localhost", get_port());
  22369. client.set_payload_max_length(1024);
  22370. sse::SSEClient sse(client, "/many-events");
  22371. std::atomic<int> messages{0};
  22372. std::atomic<bool> too_large{false};
  22373. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22374. sse.on_error([&](Error err) {
  22375. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22376. });
  22377. sse.set_max_reconnect_attempts(1);
  22378. sse.start_async();
  22379. for (int i = 0; i < 500 && messages < 1000; i++) {
  22380. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22381. }
  22382. sse.stop();
  22383. EXPECT_GE(messages.load(), 1000);
  22384. EXPECT_FALSE(too_large);
  22385. }
  22386. // Test: on_message callback
  22387. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22388. // Endpoint that sends multiple events then closes
  22389. server_->Get("/multi-event", [](const Request &, Response &res) {
  22390. res.set_chunked_content_provider(
  22391. "text/event-stream", [](size_t offset, DataSink &sink) {
  22392. if (offset == 0) {
  22393. std::string events = "data: message1\n\ndata: message2\n\n";
  22394. sink.write(events.data(), events.size());
  22395. }
  22396. return false;
  22397. });
  22398. });
  22399. Client client("localhost", get_port());
  22400. sse::SSEClient sse(client, "/multi-event");
  22401. std::vector<std::string> received_messages;
  22402. std::mutex messages_mutex;
  22403. sse.on_message([&](const sse::SSEMessage &msg) {
  22404. std::lock_guard<std::mutex> lock(messages_mutex);
  22405. received_messages.push_back(msg.data);
  22406. });
  22407. sse.set_reconnect_interval(100);
  22408. sse.set_max_reconnect_attempts(1);
  22409. sse.start_async();
  22410. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22411. sse.stop();
  22412. std::lock_guard<std::mutex> lock(messages_mutex);
  22413. EXPECT_GE(received_messages.size(), 2u);
  22414. if (received_messages.size() >= 2) {
  22415. EXPECT_EQ(received_messages[0], "message1");
  22416. EXPECT_EQ(received_messages[1], "message2");
  22417. }
  22418. }
  22419. // Test: on_event for specific types
  22420. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22421. Client client("localhost", get_port());
  22422. sse::SSEClient sse(client, "/custom-events");
  22423. std::atomic<bool> update_received{false};
  22424. std::atomic<bool> delete_received{false};
  22425. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22426. if (msg.data == "updated") { update_received.store(true); }
  22427. });
  22428. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22429. if (msg.data == "deleted") { delete_received.store(true); }
  22430. });
  22431. sse.set_max_reconnect_attempts(1);
  22432. sse.start_async();
  22433. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22434. sse.stop();
  22435. EXPECT_TRUE(update_received.load());
  22436. EXPECT_TRUE(delete_received.load());
  22437. }
  22438. // Test: on_error callback on connection failure
  22439. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22440. // Connect to a non-existent port
  22441. Client client("localhost", 59999);
  22442. sse::SSEClient sse(client, "/events");
  22443. std::atomic<bool> error_called{false};
  22444. Error received_error = Error::Success;
  22445. sse.on_error([&](Error err) {
  22446. error_called.store(true);
  22447. received_error = err;
  22448. });
  22449. sse.set_reconnect_interval(50);
  22450. sse.set_max_reconnect_attempts(1);
  22451. sse.start_async();
  22452. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22453. sse.stop();
  22454. EXPECT_TRUE(error_called.load());
  22455. EXPECT_NE(received_error, Error::Success);
  22456. }
  22457. // Test: Last-Event-ID header sent on reconnect
  22458. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22459. // Endpoint that sends event with ID
  22460. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22461. res.set_chunked_content_provider(
  22462. "text/event-stream", [](size_t offset, DataSink &sink) {
  22463. if (offset == 0) {
  22464. std::string event = "id: evt-123\ndata: test\n\n";
  22465. sink.write(event.data(), event.size());
  22466. }
  22467. return false;
  22468. });
  22469. });
  22470. Client client("localhost", get_port());
  22471. sse::SSEClient sse(client, "/event-with-id");
  22472. std::atomic<bool> id_received{false};
  22473. sse.on_message([&](const sse::SSEMessage &msg) {
  22474. if (!msg.id.empty()) { id_received.store(true); }
  22475. });
  22476. sse.set_reconnect_interval(100);
  22477. sse.set_max_reconnect_attempts(1);
  22478. sse.start_async();
  22479. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22480. sse.stop();
  22481. EXPECT_TRUE(id_received.load());
  22482. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22483. }
  22484. // Test: last_event_id() read from another thread while start_async() runs
  22485. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22486. // Ids of every length up to 200, so the stored id keeps changing size
  22487. server_->Get("/many-ids", [](const Request &, Response &res) {
  22488. res.set_chunked_content_provider(
  22489. "text/event-stream", [](size_t offset, DataSink &sink) {
  22490. if (offset == 0) {
  22491. std::string events;
  22492. for (size_t i = 0; i < 2000; i++) {
  22493. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22494. events += "data: x\n\n";
  22495. }
  22496. events += "id: end\ndata: x\n\n";
  22497. sink.write(events.data(), events.size());
  22498. }
  22499. return false;
  22500. });
  22501. });
  22502. Client client("localhost", get_port());
  22503. sse::SSEClient sse(client, "/many-ids");
  22504. // Wait out the rest of the test rather than replay the stream
  22505. sse.set_reconnect_interval(10000);
  22506. sse.set_max_reconnect_attempts(1);
  22507. sse.start_async();
  22508. auto well_formed = true;
  22509. std::string id;
  22510. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22511. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22512. id = sse.last_event_id();
  22513. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22514. well_formed = false;
  22515. }
  22516. }
  22517. sse.stop();
  22518. EXPECT_TRUE(well_formed);
  22519. EXPECT_EQ(sse.last_event_id(), "end");
  22520. }
  22521. // Test: Manual stop
  22522. TEST_F(SSEIntegrationTest, ManualStop) {
  22523. // Endpoint that sends one event and stays open briefly. The server outlives
  22524. // this test body, so the provider uses the fixture's flag, not a local.
  22525. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22526. res.set_chunked_content_provider(
  22527. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22528. if (offset == 0) {
  22529. std::string event = "data: connected\n\n";
  22530. sink.write(event.data(), event.size());
  22531. }
  22532. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22533. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22534. }
  22535. return false;
  22536. });
  22537. });
  22538. Client client("localhost", get_port());
  22539. sse::SSEClient sse(client, "/stay-open");
  22540. std::atomic<bool> connected{false};
  22541. sse.on_open([&connected]() { connected.store(true); });
  22542. sse.set_reconnect_interval(100);
  22543. sse.set_max_reconnect_attempts(1);
  22544. sse.start_async();
  22545. // Wait for connection to establish
  22546. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22547. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22548. }
  22549. EXPECT_TRUE(connected.load());
  22550. EXPECT_TRUE(sse.is_connected());
  22551. // Signal handler to stop
  22552. stop_server_.store(true);
  22553. // Stop SSE client
  22554. sse.stop();
  22555. EXPECT_FALSE(sse.is_connected());
  22556. }
  22557. // Sends one event, then nothing until stop is set
  22558. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22559. return [&stop](const Request &, Response &res) {
  22560. res.set_chunked_content_provider(
  22561. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22562. if (offset == 0) {
  22563. std::string event = "data: hello\n\n";
  22564. sink.write(event.data(), event.size());
  22565. }
  22566. while (!stop.load()) {
  22567. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22568. }
  22569. return false;
  22570. });
  22571. };
  22572. }
  22573. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22574. static void check_stop_interrupts_blocked_read(Client &client) {
  22575. client.set_read_timeout(30, 0);
  22576. for (auto by_destructor : {false, true}) {
  22577. std::atomic<bool> received{false};
  22578. std::chrono::steady_clock::time_point start;
  22579. {
  22580. sse::SSEClient sse(client, "/idle-stream");
  22581. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22582. sse.start_async();
  22583. for (int i = 0; i < 500 && !received.load(); ++i) {
  22584. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22585. }
  22586. ASSERT_TRUE(received.load());
  22587. // Let the client block in the next read
  22588. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22589. start = std::chrono::steady_clock::now();
  22590. if (!by_destructor) { sse.stop(); }
  22591. }
  22592. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22593. std::chrono::seconds(2));
  22594. }
  22595. }
  22596. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22597. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22598. Client client("localhost", get_port());
  22599. check_stop_interrupts_blocked_read(client);
  22600. }
  22601. #ifdef CPPHTTPLIB_SSL_ENABLED
  22602. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22604. std::atomic<bool> done{false};
  22605. svr.Get("/idle-stream", idle_event_stream(done));
  22606. auto port = svr.bind_to_any_port(HOST);
  22607. std::thread t([&] { svr.listen_after_bind(); });
  22608. auto se = detail::scope_exit([&] {
  22609. done.store(true);
  22610. svr.stop();
  22611. t.join();
  22612. });
  22613. svr.wait_until_ready();
  22614. Client client("https://localhost:" + std::to_string(port));
  22615. client.enable_server_certificate_verification(false);
  22616. check_stop_interrupts_blocked_read(client);
  22617. }
  22618. #endif
  22619. // Test: SSEClient with custom headers
  22620. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22621. // Setup a server endpoint that checks for custom header
  22622. std::atomic<bool> header_received{false};
  22623. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22624. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22625. header_received.store(true);
  22626. }
  22627. res.set_chunked_content_provider("text/event-stream",
  22628. [](size_t, DataSink &) { return false; });
  22629. });
  22630. Client client("localhost", get_port());
  22631. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22632. sse::SSEClient sse(client, "/header-check", headers);
  22633. sse.set_max_reconnect_attempts(1);
  22634. sse.start_async();
  22635. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22636. sse.stop();
  22637. EXPECT_TRUE(header_received.load());
  22638. }
  22639. // Test: Reconnect interval configuration
  22640. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22641. Client client("localhost", get_port());
  22642. sse::SSEClient sse(client, "/events");
  22643. auto &result = sse.set_reconnect_interval(500);
  22644. // Builder pattern should return reference to self
  22645. EXPECT_EQ(&result, &sse);
  22646. }
  22647. // Test: Max reconnect attempts
  22648. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22649. // Connect to non-existent port to force reconnects
  22650. Client client("localhost", 59998);
  22651. sse::SSEClient sse(client, "/events");
  22652. std::atomic<int> error_count{0};
  22653. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22654. sse.set_reconnect_interval(50);
  22655. sse.set_max_reconnect_attempts(2);
  22656. auto start = std::chrono::steady_clock::now();
  22657. sse.start(); // Blocking call
  22658. auto end = std::chrono::steady_clock::now();
  22659. // Should have stopped after 2 failed attempts
  22660. EXPECT_GE(error_count.load(), 2);
  22661. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22662. auto duration =
  22663. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22664. #ifdef _WIN32
  22665. // Windows is much slower for socket connection failures
  22666. EXPECT_LT(duration.count(), 7000);
  22667. #else
  22668. EXPECT_LT(duration.count(), 1000);
  22669. #endif
  22670. }
  22671. // Test: Multi-line data in integration
  22672. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22673. // Endpoint with multi-line data
  22674. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22675. res.set_chunked_content_provider(
  22676. "text/event-stream", [](size_t offset, DataSink &sink) {
  22677. if (offset == 0) {
  22678. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22679. sink.write(event.data(), event.size());
  22680. }
  22681. return false;
  22682. });
  22683. });
  22684. Client client("localhost", get_port());
  22685. sse::SSEClient sse(client, "/multiline-data");
  22686. std::string received_data;
  22687. std::mutex data_mutex;
  22688. sse.on_message([&](const sse::SSEMessage &msg) {
  22689. std::lock_guard<std::mutex> lock(data_mutex);
  22690. received_data = msg.data;
  22691. });
  22692. sse.set_reconnect_interval(100);
  22693. sse.set_max_reconnect_attempts(1);
  22694. sse.start_async();
  22695. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22696. sse.stop();
  22697. std::lock_guard<std::mutex> lock(data_mutex);
  22698. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22699. }
  22700. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22701. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22702. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22703. DataSink &sink) {
  22704. if (offset == 0) {
  22705. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22706. sink.write(events.data(), events.size());
  22707. }
  22708. return false;
  22709. });
  22710. });
  22711. Client client("localhost", get_port());
  22712. sse::SSEClient sse(client, "/empty-data-lines");
  22713. std::mutex mutex;
  22714. std::condition_variable cv;
  22715. std::vector<std::string> received;
  22716. sse.on_message([&](const sse::SSEMessage &msg) {
  22717. std::lock_guard<std::mutex> lock(mutex);
  22718. received.push_back(msg.data);
  22719. cv.notify_all();
  22720. });
  22721. sse.set_max_reconnect_attempts(1);
  22722. sse.start_async();
  22723. {
  22724. std::unique_lock<std::mutex> lock(mutex);
  22725. cv.wait_for(lock, std::chrono::seconds(2),
  22726. [&] { return received.size() >= 3; });
  22727. }
  22728. sse.stop();
  22729. ASSERT_GE(received.size(), 3u);
  22730. EXPECT_EQ(received[0], "");
  22731. EXPECT_EQ(received[1], "\nhello");
  22732. EXPECT_EQ(received[2], "");
  22733. }
  22734. // Test: Auto-reconnect after server disconnection
  22735. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22736. std::atomic<int> connection_count{0};
  22737. std::atomic<int> message_count{0};
  22738. // Endpoint that sends one event and closes, forcing reconnect
  22739. server_->Get("/reconnect-test",
  22740. [&connection_count](const Request &, Response &res) {
  22741. connection_count.fetch_add(1);
  22742. res.set_chunked_content_provider(
  22743. "text/event-stream", [](size_t offset, DataSink &sink) {
  22744. if (offset == 0) {
  22745. std::string event = "data: hello\n\n";
  22746. sink.write(event.data(), event.size());
  22747. }
  22748. return false; // Close connection after sending
  22749. });
  22750. });
  22751. Client client("localhost", get_port());
  22752. sse::SSEClient sse(client, "/reconnect-test");
  22753. sse.on_message([&message_count](const sse::SSEMessage &) {
  22754. message_count.fetch_add(1);
  22755. });
  22756. sse.set_reconnect_interval(100);
  22757. sse.set_max_reconnect_attempts(3);
  22758. sse.start_async();
  22759. // Wait long enough for multiple reconnects
  22760. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22761. sse.stop();
  22762. // Should have connected multiple times (initial + reconnects)
  22763. EXPECT_GE(connection_count.load(), 2);
  22764. // Should have received messages from multiple connections
  22765. EXPECT_GE(message_count.load(), 2);
  22766. }
  22767. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22768. std::atomic<int> connection_count{0};
  22769. // Neither Content-Length nor chunked: the close ends the stream
  22770. server_->Get("/close-delimited",
  22771. [&connection_count](const Request &, Response &res) {
  22772. connection_count.fetch_add(1);
  22773. res.set_content_provider(
  22774. "text/event-stream", [](size_t offset, DataSink &sink) {
  22775. if (offset == 0) {
  22776. std::string event = "data: hello\n\n";
  22777. sink.write(event.data(), event.size());
  22778. } else {
  22779. sink.done();
  22780. }
  22781. return true;
  22782. });
  22783. });
  22784. Client client("localhost", get_port());
  22785. sse::SSEClient sse(client, "/close-delimited");
  22786. std::atomic<int> error_count{0};
  22787. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22788. sse.set_reconnect_interval(100);
  22789. sse.start_async();
  22790. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22791. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22792. }
  22793. sse.stop();
  22794. // Reconnects as after any end of the stream, but reports no error
  22795. EXPECT_GE(connection_count.load(), 2);
  22796. EXPECT_EQ(0, error_count.load());
  22797. }
  22798. // Test: A retry field that is not all ASCII digits is ignored
  22799. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22800. std::atomic<int> connection_count{0};
  22801. server_->Get("/bad-retry",
  22802. [&connection_count](const Request &, Response &res) {
  22803. connection_count.fetch_add(1);
  22804. res.set_chunked_content_provider(
  22805. "text/event-stream", [](size_t offset, DataSink &sink) {
  22806. if (offset == 0) {
  22807. std::string event = "retry: -1\ndata: hello\n\n";
  22808. sink.write(event.data(), event.size());
  22809. }
  22810. return false;
  22811. });
  22812. });
  22813. Client client("localhost", get_port());
  22814. sse::SSEClient sse(client, "/bad-retry");
  22815. sse.set_reconnect_interval(10000);
  22816. sse.start_async();
  22817. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22818. sse.stop();
  22819. EXPECT_EQ(connection_count.load(), 1);
  22820. }
  22821. // Test: A retry field of all ASCII digits sets the reconnection time
  22822. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22823. std::mutex mutex;
  22824. std::condition_variable cv;
  22825. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22826. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22827. {
  22828. std::lock_guard<std::mutex> lock(mutex);
  22829. connected_at.push_back(std::chrono::steady_clock::now());
  22830. cv.notify_all();
  22831. }
  22832. res.set_chunked_content_provider(
  22833. "text/event-stream", [](size_t offset, DataSink &sink) {
  22834. if (offset == 0) {
  22835. std::string event = "retry: 0\ndata: hello\n\n";
  22836. sink.write(event.data(), event.size());
  22837. }
  22838. return false;
  22839. });
  22840. });
  22841. Client client("localhost", get_port());
  22842. sse::SSEClient sse(client, "/zero-retry");
  22843. sse.set_reconnect_interval(10000);
  22844. sse.start_async();
  22845. {
  22846. std::unique_lock<std::mutex> lock(mutex);
  22847. cv.wait_for(lock, std::chrono::seconds(5),
  22848. [&] { return connected_at.size() >= 2; });
  22849. }
  22850. sse.stop();
  22851. // The server-supplied interval is applied, but never below 100ms, so
  22852. // "retry: 0" does not cause a busy reconnect loop
  22853. std::lock_guard<std::mutex> lock(mutex);
  22854. ASSERT_GE(connected_at.size(), 2u);
  22855. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22856. connected_at[1] - connected_at[0])
  22857. .count();
  22858. EXPECT_GE(interval_ms, 100);
  22859. }
  22860. // Test: Last-Event-ID sent on reconnect
  22861. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22862. std::atomic<int> connection_count{0};
  22863. std::vector<std::string> received_last_event_ids;
  22864. std::mutex id_mutex;
  22865. // Endpoint that checks Last-Event-ID header and sends event with ID
  22866. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22867. int conn = connection_count.fetch_add(1);
  22868. // Capture the Last-Event-ID header from each connection
  22869. {
  22870. std::lock_guard<std::mutex> lock(id_mutex);
  22871. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22872. }
  22873. res.set_chunked_content_provider(
  22874. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22875. if (offset == 0) {
  22876. std::string event =
  22877. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22878. sink.write(event.data(), event.size());
  22879. }
  22880. return false;
  22881. });
  22882. });
  22883. Client client("localhost", get_port());
  22884. sse::SSEClient sse(client, "/reconnect-with-id");
  22885. sse.set_reconnect_interval(100);
  22886. sse.set_max_reconnect_attempts(3);
  22887. sse.start_async();
  22888. // Wait for at least 2 connections
  22889. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22890. sse.stop();
  22891. // Verify behavior
  22892. std::lock_guard<std::mutex> lock(id_mutex);
  22893. EXPECT_GE(received_last_event_ids.size(), 2u);
  22894. // First connection should have no Last-Event-ID
  22895. if (!received_last_event_ids.empty()) {
  22896. EXPECT_EQ(received_last_event_ids[0], "");
  22897. }
  22898. // Second connection should have Last-Event-ID from first connection
  22899. if (received_last_event_ids.size() >= 2) {
  22900. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22901. }
  22902. }
  22903. // Test: set_headers updates headers used on reconnect
  22904. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22905. std::vector<std::string> received_tokens;
  22906. std::mutex token_mutex;
  22907. // Endpoint that captures Authorization header
  22908. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22909. {
  22910. std::lock_guard<std::mutex> lock(token_mutex);
  22911. received_tokens.push_back(req.get_header_value("Authorization"));
  22912. }
  22913. res.set_chunked_content_provider(
  22914. "text/event-stream", [](size_t offset, DataSink &sink) {
  22915. if (offset == 0) {
  22916. std::string event = "data: hello\n\n";
  22917. sink.write(event.data(), event.size());
  22918. }
  22919. return false; // Close connection to trigger reconnect
  22920. });
  22921. });
  22922. Client client("localhost", get_port());
  22923. Headers headers = {{"Authorization", "Bearer old-token"}};
  22924. sse::SSEClient sse(client, "/auth-check", headers);
  22925. // Update headers on each successful connection
  22926. sse.on_open(
  22927. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22928. sse.set_reconnect_interval(100);
  22929. sse.set_max_reconnect_attempts(3);
  22930. sse.start_async();
  22931. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22932. sse.stop();
  22933. std::lock_guard<std::mutex> lock(token_mutex);
  22934. ASSERT_GE(received_tokens.size(), 2u);
  22935. // First connection uses original header
  22936. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22937. // Second connection uses updated header from set_headers
  22938. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22939. }
  22940. // Test: 401 allows reconnection (so on_error can refresh headers)
  22941. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22942. std::atomic<int> connection_count{0};
  22943. // Endpoint: returns 401 on first attempt, 200 on second
  22944. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22945. int conn = connection_count.fetch_add(1);
  22946. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22947. res.status = StatusCode::Unauthorized_401;
  22948. res.set_content("Unauthorized", "text/plain");
  22949. return;
  22950. }
  22951. res.set_chunked_content_provider(
  22952. "text/event-stream", [](size_t offset, DataSink &sink) {
  22953. if (offset == 0) {
  22954. std::string event = "data: authenticated\n\n";
  22955. sink.write(event.data(), event.size());
  22956. }
  22957. return false;
  22958. });
  22959. });
  22960. Client client("localhost", get_port());
  22961. Headers headers = {{"Authorization", "Bearer expired"}};
  22962. sse::SSEClient sse(client, "/auth-retry", headers);
  22963. std::atomic<bool> message_received{false};
  22964. // Refresh token on error
  22965. sse.on_error(
  22966. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22967. sse.on_message([&](const sse::SSEMessage &msg) {
  22968. if (msg.data == "authenticated") { message_received.store(true); }
  22969. });
  22970. sse.set_reconnect_interval(100);
  22971. sse.set_max_reconnect_attempts(3);
  22972. sse.start_async();
  22973. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22974. sse.stop();
  22975. // Should have reconnected after 401 and succeeded with new token
  22976. EXPECT_GE(connection_count.load(), 2);
  22977. EXPECT_TRUE(message_received.load());
  22978. }
  22979. TEST(Issue2318Test, EmptyHostString) {
  22980. {
  22981. httplib::Client cli_empty("", PORT);
  22982. auto res = cli_empty.Get("/");
  22983. ASSERT_FALSE(res);
  22984. EXPECT_EQ(httplib::Error::Connection, res.error());
  22985. }
  22986. {
  22987. httplib::Client cli(" ", PORT);
  22988. auto res = cli.Get("/");
  22989. ASSERT_FALSE(res);
  22990. EXPECT_EQ(httplib::Error::Connection, res.error());
  22991. }
  22992. }
  22993. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22994. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22995. Server svr;
  22996. // Set a small payload limit (1KB)
  22997. svr.set_payload_max_length(1024);
  22998. svr.Post("/test", [&](const Request &req, Response &res) {
  22999. res.set_content("Body size: " + std::to_string(req.body.size()),
  23000. "text/plain");
  23001. });
  23002. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23003. auto se = detail::scope_exit([&] {
  23004. svr.stop();
  23005. listen_thread.join();
  23006. });
  23007. svr.wait_until_ready();
  23008. // Create data that compresses well but exceeds limit when decompressed
  23009. // 8KB of repeated null bytes compresses to a very small size
  23010. std::string original_data(8 * 1024, '\0');
  23011. // Compress the data using gzip
  23012. std::string compressed_data;
  23013. detail::gzip_compressor compressor;
  23014. compressor.compress(original_data.data(), original_data.size(), true,
  23015. [&](const char *data, size_t size) {
  23016. compressed_data.append(data, size);
  23017. return true;
  23018. });
  23019. // Verify compression worked (compressed should be much smaller)
  23020. ASSERT_LT(compressed_data.size(), original_data.size());
  23021. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23022. // Send compressed data with Content-Encoding: gzip
  23023. Client cli(HOST, PORT);
  23024. Headers headers = {{"Content-Encoding", "gzip"}};
  23025. auto res =
  23026. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23027. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23029. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23030. }
  23031. #endif
  23032. // ============================================================================
  23033. // OpenSSL-Specific Tests
  23034. // ============================================================================
  23035. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23036. X509 *readCertificate(const std::string &strFileName) {
  23037. std::ifstream inStream(strFileName);
  23038. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23039. std::istreambuf_iterator<char>());
  23040. if (strCertPEM.empty()) return (nullptr);
  23041. BIO *pbCert = BIO_new(BIO_s_mem());
  23042. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23043. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23044. BIO_free(pbCert);
  23045. return (pCert);
  23046. }
  23047. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23048. std::ifstream inStream(strFileName);
  23049. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23050. std::istreambuf_iterator<char>());
  23051. if (strPrivateKeyPEM.empty()) return (nullptr);
  23052. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23053. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23054. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23055. BIO_free(pbPrivKey);
  23056. return (pPrivateKey);
  23057. }
  23058. TEST(BindServerTest, UpdateCerts) {
  23059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23060. int port = svr.bind_to_any_port("0.0.0.0");
  23061. ASSERT_TRUE(svr.is_valid());
  23062. ASSERT_TRUE(port > 0);
  23063. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23064. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23065. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23066. ASSERT_TRUE(cert != nullptr);
  23067. ASSERT_TRUE(ca_cert != nullptr);
  23068. ASSERT_TRUE(key != nullptr);
  23069. X509_STORE *cert_store = X509_STORE_new();
  23070. X509_STORE_add_cert(cert_store, ca_cert);
  23071. // svr.update_certs(cert, key, cert_store); // deprecated
  23072. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23073. CLIENT_CA_CERT_FILE);
  23074. ASSERT_TRUE(svr.is_valid());
  23075. svr.stop();
  23076. X509_STORE_free(cert_store);
  23077. X509_free(cert);
  23078. X509_free(ca_cert);
  23079. EVP_PKEY_free(key);
  23080. }
  23081. // Test that update_certs() updates client CA list correctly
  23082. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23083. // Start with file-based constructor
  23084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23085. ASSERT_TRUE(svr.is_valid());
  23086. // Initially no client CA list should be set
  23087. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23088. ASSERT_TRUE(ssl_ctx != nullptr);
  23089. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23090. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23091. // Now update with client CA (PEM string)
  23092. std::string cert_pem, key_pem, ca_pem;
  23093. read_file(SERVER_CERT_FILE, cert_pem);
  23094. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23095. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23096. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23097. ASSERT_TRUE(svr.is_valid());
  23098. // Now client CA list should be set
  23099. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23100. ASSERT_TRUE(ca_list_after != nullptr);
  23101. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23102. }
  23103. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23104. // Test that the file-path SSLServer constructor properly sets the client CA
  23105. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23107. ASSERT_TRUE(svr.is_valid());
  23108. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23109. ASSERT_TRUE(ssl_ctx != nullptr);
  23110. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23111. ASSERT_TRUE(ca_list != nullptr);
  23112. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23113. }
  23114. #endif
  23115. // ============================================================================
  23116. // MbedTLS-Specific Tests
  23117. // ============================================================================
  23118. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23119. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23120. using namespace httplib::tls;
  23121. // Track if callback was invoked
  23122. bool callback_invoked = false;
  23123. // The callback receives void* ctx which is actually MbedTlsContext*
  23124. // We can access the mbedtls_ssl_config via the context
  23125. auto setup_callback = [&callback_invoked](void *ctx) {
  23126. callback_invoked = true;
  23127. // Cast to MbedTlsContext* to access the ssl config
  23128. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23129. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23130. // Use static variables to hold certificate data (simplified for test)
  23131. static mbedtls_x509_crt own_cert;
  23132. static mbedtls_pk_context own_key;
  23133. static mbedtls_x509_crt ca_chain;
  23134. static bool initialized = false;
  23135. if (!initialized) {
  23136. mbedtls_x509_crt_init(&own_cert);
  23137. mbedtls_pk_init(&own_key);
  23138. mbedtls_x509_crt_init(&ca_chain);
  23139. // Load server certificate
  23140. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23141. return false;
  23142. }
  23143. // Load server private key.
  23144. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23145. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23146. #if MBEDTLS_VERSION_MAJOR == 3
  23147. ,
  23148. mbedtls_ctr_drbg_random, nullptr
  23149. #endif
  23150. ) != 0) {
  23151. return false;
  23152. }
  23153. // Load CA chain for client verification
  23154. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23155. return false;
  23156. }
  23157. initialized = true;
  23158. }
  23159. // Configure the SSL config
  23160. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23161. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23162. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23163. // Set minimum TLS version using mbedTLS native API
  23164. #if MBEDTLS_VERSION_MAJOR >= 3
  23165. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23166. #else
  23167. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23168. MBEDTLS_SSL_MINOR_VERSION_3);
  23169. #endif
  23170. return true;
  23171. };
  23172. SSLServer svr(setup_callback);
  23173. ASSERT_TRUE(svr.is_valid());
  23174. ASSERT_TRUE(callback_invoked);
  23175. svr.Get("/test", [&](const Request &req, Response &res) {
  23176. res.set_content("test", "text/plain");
  23177. auto cert = req.peer_cert();
  23178. ASSERT_TRUE(static_cast<bool>(cert));
  23179. auto common_name = cert.subject_cn();
  23180. EXPECT_EQ("Common Name", common_name);
  23181. });
  23182. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23183. auto se = detail::scope_exit([&] {
  23184. svr.stop();
  23185. t.join();
  23186. ASSERT_FALSE(svr.is_running());
  23187. });
  23188. svr.wait_until_ready();
  23189. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23190. cli.enable_server_certificate_verification(false);
  23191. cli.set_connection_timeout(30);
  23192. auto res = cli.Get("/test");
  23193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23194. ASSERT_EQ(StatusCode::OK_200, res->status);
  23195. }
  23196. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23197. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23198. // keep-alive SSL session, which reads through that config in
  23199. // mbedtls_ssl_close_notify.
  23200. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23202. ASSERT_TRUE(svr.is_valid());
  23203. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23204. res.set_content("test", "text/plain");
  23205. });
  23206. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23207. auto se = detail::scope_exit([&] {
  23208. svr.stop();
  23209. t.join();
  23210. ASSERT_FALSE(svr.is_running());
  23211. });
  23212. svr.wait_until_ready();
  23213. {
  23214. SSLClient cli(HOST, PORT);
  23215. cli.enable_server_certificate_verification(false);
  23216. cli.set_keep_alive(true);
  23217. auto res = cli.Get("/test");
  23218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23219. ASSERT_EQ(StatusCode::OK_200, res->status);
  23220. // cli is destructed here with the keep-alive SSL session still open.
  23221. }
  23222. }
  23223. #endif
  23224. // WebSocket Tests
  23225. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23226. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23227. // defining the meaning of these bits has been negotiated.
  23228. auto make_frame = [](uint8_t first_byte) {
  23229. std::string frame;
  23230. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23231. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23232. frame += "Hello";
  23233. return frame;
  23234. };
  23235. // RSV1 set (0x40)
  23236. {
  23237. detail::BufferStream strm;
  23238. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23239. ws::Opcode opcode;
  23240. std::string payload;
  23241. bool fin;
  23242. EXPECT_EQ(
  23243. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23244. ws::impl::FrameRead::Fail);
  23245. }
  23246. // RSV2 set (0x20)
  23247. {
  23248. detail::BufferStream strm;
  23249. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23250. ws::Opcode opcode;
  23251. std::string payload;
  23252. bool fin;
  23253. EXPECT_EQ(
  23254. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23255. ws::impl::FrameRead::Fail);
  23256. }
  23257. // RSV3 set (0x10)
  23258. {
  23259. detail::BufferStream strm;
  23260. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23261. ws::Opcode opcode;
  23262. std::string payload;
  23263. bool fin;
  23264. EXPECT_EQ(
  23265. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23266. ws::impl::FrameRead::Fail);
  23267. }
  23268. // No RSV bits set - should succeed
  23269. {
  23270. detail::BufferStream strm;
  23271. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23272. ws::Opcode opcode;
  23273. std::string payload;
  23274. bool fin;
  23275. EXPECT_EQ(
  23276. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23277. ws::impl::FrameRead::Ok);
  23278. EXPECT_EQ(ws::Opcode::Text, opcode);
  23279. EXPECT_EQ("Hello", payload);
  23280. EXPECT_TRUE(fin);
  23281. }
  23282. }
  23283. TEST(WebSocketTest, ControlFrameValidation) {
  23284. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23285. // payload length <= 125.
  23286. // Ping with FIN=0 - must be rejected
  23287. {
  23288. detail::BufferStream strm;
  23289. std::string frame;
  23290. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23291. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23292. strm.write(frame.data(), frame.size());
  23293. ws::Opcode opcode;
  23294. std::string payload;
  23295. bool fin;
  23296. EXPECT_EQ(
  23297. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23298. ws::impl::FrameRead::Fail);
  23299. }
  23300. // Close with FIN=0 - must be rejected
  23301. {
  23302. detail::BufferStream strm;
  23303. std::string frame;
  23304. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23305. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23306. strm.write(frame.data(), frame.size());
  23307. ws::Opcode opcode;
  23308. std::string payload;
  23309. bool fin;
  23310. EXPECT_EQ(
  23311. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23312. ws::impl::FrameRead::Fail);
  23313. }
  23314. // Ping with payload_len=126 (extended length) - must be rejected
  23315. {
  23316. detail::BufferStream strm;
  23317. std::string frame;
  23318. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23319. frame += static_cast<char>(126); // payload_len=126 (>125)
  23320. frame += static_cast<char>(0x00); // extended length high byte
  23321. frame += static_cast<char>(126); // extended length low byte
  23322. frame += std::string(126, 'x');
  23323. strm.write(frame.data(), frame.size());
  23324. ws::Opcode opcode;
  23325. std::string payload;
  23326. bool fin;
  23327. EXPECT_EQ(
  23328. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23329. ws::impl::FrameRead::Fail);
  23330. }
  23331. // Ping with FIN=1 and payload_len=125 - should succeed
  23332. {
  23333. detail::BufferStream strm;
  23334. std::string frame;
  23335. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23336. frame += static_cast<char>(125); // payload_len=125
  23337. frame += std::string(125, 'x');
  23338. strm.write(frame.data(), frame.size());
  23339. ws::Opcode opcode;
  23340. std::string payload;
  23341. bool fin;
  23342. EXPECT_EQ(
  23343. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23344. ws::impl::FrameRead::Ok);
  23345. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23346. EXPECT_EQ(125u, payload.size());
  23347. EXPECT_TRUE(fin);
  23348. }
  23349. }
  23350. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23351. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23352. // length MUST be 0.
  23353. // MSB set - must be rejected
  23354. {
  23355. detail::BufferStream strm;
  23356. std::string frame;
  23357. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23358. frame += static_cast<char>(127); // 64-bit extended length
  23359. frame += static_cast<char>(0x80); // MSB set (invalid)
  23360. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23361. strm.write(frame.data(), frame.size());
  23362. ws::Opcode opcode;
  23363. std::string payload;
  23364. bool fin;
  23365. EXPECT_EQ(
  23366. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23367. ws::impl::FrameRead::Fail);
  23368. }
  23369. // MSB clear - should pass length parsing (will be rejected by max_len,
  23370. // but that's a different check; use a small length to verify)
  23371. {
  23372. detail::BufferStream strm;
  23373. std::string frame;
  23374. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23375. frame += static_cast<char>(127); // 64-bit extended length
  23376. frame += std::string(7, '\0'); // high bytes = 0
  23377. frame += static_cast<char>(0x03); // length = 3
  23378. frame += "abc";
  23379. strm.write(frame.data(), frame.size());
  23380. ws::Opcode opcode;
  23381. std::string payload;
  23382. bool fin;
  23383. EXPECT_EQ(
  23384. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23385. ws::impl::FrameRead::Ok);
  23386. EXPECT_EQ(ws::Opcode::Text, opcode);
  23387. EXPECT_EQ("abc", payload);
  23388. }
  23389. }
  23390. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23391. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23392. // Valid UTF-8
  23393. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23394. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23395. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23396. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23397. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23398. // Invalid UTF-8
  23399. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23400. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23401. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23402. EXPECT_FALSE(
  23403. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23404. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23405. }
  23406. TEST(WebSocketTest, ConnectAndDisconnect) {
  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. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23416. auto res = client.connect();
  23417. ASSERT_TRUE(res);
  23418. EXPECT_EQ(Error::Success, res.error());
  23419. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23420. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23421. EXPECT_TRUE(client.is_open());
  23422. client.close();
  23423. EXPECT_FALSE(client.is_open());
  23424. svr.stop();
  23425. t.join();
  23426. }
  23427. TEST(WebSocketTest, ValidURL) {
  23428. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23429. EXPECT_TRUE(ws1.is_valid());
  23430. ws::WebSocketClient ws2("ws://example.com/path");
  23431. EXPECT_TRUE(ws2.is_valid());
  23432. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23433. EXPECT_TRUE(ws3.is_valid());
  23434. #ifdef CPPHTTPLIB_SSL_ENABLED
  23435. ws::WebSocketClient wss1("wss://example.com/path");
  23436. EXPECT_TRUE(wss1.is_valid());
  23437. ws::WebSocketClient wss2("wss://example.com:443/path");
  23438. EXPECT_TRUE(wss2.is_valid());
  23439. #endif
  23440. }
  23441. TEST(WebSocketTest, InvalidURL) {
  23442. // No scheme
  23443. ws::WebSocketClient ws1("localhost:8080/path");
  23444. EXPECT_FALSE(ws1.is_valid());
  23445. // No path
  23446. ws::WebSocketClient ws2("ws://localhost:8080");
  23447. EXPECT_FALSE(ws2.is_valid());
  23448. // Empty string
  23449. ws::WebSocketClient ws3("");
  23450. EXPECT_FALSE(ws3.is_valid());
  23451. // Missing host
  23452. ws::WebSocketClient ws4("ws://:8080/path");
  23453. EXPECT_FALSE(ws4.is_valid());
  23454. // Port number overflow — should not crash
  23455. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23456. EXPECT_FALSE(ws5.is_valid());
  23457. // Port out of range
  23458. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23459. EXPECT_FALSE(ws6.is_valid());
  23460. }
  23461. TEST(WebSocketTest, UnsupportedScheme) {
  23462. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23463. ws::WebSocketClient ws1("http://localhost:8080/path");
  23464. EXPECT_FALSE(ws1.is_valid());
  23465. ws::WebSocketClient ws2("https://localhost:8080/path");
  23466. EXPECT_FALSE(ws2.is_valid());
  23467. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23468. EXPECT_FALSE(ws3.is_valid());
  23469. #else
  23470. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23471. std::invalid_argument);
  23472. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23473. std::invalid_argument);
  23474. #endif
  23475. }
  23476. TEST(WebSocketTest, ConnectWhenInvalid) {
  23477. ws::WebSocketClient ws("not a valid url");
  23478. EXPECT_FALSE(ws.is_valid());
  23479. auto res = ws.connect();
  23480. EXPECT_FALSE(res);
  23481. EXPECT_EQ(Error::Connection, res.error());
  23482. EXPECT_EQ(-1, res.status());
  23483. }
  23484. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23485. // Grab a port that is free, then close it again so nothing listens there
  23486. Server svr;
  23487. auto port = svr.bind_to_any_port(HOST);
  23488. svr.stop();
  23489. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23490. auto res = client.connect();
  23491. ASSERT_FALSE(res);
  23492. EXPECT_EQ(Error::Connection, res.error());
  23493. EXPECT_EQ(-1, res.status());
  23494. }
  23495. TEST(WebSocketTest, DefaultPort) {
  23496. ws::WebSocketClient ws1("ws://example.com/path");
  23497. EXPECT_TRUE(ws1.is_valid());
  23498. // ws:// defaults to port 80 (verified by successful parse)
  23499. #ifdef CPPHTTPLIB_SSL_ENABLED
  23500. ws::WebSocketClient ws2("wss://example.com/path");
  23501. EXPECT_TRUE(ws2.is_valid());
  23502. // wss:// defaults to port 443 (verified by successful parse)
  23503. #endif
  23504. }
  23505. TEST(WebSocketTest, IPv6LiteralAddress) {
  23506. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23507. EXPECT_TRUE(ws1.is_valid());
  23508. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23509. EXPECT_TRUE(ws2.is_valid());
  23510. }
  23511. TEST(WebSocketTest, ComplexPath) {
  23512. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23513. EXPECT_TRUE(ws1.is_valid());
  23514. ws::WebSocketClient ws2("ws://localhost:8080/");
  23515. EXPECT_TRUE(ws2.is_valid());
  23516. }
  23517. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23518. Server svr;
  23519. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23520. std::string msg;
  23521. while (ws.read(msg)) {}
  23522. });
  23523. auto port = svr.bind_to_any_port(HOST);
  23524. std::thread t([&]() { svr.listen_after_bind(); });
  23525. svr.wait_until_ready();
  23526. auto another_host = "example.com";
  23527. auto wrong_ip = "192.0.2.1";
  23528. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23529. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23530. ASSERT_TRUE(client.connect());
  23531. EXPECT_TRUE(client.is_open());
  23532. client.close();
  23533. svr.stop();
  23534. t.join();
  23535. }
  23536. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23537. Server svr;
  23538. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23539. std::string msg;
  23540. while (ws.read(msg)) {}
  23541. });
  23542. auto port = svr.bind_to_any_port(HOST);
  23543. std::thread t([&]() { svr.listen_after_bind(); });
  23544. svr.wait_until_ready();
  23545. auto wrong_ip = "192.0.2.1";
  23546. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23547. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23548. client.set_connection_timeout(1);
  23549. client.set_read_timeout(1);
  23550. client.set_write_timeout(1);
  23551. EXPECT_FALSE(client.connect());
  23552. EXPECT_FALSE(client.is_open());
  23553. svr.stop();
  23554. t.join();
  23555. }
  23556. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23557. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23558. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23559. // (RFC 6761) is only a map key and the Host header value.
  23560. auto host = "target.invalid";
  23561. Server svr;
  23562. std::string received_host;
  23563. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23564. received_host = req.get_header_value("Host");
  23565. std::string msg;
  23566. while (ws.read(msg)) {}
  23567. });
  23568. auto port = svr.bind_to_any_port(HOST);
  23569. std::thread t([&]() { svr.listen_after_bind(); });
  23570. // ASSERT_* below returns from the test body, which would leave t joinable
  23571. // and make ~thread call std::terminate.
  23572. auto se = detail::scope_exit([&] {
  23573. svr.stop();
  23574. if (t.joinable()) { t.join(); }
  23575. });
  23576. svr.wait_until_ready();
  23577. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23578. std::to_string(port) + "/ws");
  23579. client.set_hostname_addr_map({{host, HOST}});
  23580. ASSERT_TRUE(client.connect());
  23581. EXPECT_TRUE(client.is_open());
  23582. client.close();
  23583. svr.stop();
  23584. t.join();
  23585. // The mapping only redirects the connection; the identity stays host_.
  23586. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23587. }
  23588. class WebSocketIntegrationTest : public ::testing::Test {
  23589. protected:
  23590. void SetUp() override {
  23591. server_ = httplib::detail::make_unique<Server>();
  23592. setup_server();
  23593. start_server();
  23594. }
  23595. void TearDown() override {
  23596. server_->stop();
  23597. if (server_thread_.joinable()) { server_thread_.join(); }
  23598. }
  23599. void setup_server() {
  23600. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23601. std::string msg;
  23602. ws::ReadResult ret;
  23603. while ((ret = ws.read(msg))) {
  23604. if (ret == ws::Binary) {
  23605. ws.send(msg.data(), msg.size());
  23606. } else {
  23607. ws.send(msg);
  23608. }
  23609. }
  23610. });
  23611. server_->WebSocket("/ws-echo-string",
  23612. [](const Request &, ws::WebSocket &ws) {
  23613. std::string msg;
  23614. while (ws.read(msg)) {
  23615. ws.send("echo: " + msg);
  23616. }
  23617. });
  23618. server_->WebSocket(
  23619. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23620. // Echo back request metadata
  23621. ws.send("path:" + req.path);
  23622. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23623. std::string msg;
  23624. while (ws.read(msg)) {}
  23625. });
  23626. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23627. std::string msg;
  23628. ws.read(msg); // wait for a message
  23629. ws.close();
  23630. });
  23631. server_->WebSocket("/ws-close-status",
  23632. [](const Request &, ws::WebSocket &ws) {
  23633. std::string msg;
  23634. ws.read(msg); // wait for a message
  23635. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23636. });
  23637. server_->WebSocket(
  23638. "/ws-subprotocol",
  23639. [](const Request &, ws::WebSocket &ws) {
  23640. std::string msg;
  23641. while (ws.read(msg)) {
  23642. ws.send(msg);
  23643. }
  23644. },
  23645. [](const std::vector<std::string> &protocols) -> std::string {
  23646. for (const auto &p : protocols) {
  23647. if (p == "graphql-ws") { return p; }
  23648. }
  23649. return "";
  23650. });
  23651. server_->WebSocket(
  23652. "/ws-subprotocol-unoffered",
  23653. [](const Request &, ws::WebSocket &ws) {
  23654. std::string msg;
  23655. while (ws.read(msg)) {
  23656. ws.send(msg);
  23657. }
  23658. },
  23659. [](const std::vector<std::string> &) -> std::string {
  23660. return "admin";
  23661. });
  23662. }
  23663. void start_server() {
  23664. port_ = server_->bind_to_any_port(HOST);
  23665. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23666. server_->wait_until_ready();
  23667. }
  23668. std::unique_ptr<Server> server_;
  23669. std::thread server_thread_;
  23670. int port_ = 0;
  23671. };
  23672. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23673. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23674. "/ws-echo");
  23675. ASSERT_TRUE(client.connect());
  23676. ASSERT_TRUE(client.is_open());
  23677. ASSERT_TRUE(client.send("Hello WebSocket"));
  23678. std::string msg;
  23679. EXPECT_EQ(ws::Text, client.read(msg));
  23680. EXPECT_EQ("Hello WebSocket", msg);
  23681. client.close();
  23682. }
  23683. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23685. "/ws-echo");
  23686. ASSERT_TRUE(client.connect());
  23687. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23688. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23689. std::string msg;
  23690. EXPECT_EQ(ws::Binary, client.read(msg));
  23691. EXPECT_EQ(binary_data, msg);
  23692. client.close();
  23693. }
  23694. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23695. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23696. "/ws-echo");
  23697. ASSERT_TRUE(client.connect());
  23698. for (int i = 0; i < 10; i++) {
  23699. auto text = "message " + std::to_string(i);
  23700. ASSERT_TRUE(client.send(text));
  23701. std::string msg;
  23702. ASSERT_TRUE(client.read(msg));
  23703. EXPECT_EQ(text, msg);
  23704. }
  23705. client.close();
  23706. }
  23707. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23708. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23709. "/ws-close");
  23710. ASSERT_TRUE(client.connect());
  23711. // Send a message to trigger the server to close
  23712. ASSERT_TRUE(client.send("trigger close"));
  23713. // The server will close, so read should return false
  23714. std::string msg;
  23715. EXPECT_FALSE(client.read(msg));
  23716. EXPECT_FALSE(client.is_open());
  23717. }
  23718. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23719. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23720. "/ws-echo");
  23721. ASSERT_TRUE(client.connect());
  23722. // 128KB message
  23723. std::string large_data(128 * 1024, 'X');
  23724. ASSERT_TRUE(client.send(large_data));
  23725. std::string msg;
  23726. ASSERT_TRUE(client.read(msg));
  23727. EXPECT_EQ(large_data, msg);
  23728. client.close();
  23729. }
  23730. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23731. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23732. "/ws-echo");
  23733. ASSERT_TRUE(client.connect());
  23734. const int num_threads = 4;
  23735. std::vector<std::thread> threads;
  23736. std::atomic<int> send_count{0};
  23737. for (int t = 0; t < num_threads; t++) {
  23738. threads.emplace_back([&client, &send_count, t]() {
  23739. for (int i = 0; i < 5; i++) {
  23740. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23741. if (client.send(text)) { send_count++; }
  23742. }
  23743. });
  23744. }
  23745. for (auto &th : threads) {
  23746. th.join();
  23747. }
  23748. int received = 0;
  23749. std::string msg;
  23750. while (received < send_count.load()) {
  23751. if (!client.read(msg)) { break; }
  23752. received++;
  23753. }
  23754. EXPECT_EQ(send_count.load(), received);
  23755. client.close();
  23756. }
  23757. TEST_F(WebSocketIntegrationTest, ReadString) {
  23758. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23759. "/ws-echo-string");
  23760. ASSERT_TRUE(client.connect());
  23761. ASSERT_TRUE(client.send("hello"));
  23762. std::string msg;
  23763. ASSERT_TRUE(client.read(msg));
  23764. EXPECT_EQ("echo: hello", msg);
  23765. ASSERT_TRUE(client.send("world"));
  23766. ASSERT_TRUE(client.read(msg));
  23767. EXPECT_EQ("echo: world", msg);
  23768. client.close();
  23769. }
  23770. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23771. Headers headers = {{"X-Test-Header", "test-value"}};
  23772. ws::WebSocketClient client(
  23773. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23774. ASSERT_TRUE(client.connect());
  23775. std::string msg;
  23776. ASSERT_TRUE(client.read(msg));
  23777. EXPECT_EQ("path:/ws-request-info", msg);
  23778. ASSERT_TRUE(client.read(msg));
  23779. EXPECT_EQ("header:test-value", msg);
  23780. client.close();
  23781. }
  23782. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23783. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23784. "/ws-echo");
  23785. client.set_read_timeout(1, 0); // 1 second
  23786. ASSERT_TRUE(client.connect());
  23787. // Don't send anything — server echo handler waits for a message, so read()
  23788. // should time out. The connection survives it: nothing was consumed.
  23789. std::string msg;
  23790. EXPECT_EQ(client.read(msg), ws::Timeout);
  23791. EXPECT_TRUE(client.is_open());
  23792. // And it is still usable afterwards.
  23793. EXPECT_TRUE(client.send("after timeout"));
  23794. EXPECT_EQ(client.read(msg), ws::Text);
  23795. EXPECT_EQ(msg, "after timeout");
  23796. }
  23797. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23798. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23799. "/ws-echo");
  23800. client.set_read_timeout(1, 0);
  23801. ASSERT_TRUE(client.connect());
  23802. ASSERT_TRUE(client.send("first"));
  23803. std::string msg;
  23804. ASSERT_EQ(client.read(msg), ws::Text);
  23805. ASSERT_EQ(msg, "first");
  23806. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23807. // not be used with a read timeout: it would reprocess the previous message.
  23808. EXPECT_EQ(client.read(msg), ws::Timeout);
  23809. EXPECT_EQ(msg, "first");
  23810. }
  23811. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23812. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23813. "/ws-echo");
  23814. ASSERT_TRUE(client.connect());
  23815. // Setting it once the connection is open reaches the live stream, not just
  23816. // the seed for the next connect().
  23817. client.set_read_timeout(1, 0);
  23818. std::string msg;
  23819. EXPECT_EQ(client.read(msg), ws::Timeout);
  23820. EXPECT_TRUE(client.is_open());
  23821. }
  23822. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23823. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23824. "/ws-echo");
  23825. client.set_read_timeout(5, 0);
  23826. ASSERT_TRUE(client.connect());
  23827. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23828. // The server should reject it and close the connection.
  23829. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23830. client.send(oversized);
  23831. // The server's read() should have failed due to payload limit,
  23832. // so our read() should return false (connection closed).
  23833. std::string msg;
  23834. EXPECT_FALSE(client.read(msg));
  23835. }
  23836. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23837. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23838. "/ws-echo");
  23839. client.set_read_timeout(10, 0);
  23840. ASSERT_TRUE(client.connect());
  23841. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23842. // This should succeed.
  23843. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23844. ASSERT_TRUE(client.send(at_limit));
  23845. std::string msg;
  23846. ASSERT_TRUE(client.read(msg));
  23847. EXPECT_EQ(at_limit.size(), msg.size());
  23848. client.close();
  23849. }
  23850. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23851. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23852. "/nonexistent");
  23853. auto res = client.connect();
  23854. EXPECT_FALSE(res);
  23855. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23856. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23857. EXPECT_FALSE(client.is_open());
  23858. }
  23859. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23860. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23861. "/ws-echo");
  23862. ASSERT_TRUE(client.connect());
  23863. ASSERT_TRUE(client.send(""));
  23864. std::string msg;
  23865. EXPECT_EQ(ws::Text, client.read(msg));
  23866. EXPECT_EQ("", msg);
  23867. client.close();
  23868. }
  23869. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23870. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23871. "/ws-echo");
  23872. // First connection
  23873. ASSERT_TRUE(client.connect());
  23874. ASSERT_TRUE(client.send("first"));
  23875. std::string msg;
  23876. ASSERT_TRUE(client.read(msg));
  23877. EXPECT_EQ("first", msg);
  23878. client.close();
  23879. EXPECT_FALSE(client.is_open());
  23880. // Reconnect using the same client object
  23881. ASSERT_TRUE(client.connect());
  23882. ASSERT_TRUE(client.is_open());
  23883. ASSERT_TRUE(client.send("second"));
  23884. ASSERT_TRUE(client.read(msg));
  23885. EXPECT_EQ("second", msg);
  23886. client.close();
  23887. }
  23888. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23890. "/ws-close-status");
  23891. ASSERT_TRUE(client.connect());
  23892. // Trigger the server to close with GoingAway status
  23893. ASSERT_TRUE(client.send("trigger"));
  23894. // read() should return false after receiving the close frame
  23895. std::string msg;
  23896. EXPECT_FALSE(client.read(msg));
  23897. EXPECT_FALSE(client.is_open());
  23898. }
  23899. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23900. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23901. "/ws-echo");
  23902. ASSERT_TRUE(client.connect());
  23903. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23904. EXPECT_FALSE(client.is_open());
  23905. }
  23906. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23907. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23908. ws::WebSocketClient client(
  23909. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23910. ASSERT_TRUE(client.connect());
  23911. // Server should have selected graphql-ws
  23912. EXPECT_EQ("graphql-ws", client.subprotocol());
  23913. client.close();
  23914. }
  23915. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23916. Headers headers;
  23917. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23918. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23919. ws::WebSocketClient client(
  23920. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23921. ASSERT_TRUE(client.connect());
  23922. // The offer on the second field line counts too, so graphql-ws is selected
  23923. EXPECT_EQ("graphql-ws", client.subprotocol());
  23924. client.close();
  23925. }
  23926. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23927. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23928. ws::WebSocketClient client(
  23929. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23930. ASSERT_TRUE(client.connect());
  23931. // Server should not have selected any subprotocol
  23932. EXPECT_TRUE(client.subprotocol().empty());
  23933. client.close();
  23934. }
  23935. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23936. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23938. "/ws-subprotocol-unoffered",
  23939. headers);
  23940. ASSERT_TRUE(client.connect());
  23941. EXPECT_TRUE(client.subprotocol().empty());
  23942. client.close();
  23943. }
  23944. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23945. // Connect without requesting any subprotocol
  23946. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23947. "/ws-subprotocol");
  23948. ASSERT_TRUE(client.connect());
  23949. EXPECT_TRUE(client.subprotocol().empty());
  23950. client.close();
  23951. }
  23952. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23953. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23954. "/ws-echo");
  23955. client.set_tcp_nodelay(true);
  23956. client.set_connection_timeout(3, 0);
  23957. bool socket_options_called = false;
  23958. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23959. ASSERT_TRUE(client.connect());
  23960. ASSERT_TRUE(client.is_open());
  23961. EXPECT_TRUE(socket_options_called);
  23962. ASSERT_TRUE(client.send("hello"));
  23963. std::string msg;
  23964. auto result = client.read(msg);
  23965. EXPECT_EQ(result, ws::ReadResult::Text);
  23966. EXPECT_EQ(msg, "hello");
  23967. client.close();
  23968. }
  23969. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23970. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23971. "/ws-echo");
  23972. client.set_connection_timeout(std::chrono::seconds(3));
  23973. client.set_write_timeout(std::chrono::seconds(3));
  23974. // A sub-second remainder exercises the seconds/microseconds split.
  23975. client.set_read_timeout(std::chrono::milliseconds(1500));
  23976. ASSERT_TRUE(client.connect());
  23977. auto start = std::chrono::steady_clock::now();
  23978. std::string msg;
  23979. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23980. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23981. std::chrono::steady_clock::now() - start)
  23982. .count();
  23983. // Above 1s so that dropping the microseconds half of the split fails here.
  23984. // Ignoring the setter altogether would not reach this line at all: a client
  23985. // waits forever by default.
  23986. EXPECT_GE(elapsed, 1400);
  23987. EXPECT_LT(elapsed, 30000);
  23988. }
  23989. #ifndef _WIN32
  23990. // A send() that times out after part of the data went out returns the count
  23991. // written so far. Every byte of the frame must still be sent, or the peer reads
  23992. // the next frame's header and payload as the rest of this one.
  23993. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  23994. signal(SIGPIPE, SIG_IGN);
  23995. const std::string large(4 * 1024 * 1024, 'A');
  23996. std::atomic<bool> large_sent{false};
  23997. std::atomic<bool> small_sent{false};
  23998. Server svr;
  23999. svr.set_write_timeout(0, 500000);
  24000. svr.set_socket_options([](socket_t sock) {
  24001. int size = 8192;
  24002. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24003. reinterpret_cast<const char *>(&size), sizeof(size));
  24004. });
  24005. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24006. large_sent = ws.send(large.data(), large.size());
  24007. small_sent = ws.send("after");
  24008. std::string msg;
  24009. while (ws.read(msg)) {}
  24010. });
  24011. auto port = svr.bind_to_any_port(HOST);
  24012. std::thread t([&]() { svr.listen_after_bind(); });
  24013. auto se = detail::scope_exit([&] {
  24014. svr.stop();
  24015. t.join();
  24016. });
  24017. svr.wait_until_ready();
  24018. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24019. std::to_string(port) + "/ws");
  24020. client.set_read_timeout(5);
  24021. client.set_socket_options([](socket_t sock) {
  24022. int size = 8192;
  24023. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24024. reinterpret_cast<const char *>(&size), sizeof(size));
  24025. });
  24026. ASSERT_TRUE(client.connect());
  24027. // Outlast the server's write timeout, then drain.
  24028. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24029. std::string msg;
  24030. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24031. EXPECT_TRUE(msg == large);
  24032. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24033. EXPECT_EQ("after", msg);
  24034. EXPECT_TRUE(large_sent);
  24035. EXPECT_TRUE(small_sent);
  24036. client.close();
  24037. }
  24038. #endif
  24039. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24040. Server svr;
  24041. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24042. if (!req.has_header("Authorization")) {
  24043. res.status = StatusCode::Unauthorized_401;
  24044. res.set_content("Unauthorized", "text/plain");
  24045. return Server::HandlerResponse::Handled;
  24046. }
  24047. return Server::HandlerResponse::Unhandled;
  24048. });
  24049. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24050. std::string msg;
  24051. while (ws.read(msg)) {
  24052. ws.send(msg);
  24053. }
  24054. });
  24055. auto port = svr.bind_to_any_port("localhost");
  24056. std::thread t([&]() { svr.listen_after_bind(); });
  24057. svr.wait_until_ready();
  24058. // Without Authorization header - should be rejected before upgrade
  24059. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24060. EXPECT_FALSE(client1.connect());
  24061. // The rejection is framed like any other HTTP response
  24062. {
  24063. Client cli("localhost", port);
  24064. Headers headers = {{"Upgrade", "websocket"},
  24065. {"Connection", "Upgrade"},
  24066. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24067. {"Sec-WebSocket-Version", "13"}};
  24068. auto res = cli.Get("/ws", headers);
  24069. ASSERT_TRUE(res);
  24070. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24071. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24072. EXPECT_EQ("Unauthorized", res->body);
  24073. }
  24074. // With Authorization header - should succeed
  24075. Headers headers = {{"Authorization", "Bearer token123"}};
  24076. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24077. headers);
  24078. ASSERT_TRUE(client2.connect());
  24079. ASSERT_TRUE(client2.send("hello"));
  24080. std::string msg;
  24081. ASSERT_TRUE(client2.read(msg));
  24082. EXPECT_EQ("hello", msg);
  24083. client2.close();
  24084. svr.stop();
  24085. t.join();
  24086. }
  24087. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24088. Server svr;
  24089. std::atomic<int> pre_routing_calls{0};
  24090. std::atomic<int> pre_request_calls{0};
  24091. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24092. pre_routing_calls++;
  24093. if (req.path == "/handled") {
  24094. res.set_content("handled", "text/plain");
  24095. return Server::HandlerResponse::Handled;
  24096. }
  24097. return Server::HandlerResponse::Unhandled;
  24098. });
  24099. svr.set_pre_request_handler([&](const Request &, Response &) {
  24100. pre_request_calls++;
  24101. return Server::HandlerResponse::Unhandled;
  24102. });
  24103. svr.Get("/http", [](const Request &, Response &res) {
  24104. res.set_content("http", "text/plain");
  24105. });
  24106. svr.WebSocket("/ws",
  24107. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24108. auto port = svr.bind_to_any_port("localhost");
  24109. std::thread t([&]() { svr.listen_after_bind(); });
  24110. auto se = detail::scope_exit([&] {
  24111. svr.stop();
  24112. t.join();
  24113. });
  24114. svr.wait_until_ready();
  24115. Headers upgrade = {{"Upgrade", "websocket"},
  24116. {"Connection", "Upgrade"},
  24117. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24118. {"Sec-WebSocket-Version", "13"}};
  24119. auto get = [&](const char *path) {
  24120. pre_routing_calls = 0;
  24121. return Client("localhost", port).Get(path, upgrade);
  24122. };
  24123. // No WebSocket route, but an HTTP one
  24124. auto res = get("/http");
  24125. ASSERT_TRUE(res);
  24126. EXPECT_EQ(StatusCode::OK_200, res->status);
  24127. EXPECT_EQ("http", res->body);
  24128. EXPECT_EQ(1, pre_routing_calls);
  24129. EXPECT_EQ(1, pre_request_calls);
  24130. // No route at all
  24131. res = get("/none");
  24132. ASSERT_TRUE(res);
  24133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24134. EXPECT_EQ(1, pre_routing_calls);
  24135. // Answered by the pre-routing handler
  24136. res = get("/handled");
  24137. ASSERT_TRUE(res);
  24138. EXPECT_EQ(StatusCode::OK_200, res->status);
  24139. EXPECT_EQ("handled", res->body);
  24140. EXPECT_EQ(1, pre_routing_calls);
  24141. // A WebSocket route
  24142. pre_routing_calls = 0;
  24143. pre_request_calls = 0;
  24144. {
  24145. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24146. "/ws");
  24147. ASSERT_TRUE(client.connect());
  24148. std::string msg;
  24149. ASSERT_TRUE(client.read(msg));
  24150. EXPECT_EQ("ws", msg);
  24151. client.close();
  24152. }
  24153. EXPECT_EQ(1, pre_routing_calls);
  24154. EXPECT_EQ(1, pre_request_calls);
  24155. }
  24156. // An upgrade request answered by a hook leaves its body unread, so that body
  24157. // must not be served as the next request on the connection.
  24158. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24159. Server svr;
  24160. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24161. if (req.path == "/pre-routing") {
  24162. res.set_content("pre-routing", "text/plain");
  24163. return Server::HandlerResponse::Handled;
  24164. }
  24165. return Server::HandlerResponse::Unhandled;
  24166. });
  24167. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24168. if (req.matched_route == "/pre-request") {
  24169. res.set_content("pre-request", "text/plain");
  24170. return Server::HandlerResponse::Handled;
  24171. }
  24172. return Server::HandlerResponse::Unhandled;
  24173. });
  24174. svr.Get("/smuggled", [](const Request &, Response &res) {
  24175. res.set_content("smuggled", "text/plain");
  24176. });
  24177. svr.WebSocket("/pre-request",
  24178. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24179. auto port = svr.bind_to_any_port(HOST);
  24180. std::thread t([&]() { svr.listen_after_bind(); });
  24181. auto se = detail::scope_exit([&] {
  24182. svr.stop();
  24183. t.join();
  24184. });
  24185. svr.wait_until_ready();
  24186. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24187. for (auto path : {"/pre-routing", "/pre-request"}) {
  24188. std::string req = std::string("GET ") + path +
  24189. " HTTP/1.1\r\n"
  24190. "Host: localhost\r\n"
  24191. "Upgrade: websocket\r\n"
  24192. "Connection: Upgrade\r\n"
  24193. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24194. "Sec-WebSocket-Version: 13\r\n"
  24195. "Content-Length: " +
  24196. std::to_string(body.size()) + "\r\n\r\n" + body;
  24197. std::string res;
  24198. ASSERT_TRUE(send_request(5, req, &res, port));
  24199. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24200. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24201. // Only one response, and the body was not served as a request
  24202. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24203. }
  24204. }
  24205. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24206. Server svr;
  24207. std::atomic<int> pre_request_calls{0};
  24208. std::atomic<bool> route_matched{false};
  24209. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24210. pre_request_calls++;
  24211. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24212. if (req.get_header_value("Authorization") != "Bearer token123") {
  24213. res.status = StatusCode::Unauthorized_401;
  24214. res.set_content("Unauthorized", "text/plain");
  24215. return Server::HandlerResponse::Handled;
  24216. }
  24217. return Server::HandlerResponse::Unhandled;
  24218. });
  24219. std::atomic<bool> handler_called{false};
  24220. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24221. handler_called = true;
  24222. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24223. });
  24224. auto port = svr.bind_to_any_port("localhost");
  24225. std::thread t([&]() { svr.listen_after_bind(); });
  24226. svr.wait_until_ready();
  24227. // Without Authorization header - should be rejected before upgrade
  24228. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24229. "/ws/1");
  24230. EXPECT_FALSE(client1.connect());
  24231. EXPECT_FALSE(handler_called);
  24232. EXPECT_EQ(1, pre_request_calls);
  24233. EXPECT_TRUE(route_matched);
  24234. // The rejection is an ordinary HTTP response, not a protocol switch
  24235. {
  24236. Client cli("localhost", port);
  24237. Headers headers = {{"Upgrade", "websocket"},
  24238. {"Connection", "Upgrade"},
  24239. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24240. {"Sec-WebSocket-Version", "13"}};
  24241. auto res = cli.Get("/ws/1", headers);
  24242. ASSERT_TRUE(res);
  24243. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24244. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24245. EXPECT_EQ("Unauthorized", res->body);
  24246. }
  24247. EXPECT_FALSE(handler_called);
  24248. // With Authorization header - should succeed
  24249. Headers headers = {{"Authorization", "Bearer token123"}};
  24250. ws::WebSocketClient client2(
  24251. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24252. ASSERT_TRUE(client2.connect());
  24253. std::string msg;
  24254. ASSERT_TRUE(client2.read(msg));
  24255. EXPECT_EQ("/ws/:id 2", msg);
  24256. EXPECT_TRUE(handler_called);
  24257. client2.close();
  24258. svr.stop();
  24259. t.join();
  24260. }
  24261. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24262. static Headers websocket_upgrade_headers() {
  24263. return {{"Upgrade", "websocket"},
  24264. {"Connection", "Upgrade"},
  24265. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24266. {"Sec-WebSocket-Version", "13"},
  24267. {"Sec-WebSocket-Protocol", "chat"}};
  24268. }
  24269. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24270. Server svr;
  24271. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24272. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24273. return Server::HandlerResponse::Unhandled;
  24274. });
  24275. svr.set_pre_request_handler([](const Request &req, Response &) {
  24276. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24277. return Server::HandlerResponse::Unhandled;
  24278. });
  24279. svr.set_exception_handler(
  24280. [](const Request &, Response &res, std::exception_ptr ep) {
  24281. try {
  24282. std::rethrow_exception(ep);
  24283. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24284. });
  24285. auto handler = [](const Request &, ws::WebSocket &) {};
  24286. svr.WebSocket("/pre-routing", handler);
  24287. svr.WebSocket("/pre-request", handler);
  24288. svr.WebSocket("/sub-protocol", handler,
  24289. [](const std::vector<std::string> &) -> std::string {
  24290. throw std::runtime_error("/sub-protocol");
  24291. });
  24292. auto port = svr.bind_to_any_port(HOST);
  24293. ASSERT_GT(port, 0);
  24294. thread t = thread([&] { svr.listen_after_bind(); });
  24295. auto se = detail::scope_exit([&] {
  24296. svr.stop();
  24297. t.join();
  24298. ASSERT_FALSE(svr.is_running());
  24299. });
  24300. svr.wait_until_ready();
  24301. Client cli(HOST, port);
  24302. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24303. auto res = cli.Get(path, websocket_upgrade_headers());
  24304. if (!res) {
  24305. ADD_FAILURE() << path << ": " << to_string(res.error());
  24306. continue;
  24307. }
  24308. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24309. EXPECT_EQ(path, res->body);
  24310. }
  24311. }
  24312. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24313. Server svr;
  24314. svr.set_pre_routing_handler(
  24315. [](const Request &, Response &) -> Server::HandlerResponse {
  24316. throw std::runtime_error("pre-routing");
  24317. });
  24318. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24319. auto port = svr.bind_to_any_port(HOST);
  24320. ASSERT_GT(port, 0);
  24321. thread t = thread([&] { svr.listen_after_bind(); });
  24322. auto se = detail::scope_exit([&] {
  24323. svr.stop();
  24324. t.join();
  24325. ASSERT_FALSE(svr.is_running());
  24326. });
  24327. svr.wait_until_ready();
  24328. Client cli(HOST, port);
  24329. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24330. ASSERT_TRUE(res) << to_string(res.error());
  24331. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24332. }
  24333. #endif
  24334. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24335. Server svr;
  24336. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24337. // A read timeout is how a handler gets control back. Without it, a handler
  24338. // parked in read() can never write on the connection it is reading.
  24339. ws.set_read_timeout(std::chrono::milliseconds(100));
  24340. std::string msg;
  24341. while (ws.is_open()) {
  24342. auto r = ws.read(msg);
  24343. if (r == httplib::ws::Timeout) {
  24344. ws.send("tick");
  24345. continue;
  24346. }
  24347. if (r == httplib::ws::Fail) { break; }
  24348. ws.send(msg);
  24349. }
  24350. });
  24351. auto port = svr.bind_to_any_port("localhost");
  24352. std::thread t([&]() { svr.listen_after_bind(); });
  24353. svr.wait_until_ready();
  24354. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24355. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24356. ASSERT_TRUE(client.connect());
  24357. // The client sends nothing, so anything it receives came out of the
  24358. // handler's timeout path.
  24359. std::string msg;
  24360. ASSERT_EQ(client.read(msg), ws::Text);
  24361. EXPECT_EQ("tick", msg);
  24362. client.close();
  24363. svr.stop();
  24364. t.join();
  24365. }
  24366. // Stream::read may return fewer bytes than asked for. This is that contract at
  24367. // its worst -- one byte per call -- which is what a frame header straddling a
  24368. // read buffer's boundary looks like to the frame parser.
  24369. class WsByteAtATimeStream : public Stream {
  24370. public:
  24371. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24372. bool is_readable() const override { return true; }
  24373. bool wait_readable() const override { return true; }
  24374. bool wait_writable() const override { return true; }
  24375. ssize_t read(char *ptr, size_t size) override {
  24376. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24377. *ptr = data_[pos_++];
  24378. return 1;
  24379. }
  24380. ssize_t write(const char *, size_t size) override {
  24381. return static_cast<ssize_t>(size);
  24382. }
  24383. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24384. ip = "127.0.0.1";
  24385. port = 0;
  24386. }
  24387. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24388. ip = "127.0.0.1";
  24389. port = 0;
  24390. }
  24391. socket_t socket() const override { return INVALID_SOCKET; }
  24392. time_t duration() const override { return 0; }
  24393. private:
  24394. std::string data_;
  24395. size_t pos_ = 0;
  24396. };
  24397. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24398. // The payload uses the 16-bit extended length, so the header, the length
  24399. // and the mask key are all multi-byte fields here. Each used to be read
  24400. // with a single read() call, which fails as soon as one is split. The
  24401. // payload is also a little over one read chunk, so it is read in two.
  24402. std::string body;
  24403. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24404. body += static_cast<char>(i % 251);
  24405. }
  24406. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24407. std::string frame;
  24408. frame += static_cast<char>(0x81); // FIN + Text
  24409. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24410. frame += static_cast<char>(body.size() >> 8);
  24411. frame += static_cast<char>(body.size() & 0xff);
  24412. for (size_t i = 0; i < 4; i++) {
  24413. frame += static_cast<char>(mask[i]);
  24414. }
  24415. for (size_t i = 0; i < body.size(); i++) {
  24416. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24417. }
  24418. WsByteAtATimeStream strm(frame);
  24419. ws::Opcode opcode;
  24420. std::string payload;
  24421. bool fin = false;
  24422. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24423. /*expect_masked=*/true, body.size()),
  24424. ws::impl::FrameRead::Ok);
  24425. EXPECT_TRUE(fin);
  24426. EXPECT_EQ(opcode, ws::Opcode::Text);
  24427. EXPECT_EQ(payload, body);
  24428. }
  24429. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24430. std::string body(2000, 'x');
  24431. std::string frame;
  24432. frame += static_cast<char>(0x82); // FIN + Binary
  24433. frame += static_cast<char>(126); // 16-bit length follows
  24434. frame += static_cast<char>(body.size() >> 8);
  24435. frame += static_cast<char>(body.size() & 0xff);
  24436. frame += body;
  24437. detail::BufferStream strm;
  24438. strm.write(frame.data(), frame.size());
  24439. ws::Opcode opcode;
  24440. std::string payload;
  24441. bool fin;
  24442. EXPECT_EQ(
  24443. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24444. ws::impl::FrameRead::Ok);
  24445. EXPECT_EQ(body, payload);
  24446. }
  24447. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24448. // The header announces the largest payload allowed, and only 3 bytes of it
  24449. // ever arrive.
  24450. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24451. std::string frame;
  24452. frame += static_cast<char>(0x82); // FIN + Binary
  24453. frame += static_cast<char>(127); // 64-bit length follows
  24454. for (int shift = 56; shift >= 0; shift -= 8) {
  24455. frame += static_cast<char>((len >> shift) & 0xff);
  24456. }
  24457. frame += "abc";
  24458. detail::BufferStream strm;
  24459. strm.write(frame.data(), frame.size());
  24460. ws::Opcode opcode;
  24461. std::string payload;
  24462. bool fin;
  24463. EXPECT_EQ(
  24464. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24465. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24466. ws::impl::FrameRead::Fail);
  24467. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24468. }
  24469. TEST(WebSocketTest, QueryStringInHandshake) {
  24470. Server svr;
  24471. std::mutex mtx;
  24472. std::string received_target;
  24473. std::string received_token;
  24474. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24475. {
  24476. std::lock_guard<std::mutex> lock(mtx);
  24477. received_target = req.target;
  24478. if (req.has_param("token")) {
  24479. received_token = req.get_param_value("token");
  24480. }
  24481. }
  24482. std::string msg;
  24483. while (ws.read(msg)) {
  24484. ws.send(msg);
  24485. }
  24486. });
  24487. auto port = svr.bind_to_any_port("localhost");
  24488. std::thread t([&]() { svr.listen_after_bind(); });
  24489. svr.wait_until_ready();
  24490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24491. "/ws?token=ABC&session=123");
  24492. ASSERT_TRUE(client.connect());
  24493. // Round-trip ensures the handler has run and captured the request.
  24494. ASSERT_TRUE(client.send("hello"));
  24495. std::string msg;
  24496. ASSERT_TRUE(client.read(msg));
  24497. EXPECT_EQ("hello", msg);
  24498. client.close();
  24499. {
  24500. std::lock_guard<std::mutex> lock(mtx);
  24501. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24502. EXPECT_EQ("ABC", received_token);
  24503. }
  24504. svr.stop();
  24505. t.join();
  24506. }
  24507. // Run a handshake against a throwaway server and hand the request the server
  24508. // received back to the caller, so tests can assert on the headers the client
  24509. // actually put on the wire.
  24510. static void capture_websocket_handshake_request(
  24511. const Headers &client_headers,
  24512. std::function<void(const Request &, int port)> verify) {
  24513. Server svr;
  24514. std::mutex mtx;
  24515. Request received;
  24516. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24517. {
  24518. std::lock_guard<std::mutex> lock(mtx);
  24519. received = req;
  24520. }
  24521. std::string msg;
  24522. while (ws.read(msg)) {
  24523. ws.send(msg);
  24524. }
  24525. });
  24526. auto port = svr.bind_to_any_port("localhost");
  24527. std::thread t([&]() { svr.listen_after_bind(); });
  24528. auto se = detail::scope_exit([&] {
  24529. svr.stop();
  24530. t.join();
  24531. });
  24532. svr.wait_until_ready();
  24533. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24534. client_headers);
  24535. ASSERT_TRUE(client.connect());
  24536. ASSERT_TRUE(client.send("hello"));
  24537. std::string msg;
  24538. ASSERT_TRUE(client.read(msg));
  24539. client.close();
  24540. {
  24541. std::lock_guard<std::mutex> lock(mtx);
  24542. verify(received, port);
  24543. }
  24544. }
  24545. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24546. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24547. // Non-default port must be present in the Host header. Default ports
  24548. // (80/443) are omitted; that logic is covered by
  24549. // MakeHostAndPortStringTest.
  24550. EXPECT_EQ("localhost:" + std::to_string(port),
  24551. req.get_header_value("Host"));
  24552. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24553. req.get_header_value("User-Agent"));
  24554. EXPECT_FALSE(req.has_header("Accept"));
  24555. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24556. EXPECT_FALSE(req.has_header("Content-Length"));
  24557. });
  24558. }
  24559. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24560. capture_websocket_handshake_request(
  24561. {{"Host", "example.com"},
  24562. {"User-Agent", "custom-agent"},
  24563. {"X-Custom", "value"}},
  24564. [](const Request &req, int) {
  24565. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24566. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24567. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24568. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24569. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24570. });
  24571. }
  24572. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24573. capture_websocket_handshake_request(
  24574. {{"Upgrade", "bogus"},
  24575. {"Connection", "close"},
  24576. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24577. {"Sec-WebSocket-Version", "8"}},
  24578. [](const Request &req, int) {
  24579. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24580. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24581. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24582. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24583. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24584. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24585. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24586. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24587. req.get_header_value("Sec-WebSocket-Key"));
  24588. });
  24589. }
  24590. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24591. // A header the client refuses to send must abort the handshake before any
  24592. // part of it reaches the wire; a lone request line would otherwise sit in
  24593. // the peer's buffer as a truncated request.
  24594. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24595. ASSERT_NE(INVALID_SOCKET, srv);
  24596. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24597. sockaddr_in addr{};
  24598. addr.sin_family = AF_INET;
  24599. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24600. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24601. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24602. ASSERT_EQ(0, ::listen(srv, 1));
  24603. sockaddr_in bound{};
  24604. socklen_t bound_len = sizeof(bound);
  24605. ASSERT_EQ(
  24606. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24607. auto port = ntohs(bound.sin_port);
  24608. ssize_t received = -1;
  24609. std::thread t([&] {
  24610. // Bound every blocking call so a regression fails the test with a bad
  24611. // value instead of hanging the suite.
  24612. fd_set rfds;
  24613. FD_ZERO(&rfds);
  24614. FD_SET(srv, &rfds);
  24615. timeval tv{5, 0};
  24616. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24617. 0) {
  24618. return;
  24619. }
  24620. sockaddr_in cli_addr{};
  24621. socklen_t cli_len = sizeof(cli_addr);
  24622. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24623. if (cli == INVALID_SOCKET) { return; }
  24624. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24625. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24626. char buf[4096];
  24627. received = ::recv(cli, buf, sizeof(buf), 0);
  24628. });
  24629. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24630. // connect() has already shut the socket down by the time it returns false,
  24631. // so the peer sees EOF without waiting for the client to be destroyed.
  24632. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24633. {{"X-Bad", "a\r\nInjected: 1"}});
  24634. EXPECT_FALSE(client.connect());
  24635. t.join();
  24636. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24637. EXPECT_EQ(0, received);
  24638. }
  24639. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24640. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24641. // contains "upgrade" as a substring is a different token and must not
  24642. // start a WebSocket handshake.
  24643. auto make_request = [](const std::vector<std::string> &connection_values) {
  24644. Request req;
  24645. req.method = "GET";
  24646. req.headers.emplace("Upgrade", "websocket");
  24647. for (const auto &value : connection_values) {
  24648. req.headers.emplace("Connection", value);
  24649. }
  24650. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24651. req.headers.emplace("Sec-WebSocket-Version", "13");
  24652. return req;
  24653. };
  24654. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24655. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24656. EXPECT_TRUE(
  24657. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24658. EXPECT_TRUE(
  24659. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24660. EXPECT_TRUE(
  24661. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24662. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24663. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24664. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24665. EXPECT_FALSE(
  24666. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24667. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24668. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24669. }
  24670. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24671. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24672. // asks recipients to match each protocol-name case-insensitively, and RFC
  24673. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24674. // client naming websocket alongside another protocol, or on a second field
  24675. // line, is offering websocket; a value that merely contains "websocket" as a
  24676. // substring is a different protocol name and is not.
  24677. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24678. Request req;
  24679. req.method = "GET";
  24680. for (const auto &value : upgrade_values) {
  24681. req.headers.emplace("Upgrade", value);
  24682. }
  24683. req.headers.emplace("Connection", "Upgrade");
  24684. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24685. req.headers.emplace("Sec-WebSocket-Version", "13");
  24686. return req;
  24687. };
  24688. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24689. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24690. EXPECT_TRUE(
  24691. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24692. EXPECT_TRUE(
  24693. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24694. EXPECT_TRUE(
  24695. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24696. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24697. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24698. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24699. EXPECT_FALSE(
  24700. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24701. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24702. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24703. }
  24704. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24705. Server svr;
  24706. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24707. auto port = svr.bind_to_any_port("localhost");
  24708. std::thread t([&]() { svr.listen_after_bind(); });
  24709. auto se = detail::scope_exit([&] {
  24710. svr.stop();
  24711. t.join();
  24712. });
  24713. svr.wait_until_ready();
  24714. Headers headers = {{"Upgrade", "websocket"},
  24715. {"Connection", "notupgrade"},
  24716. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24717. {"Sec-WebSocket-Version", "13"}};
  24718. Client cli("localhost", port);
  24719. auto res = cli.Get("/ws", headers);
  24720. // The route exists only as a WebSocket route, so a request that fails the
  24721. // handshake check falls through to ordinary routing.
  24722. ASSERT_TRUE(res);
  24723. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24724. }
  24725. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24726. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24727. // Connection value is the only thing left for the client to reject.
  24728. Server svr;
  24729. svr.Get("/ws", [](const Request &req, Response &res) {
  24730. res.status = StatusCode::SwitchingProtocol_101;
  24731. res.set_header("Upgrade", "websocket");
  24732. res.set_header("Connection", "notupgrade");
  24733. res.set_header("Sec-WebSocket-Accept",
  24734. detail::websocket_accept_key(
  24735. req.get_header_value("Sec-WebSocket-Key")));
  24736. });
  24737. auto port = svr.bind_to_any_port("localhost");
  24738. std::thread t([&]() { svr.listen_after_bind(); });
  24739. auto se = detail::scope_exit([&] {
  24740. svr.stop();
  24741. t.join();
  24742. });
  24743. svr.wait_until_ready();
  24744. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24745. auto res = client.connect();
  24746. EXPECT_FALSE(res);
  24747. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24748. EXPECT_FALSE(client.is_open());
  24749. }
  24750. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24751. Server svr;
  24752. svr.Get("/ws", [](const Request &req, Response &res) {
  24753. res.status = StatusCode::SwitchingProtocol_101;
  24754. res.set_header("Upgrade", "websocket");
  24755. res.set_header("Connection", "Upgrade");
  24756. res.set_header("Sec-WebSocket-Accept",
  24757. detail::websocket_accept_key(
  24758. req.get_header_value("Sec-WebSocket-Key")));
  24759. res.set_header("Sec-WebSocket-Protocol", "admin");
  24760. });
  24761. auto port = svr.bind_to_any_port("localhost");
  24762. std::thread t([&]() { svr.listen_after_bind(); });
  24763. auto se = detail::scope_exit([&] {
  24764. svr.stop();
  24765. t.join();
  24766. });
  24767. svr.wait_until_ready();
  24768. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24769. // Server selects a subprotocol the client never offered
  24770. {
  24771. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24772. ws::WebSocketClient client(url, headers);
  24773. auto res = client.connect();
  24774. EXPECT_FALSE(res);
  24775. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24776. EXPECT_FALSE(client.is_open());
  24777. EXPECT_TRUE(client.subprotocol().empty());
  24778. }
  24779. // Client offered none but the server named one anyway
  24780. {
  24781. ws::WebSocketClient client(url);
  24782. auto res = client.connect();
  24783. EXPECT_FALSE(res);
  24784. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24785. EXPECT_FALSE(client.is_open());
  24786. EXPECT_TRUE(client.subprotocol().empty());
  24787. }
  24788. }
  24789. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24790. // The socket path doubles as the URL host, so it must not contain '/'.
  24791. const char *shard = getenv("GTEST_SHARD_INDEX");
  24792. const std::string sock_path =
  24793. shard ? std::string("httplib-ws-") + shard + ".sock"
  24794. : std::string("httplib-ws.sock");
  24795. std::remove(sock_path.c_str());
  24796. Server svr;
  24797. std::mutex mtx;
  24798. std::string received_host;
  24799. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24800. {
  24801. std::lock_guard<std::mutex> lock(mtx);
  24802. received_host = req.get_header_value("Host");
  24803. }
  24804. std::string msg;
  24805. while (ws.read(msg)) {
  24806. ws.send(msg);
  24807. }
  24808. });
  24809. svr.set_address_family(AF_UNIX);
  24810. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24811. auto se = detail::scope_exit([&] {
  24812. svr.stop();
  24813. t.join();
  24814. std::remove(sock_path.c_str());
  24815. });
  24816. svr.wait_until_ready();
  24817. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24818. client.set_address_family(AF_UNIX);
  24819. ASSERT_TRUE(client.connect());
  24820. ASSERT_TRUE(client.send("hello"));
  24821. std::string msg;
  24822. ASSERT_TRUE(client.read(msg));
  24823. client.close();
  24824. {
  24825. std::lock_guard<std::mutex> lock(mtx);
  24826. // There is no host:port for a Unix socket, so the same "localhost"
  24827. // placeholder the HTTP client uses is expected.
  24828. EXPECT_EQ("localhost", received_host);
  24829. }
  24830. }
  24831. // Two threads must never parse WebSocket frames from the same stream.
  24832. // close() used to read the peer's Close reply with its own frame read, so it
  24833. // raced a reader thread that was in the middle of a payload: the payload loop
  24834. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24835. // so bytes taken by close() were replaced with bytes from further along the
  24836. // stream. The message kept its length and silently changed content.
  24837. //
  24838. // The raw peer below sends a frame header plus part of the payload, waits for
  24839. // the handler to call close(), and only then sends the rest. Whichever thread
  24840. // would win the race for those bytes, the message must arrive intact, because
  24841. // close() must not touch the stream while read() owns it.
  24842. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24843. #ifndef _WIN32
  24844. signal(SIGPIPE, SIG_IGN);
  24845. #endif
  24846. const size_t payload_len = 120; // fits the 7-bit length field
  24847. const size_t prefix_len = 8;
  24848. const int attempts = 8;
  24849. std::string expected(payload_len, '\0');
  24850. for (size_t i = 0; i < payload_len; i++) {
  24851. expected[i] = static_cast<char>('a' + i % 26);
  24852. }
  24853. std::atomic<bool> peer_stalled{false};
  24854. std::atomic<bool> handler_done{false};
  24855. std::mutex received_mutex;
  24856. std::vector<std::string> received;
  24857. // Bound every wait, so a regression fails the test instead of hanging the
  24858. // suite.
  24859. auto wait_for = [](const std::atomic<bool> &flag) {
  24860. for (int i = 0; i < 500 && !flag; i++) {
  24861. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24862. }
  24863. };
  24864. Server svr;
  24865. svr.set_websocket_ping_interval(0);
  24866. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24867. std::thread reader([&]() {
  24868. std::string msg;
  24869. while (ws.read(msg)) {
  24870. std::lock_guard<std::mutex> guard(received_mutex);
  24871. received.push_back(msg);
  24872. }
  24873. });
  24874. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24875. // inside read_websocket_frame() when close() runs.
  24876. wait_for(peer_stalled);
  24877. ws.close();
  24878. reader.join();
  24879. handler_done = true;
  24880. });
  24881. auto port = svr.bind_to_any_port("127.0.0.1");
  24882. std::thread t([&]() { svr.listen_after_bind(); });
  24883. auto se = detail::scope_exit([&] {
  24884. svr.stop();
  24885. t.join();
  24886. });
  24887. svr.wait_until_ready();
  24888. auto send_bytes = [](socket_t s, const std::string &data) {
  24889. #ifdef _WIN32
  24890. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24891. #else
  24892. auto n = ::send(s, data.data(), data.size(), 0);
  24893. #endif
  24894. return n == static_cast<decltype(n)>(data.size());
  24895. };
  24896. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24897. // Every length used here fits the 7-bit length field.
  24898. auto masked_header = [](uint8_t first_byte, size_t len) {
  24899. std::string h;
  24900. h += static_cast<char>(first_byte);
  24901. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24902. h.append(4, '\0'); // mask key
  24903. return h;
  24904. };
  24905. for (int attempt = 0; attempt < attempts; attempt++) {
  24906. peer_stalled = false;
  24907. handler_done = false;
  24908. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24909. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24910. auto se_sock = detail::scope_exit([&] {
  24911. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24912. });
  24913. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24914. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24915. sockaddr_in addr{};
  24916. addr.sin_family = AF_INET;
  24917. addr.sin_port = htons(static_cast<uint16_t>(port));
  24918. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24919. ASSERT_EQ(
  24920. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24921. << "attempt " << attempt;
  24922. ASSERT_TRUE(send_bytes(sock,
  24923. "GET /ws HTTP/1.1\r\n"
  24924. "Host: 127.0.0.1\r\n"
  24925. "Upgrade: websocket\r\n"
  24926. "Connection: Upgrade\r\n"
  24927. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24928. "Sec-WebSocket-Version: 13\r\n"
  24929. "\r\n"))
  24930. << "attempt " << attempt;
  24931. std::string response;
  24932. while (response.find("\r\n\r\n") == std::string::npos) {
  24933. char buf[512];
  24934. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24935. if (n <= 0) { break; }
  24936. response.append(buf, static_cast<size_t>(n));
  24937. }
  24938. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24939. << "attempt " << attempt;
  24940. // Send the header of a Binary message but only the first prefix_len bytes
  24941. // of its payload, leaving the reader thread stalled inside the payload.
  24942. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24943. expected.substr(0, prefix_len)))
  24944. << "attempt " << attempt;
  24945. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24946. peer_stalled = true;
  24947. // Let close() send its Close frame and park in its own read before the
  24948. // rest of the payload arrives, so both threads are waiting for it.
  24949. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24950. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24951. close_frame += static_cast<char>(0x03); // status 1000
  24952. close_frame += static_cast<char>(0xE8);
  24953. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24954. << "attempt " << attempt;
  24955. // Closing the peer releases the reader thread even on the buggy path,
  24956. // where it waits for bytes another thread already consumed.
  24957. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24958. detail::close_socket(sock);
  24959. sock = INVALID_SOCKET;
  24960. wait_for(handler_done);
  24961. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24962. }
  24963. std::lock_guard<std::mutex> guard(received_mutex);
  24964. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24965. << "a message in flight when close() ran was dropped";
  24966. for (size_t i = 0; i < received.size(); i++) {
  24967. EXPECT_EQ(expected, received[i]) << "message " << i;
  24968. }
  24969. }
  24970. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24971. // returning the socket, or INVALID_SOCKET.
  24972. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24973. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24974. if (sock == INVALID_SOCKET) { return sock; }
  24975. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24976. sockaddr_in addr{};
  24977. addr.sin_family = AF_INET;
  24978. addr.sin_port = htons(static_cast<uint16_t>(port));
  24979. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24980. std::string req = "GET " + path +
  24981. " HTTP/1.1\r\n"
  24982. "Host: 127.0.0.1\r\n"
  24983. "Upgrade: websocket\r\n"
  24984. "Connection: Upgrade\r\n"
  24985. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24986. "Sec-WebSocket-Version: 13\r\n"
  24987. "\r\n";
  24988. std::string res;
  24989. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24990. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24991. static_cast<ssize_t>(req.size())) {
  24992. char c;
  24993. while (res.find("\r\n\r\n") == std::string::npos &&
  24994. ::recv(sock, &c, 1, 0) == 1) {
  24995. res += c;
  24996. }
  24997. }
  24998. if (res.find(" 101 ") == std::string::npos) {
  24999. detail::close_socket(sock);
  25000. return INVALID_SOCKET;
  25001. }
  25002. return sock;
  25003. }
  25004. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25005. // The payload must fit the 7-bit length field.
  25006. static std::string masked_frame(uint8_t first_byte,
  25007. const std::string &payload) {
  25008. std::string f;
  25009. f += static_cast<char>(first_byte);
  25010. f += static_cast<char>(0x80 | payload.size());
  25011. f.append(4, '\0');
  25012. return f + payload;
  25013. }
  25014. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25015. std::atomic<bool> done{false};
  25016. std::string received;
  25017. Server svr;
  25018. svr.set_websocket_ping_interval(0);
  25019. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25020. std::string msg;
  25021. if (ws.read(msg) == ws::Binary) { received = msg; }
  25022. done = true;
  25023. });
  25024. auto port = svr.bind_to_any_port("127.0.0.1");
  25025. std::thread t([&]() { svr.listen_after_bind(); });
  25026. auto se = detail::scope_exit([&] {
  25027. svr.stop();
  25028. t.join();
  25029. });
  25030. svr.wait_until_ready();
  25031. auto sock = connect_raw_websocket(port, "/ws");
  25032. ASSERT_NE(INVALID_SOCKET, sock);
  25033. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25034. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25035. masked_frame(0x89, "p") + // FIN + Ping
  25036. masked_frame(0x80, "lo"); // FIN + Continuation
  25037. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25038. for (int i = 0; i < 500 && !done; i++) {
  25039. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25040. }
  25041. ASSERT_TRUE(done);
  25042. EXPECT_EQ("Hello", received);
  25043. // The Ping between the fragments is answered with a Pong.
  25044. char pong[3];
  25045. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25046. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25047. }
  25048. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25049. Server svr;
  25050. svr.set_websocket_ping_interval(-1);
  25051. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25052. std::string msg;
  25053. while (ws.read(msg)) {}
  25054. });
  25055. auto port = svr.bind_to_any_port("127.0.0.1");
  25056. std::thread t([&]() { svr.listen_after_bind(); });
  25057. auto se = detail::scope_exit([&] {
  25058. svr.stop();
  25059. t.join();
  25060. });
  25061. svr.wait_until_ready();
  25062. auto sock = connect_raw_websocket(port, "/ws");
  25063. ASSERT_NE(INVALID_SOCKET, sock);
  25064. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25065. // Nothing comes while the client stays quiet.
  25066. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25067. char c;
  25068. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25069. }
  25070. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25071. // and that has to end a read() already waiting on the peer, on every platform.
  25072. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25073. // The peer sends no pings, and its handler never calls read(), which is
  25074. // where pongs are written.
  25075. std::mutex mutex;
  25076. std::condition_variable cv;
  25077. auto release = false;
  25078. svr.set_websocket_ping_interval(0);
  25079. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25080. std::unique_lock<std::mutex> lock(mutex);
  25081. cv.wait(lock, [&] { return release; });
  25082. });
  25083. auto port = svr.bind_to_any_port(HOST);
  25084. std::thread t([&]() { svr.listen_after_bind(); });
  25085. auto se = detail::scope_exit([&] {
  25086. {
  25087. std::lock_guard<std::mutex> lock(mutex);
  25088. release = true;
  25089. }
  25090. cv.notify_all();
  25091. svr.stop();
  25092. t.join();
  25093. });
  25094. svr.wait_until_ready();
  25095. ws::WebSocketClient client(std::string(scheme) +
  25096. "://localhost:" + std::to_string(port) + "/ws");
  25097. #ifdef CPPHTTPLIB_SSL_ENABLED
  25098. client.enable_server_certificate_verification(false);
  25099. #endif
  25100. // A ping a second, given up on after two go unanswered: about 3s
  25101. client.set_websocket_ping_interval(1);
  25102. client.set_websocket_max_missed_pongs(2);
  25103. // Well past that, so that a read the timeout ends instead stands out
  25104. client.set_read_timeout(10);
  25105. ASSERT_TRUE(client.connect());
  25106. auto start = std::chrono::steady_clock::now();
  25107. std::string msg;
  25108. EXPECT_EQ(ws::Fail, client.read(msg));
  25109. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25110. std::chrono::steady_clock::now() - start)
  25111. .count(),
  25112. 6000);
  25113. EXPECT_FALSE(client.is_open());
  25114. }
  25115. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25116. Server svr;
  25117. check_pong_timeout_ends_read(svr, "ws");
  25118. }
  25119. #ifdef CPPHTTPLIB_SSL_ENABLED
  25120. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25122. ASSERT_TRUE(svr.is_valid());
  25123. check_pong_timeout_ends_read(svr, "wss");
  25124. }
  25125. #endif
  25126. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25127. Server svr;
  25128. svr.set_websocket_ping_interval(0);
  25129. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25130. std::string msg;
  25131. while (ws.read(msg)) {}
  25132. });
  25133. auto port = svr.bind_to_any_port("127.0.0.1");
  25134. std::thread t([&]() { svr.listen_after_bind(); });
  25135. auto se = detail::scope_exit([&] {
  25136. svr.stop();
  25137. t.join();
  25138. });
  25139. svr.wait_until_ready();
  25140. // Each Close payload and the reply it should get: an echo when valid, 1002
  25141. // otherwise.
  25142. std::vector<std::pair<std::string, std::string>> cases = {
  25143. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25144. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25145. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25146. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25147. };
  25148. // Also between the fragments of a message.
  25149. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25150. for (const auto &c : cases) {
  25151. auto sock = connect_raw_websocket(port, "/ws");
  25152. ASSERT_NE(INVALID_SOCKET, sock);
  25153. auto frames = prefix + masked_frame(0x88, c.first);
  25154. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25155. std::string reply;
  25156. char buf[256];
  25157. while (reply.size() < 2 + c.second.size()) {
  25158. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25159. if (n <= 0) { break; }
  25160. reply.append(buf, static_cast<size_t>(n));
  25161. }
  25162. detail::close_socket(sock);
  25163. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25164. c.second,
  25165. reply);
  25166. }
  25167. }
  25168. }
  25169. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25170. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25171. protected:
  25172. void SetUp() override {
  25173. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25174. SERVER_PRIVATE_KEY_FILE);
  25175. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25176. std::string msg;
  25177. ws::ReadResult ret;
  25178. while ((ret = ws.read(msg))) {
  25179. if (ret == ws::Binary) {
  25180. ws.send(msg.data(), msg.size());
  25181. } else {
  25182. ws.send(msg);
  25183. }
  25184. }
  25185. });
  25186. port_ = server_->bind_to_any_port(HOST);
  25187. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25188. server_->wait_until_ready();
  25189. }
  25190. void TearDown() override {
  25191. server_->stop();
  25192. if (server_thread_.joinable()) { server_thread_.join(); }
  25193. }
  25194. std::unique_ptr<SSLServer> server_;
  25195. std::thread server_thread_;
  25196. int port_ = 0;
  25197. };
  25198. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25199. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25200. {
  25201. ws::WebSocketClient client(url);
  25202. client.enable_server_certificate_verification(false);
  25203. auto calls = 0;
  25204. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25205. calls++;
  25206. return false;
  25207. });
  25208. EXPECT_FALSE(client.connect());
  25209. EXPECT_GT(calls, 0);
  25210. }
  25211. {
  25212. ws::WebSocketClient client(url);
  25213. client.enable_server_certificate_verification(false);
  25214. client.set_session_verifier([](tls::session_t) {
  25215. return SSLVerifierResponse::CertificateRejected;
  25216. });
  25217. EXPECT_FALSE(client.connect());
  25218. }
  25219. {
  25220. ws::WebSocketClient client(url);
  25221. client.enable_server_certificate_verification(false);
  25222. client.set_session_verifier([](tls::session_t) {
  25223. return SSLVerifierResponse::CertificateAccepted;
  25224. });
  25225. EXPECT_TRUE(client.connect());
  25226. }
  25227. }
  25228. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25229. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25230. "/ws-echo");
  25231. client.enable_server_certificate_verification(false);
  25232. ASSERT_TRUE(client.connect());
  25233. ASSERT_TRUE(client.is_open());
  25234. ASSERT_TRUE(client.send("Hello WSS"));
  25235. std::string msg;
  25236. EXPECT_EQ(ws::Text, client.read(msg));
  25237. EXPECT_EQ("Hello WSS", msg);
  25238. client.close();
  25239. }
  25240. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25241. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25242. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25243. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25244. // client (without calling close() first) is the only path that runs
  25245. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25246. // bug exactly.
  25247. //
  25248. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25249. // when linked against an instrumented libssl; run under Valgrind to catch it
  25250. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25251. // suite (the freed session otherwise stalls on the close handshake) — this test
  25252. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25253. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25254. {
  25255. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25256. "/ws-echo");
  25257. client.enable_server_certificate_verification(false);
  25258. client.set_read_timeout(2, 0);
  25259. client.set_write_timeout(2, 0);
  25260. ASSERT_TRUE(client.connect());
  25261. ASSERT_TRUE(client.is_open());
  25262. ASSERT_TRUE(client.send("still open"));
  25263. // Intentionally do NOT call client.close(): leaving scope runs
  25264. // shutdown_and_close() with the WebSocket still open, which must send the
  25265. // close frame while the TLS session is still alive.
  25266. }
  25267. }
  25268. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25269. // shutdown_and_close() at the start of connect(), reproducing the same
  25270. // use-after-free within the test body rather than at scope exit. The second
  25271. // connect must succeed and echo, proving the close handshake ran over a live
  25272. // session. See the note above about memory-tool requirements.
  25273. TEST_F(WebSocketSSLIntegrationTest,
  25274. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25275. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25276. "/ws-echo");
  25277. client.enable_server_certificate_verification(false);
  25278. client.set_read_timeout(2, 0);
  25279. client.set_write_timeout(2, 0);
  25280. ASSERT_TRUE(client.connect());
  25281. ASSERT_TRUE(client.is_open());
  25282. ASSERT_TRUE(client.send("still open"));
  25283. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25284. // the still-open connection, which must not touch a freed TLS session.
  25285. ASSERT_TRUE(client.connect());
  25286. ASSERT_TRUE(client.is_open());
  25287. ASSERT_TRUE(client.send("after reconnect"));
  25288. std::string msg;
  25289. EXPECT_EQ(ws::Text, client.read(msg));
  25290. EXPECT_EQ("after reconnect", msg);
  25291. client.close();
  25292. }
  25293. #endif
  25294. #ifdef CPPHTTPLIB_SSL_ENABLED
  25295. class WebSocketSSLCATest : public ::testing::Test {
  25296. protected:
  25297. void SetUp() override {
  25298. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25299. SERVER_PRIVATE_KEY_FILE);
  25300. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25301. std::string msg;
  25302. while (ws.read(msg)) {
  25303. ws.send(msg);
  25304. }
  25305. });
  25306. port_ = server_->bind_to_any_port("127.0.0.1");
  25307. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25308. server_->wait_until_ready();
  25309. }
  25310. void TearDown() override {
  25311. server_->stop();
  25312. if (server_thread_.joinable()) { server_thread_.join(); }
  25313. }
  25314. std::string url() const {
  25315. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25316. }
  25317. std::unique_ptr<SSLServer> server_;
  25318. std::thread server_thread_;
  25319. int port_ = 0;
  25320. };
  25321. // A custom CA loaded as PEM verifies the server with full certificate
  25322. // verification enabled
  25323. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25324. ws::WebSocketClient client(url());
  25325. std::string cert;
  25326. read_file(SERVER_CERT2_FILE, cert);
  25327. client.load_ca_cert_store(cert.c_str(), cert.size());
  25328. ASSERT_TRUE(client.connect());
  25329. ASSERT_TRUE(client.send("hello"));
  25330. std::string msg;
  25331. EXPECT_EQ(ws::Text, client.read(msg));
  25332. EXPECT_EQ("hello", msg);
  25333. client.close();
  25334. }
  25335. // A custom CA that does not cover the server must fail verification (the
  25336. // custom CA is exclusive; system certs are not loaded alongside it)
  25337. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25338. ws::WebSocketClient client(url());
  25339. std::string cert;
  25340. read_file(CLIENT_CA_CERT_FILE, cert);
  25341. client.load_ca_cert_store(cert.c_str(), cert.size());
  25342. auto res = client.connect();
  25343. ASSERT_FALSE(res);
  25344. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25345. EXPECT_EQ(-1, res.status());
  25346. EXPECT_NE(0u, res.ssl_backend_error());
  25347. }
  25348. // The same CA as a file path rather than PEM in memory
  25349. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25350. ws::WebSocketClient client(url());
  25351. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25352. ASSERT_TRUE(client.connect());
  25353. ASSERT_TRUE(client.send("hello"));
  25354. std::string msg;
  25355. EXPECT_EQ(ws::Text, client.read(msg));
  25356. EXPECT_EQ("hello", msg);
  25357. client.close();
  25358. }
  25359. // ...and a CA file that does not cover the server still fails, so it is the
  25360. // path above that decides the outcome
  25361. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25362. ws::WebSocketClient client(url());
  25363. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25364. ASSERT_FALSE(client.connect());
  25365. }
  25366. // Regression test: reconnecting with a native custom CA store used to reuse
  25367. // a store handle the previous TLS context had already freed (use-after-free
  25368. // under the OpenSSL backend). The context now lives as long as the client.
  25369. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25370. ws::WebSocketClient client(url());
  25371. std::string cert;
  25372. read_file(SERVER_CERT2_FILE, cert);
  25373. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25374. ASSERT_TRUE(client.connect());
  25375. client.close();
  25376. ASSERT_TRUE(client.connect());
  25377. ASSERT_TRUE(client.send("again"));
  25378. std::string msg;
  25379. EXPECT_EQ(ws::Text, client.read(msg));
  25380. EXPECT_EQ("again", msg);
  25381. client.close();
  25382. }
  25383. // Regression test: a certificate with a trusted chain but no identity match
  25384. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25385. // verification entirely for IP hosts, so this connection succeeded there.
  25386. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25387. // chain verification while the identity check must still fail.
  25388. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25389. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25390. ASSERT_TRUE(svr.is_valid());
  25391. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25392. std::string msg;
  25393. while (ws.read(msg)) {
  25394. ws.send(msg);
  25395. }
  25396. });
  25397. auto port = svr.bind_to_any_port("127.0.0.1");
  25398. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25399. auto se = detail::scope_exit([&] {
  25400. svr.stop();
  25401. t.join();
  25402. });
  25403. svr.wait_until_ready();
  25404. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25405. "/echo");
  25406. std::string cert;
  25407. read_file(SERVER_CERT_FILE, cert);
  25408. client.load_ca_cert_store(cert.c_str(), cert.size());
  25409. ASSERT_FALSE(client.connect());
  25410. }
  25411. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25412. // SNI, so nothing binds the host name to the TLS session. These bind the
  25413. // server to "localhost" instead, the only shape that exercises the SNI and
  25414. // hostname-verification path with certificate verification left enabled.
  25415. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25416. protected:
  25417. void Start(const char *cert_file) {
  25418. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25419. SERVER_PRIVATE_KEY_FILE);
  25420. ASSERT_TRUE(server_->is_valid());
  25421. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25422. std::string msg;
  25423. while (ws.read(msg)) {
  25424. ws.send(msg);
  25425. }
  25426. });
  25427. port_ = server_->bind_to_any_port("localhost");
  25428. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25429. server_->wait_until_ready();
  25430. }
  25431. void TearDown() override {
  25432. if (server_) { server_->stop(); }
  25433. if (server_thread_.joinable()) { server_thread_.join(); }
  25434. }
  25435. std::string url() const {
  25436. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25437. }
  25438. std::unique_ptr<SSLServer> server_;
  25439. std::thread server_thread_;
  25440. int port_ = 0;
  25441. };
  25442. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25443. // out and the connection is usable
  25444. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25445. Start(SERVER_CERT2_FILE);
  25446. ws::WebSocketClient client(url());
  25447. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25448. ASSERT_TRUE(client.connect());
  25449. ASSERT_TRUE(client.send("hello"));
  25450. std::string msg;
  25451. EXPECT_EQ(ws::Text, client.read(msg));
  25452. EXPECT_EQ("hello", msg);
  25453. client.close();
  25454. }
  25455. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25456. // while the identity check must still reject "localhost"
  25457. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25458. Start(SERVER_CERT_FILE);
  25459. ws::WebSocketClient client(url());
  25460. client.set_ca_cert_path(SERVER_CERT_FILE);
  25461. auto res = client.connect();
  25462. ASSERT_FALSE(res);
  25463. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25464. EXPECT_EQ(-1, res.status());
  25465. }
  25466. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25467. // disabled: the chain is still checked, only the identity check is skipped
  25468. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25469. Start(SERVER_CERT_FILE);
  25470. ws::WebSocketClient client(url());
  25471. client.set_ca_cert_path(SERVER_CERT_FILE);
  25472. client.enable_server_hostname_verification(false);
  25473. ASSERT_TRUE(client.connect());
  25474. ASSERT_TRUE(client.send("hello"));
  25475. std::string msg;
  25476. EXPECT_EQ(ws::Text, client.read(msg));
  25477. EXPECT_EQ("hello", msg);
  25478. client.close();
  25479. }
  25480. // A CA that did not sign the server certificate fails the chain, even though
  25481. // the name would match
  25482. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25483. Start(SERVER_CERT2_FILE);
  25484. ws::WebSocketClient client(url());
  25485. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25486. ASSERT_FALSE(client.connect());
  25487. }
  25488. // With verification disabled, neither the chain nor the name is checked
  25489. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25490. Start(SERVER_CERT_FILE);
  25491. ws::WebSocketClient client(url());
  25492. client.enable_server_certificate_verification(false);
  25493. ASSERT_TRUE(client.connect());
  25494. ASSERT_TRUE(client.send("hello"));
  25495. std::string msg;
  25496. EXPECT_EQ(ws::Text, client.read(msg));
  25497. EXPECT_EQ("hello", msg);
  25498. client.close();
  25499. }
  25500. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25501. protected:
  25502. void SetUp() override {
  25503. server_ = httplib::detail::make_unique<SSLServer>(
  25504. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25505. ASSERT_TRUE(server_->is_valid());
  25506. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25507. std::string msg;
  25508. while (ws.read(msg)) {
  25509. ws.send(msg);
  25510. }
  25511. });
  25512. port_ = server_->bind_to_any_port("localhost");
  25513. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25514. server_->wait_until_ready();
  25515. }
  25516. void TearDown() override {
  25517. server_->stop();
  25518. if (server_thread_.joinable()) { server_thread_.join(); }
  25519. }
  25520. std::string url() const {
  25521. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25522. }
  25523. void ConnectWithClientCert(const std::string &client_cert_file,
  25524. const std::string &client_private_key_file,
  25525. const char *private_key_password) {
  25526. std::string cert_pem, key_pem;
  25527. read_file(client_cert_file, cert_pem);
  25528. read_file(client_private_key_file, key_pem);
  25529. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25530. key_pem.c_str(), key_pem.size(),
  25531. private_key_password};
  25532. ConnectWithPem(pem);
  25533. }
  25534. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25535. ws::WebSocketClient client(url(), pem);
  25536. ASSERT_TRUE(client.is_valid());
  25537. client.enable_server_certificate_verification(false);
  25538. ASSERT_TRUE(client.connect());
  25539. ASSERT_TRUE(client.send("hello"));
  25540. std::string msg;
  25541. EXPECT_EQ(ws::Text, client.read(msg));
  25542. EXPECT_EQ("hello", msg);
  25543. client.close();
  25544. }
  25545. std::unique_ptr<SSLServer> server_;
  25546. std::thread server_thread_;
  25547. int port_ = 0;
  25548. };
  25549. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25550. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25551. }
  25552. // Control for the tests above: the fixture's server really does require a
  25553. // client certificate, so it is the PEM the constructor installed that decides
  25554. // the outcome.
  25555. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25556. ws::WebSocketClient client(url());
  25557. ASSERT_TRUE(client.is_valid());
  25558. client.enable_server_certificate_verification(false);
  25559. EXPECT_FALSE(client.connect());
  25560. }
  25561. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25562. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25563. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25564. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25565. }
  25566. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25567. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25568. std::string cert_pem, key_pem;
  25569. read_file(CLIENT_CERT_FILE, cert_pem);
  25570. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25571. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25572. std::vector<char> key(key_pem.begin(), key_pem.end());
  25573. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25574. key.size(), nullptr};
  25575. ConnectWithPem(pem);
  25576. }
  25577. #endif
  25578. #if !defined(_WIN32)
  25579. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25580. auto secret_dir = std::string("./symlink_test_secret");
  25581. auto served_dir = std::string("./symlink_test_served");
  25582. auto secret_file = secret_dir + "/secret.txt";
  25583. auto symlink_path = served_dir + "/escape";
  25584. // Setup: create directories and files
  25585. mkdir(secret_dir.c_str(), 0755);
  25586. mkdir(served_dir.c_str(), 0755);
  25587. {
  25588. std::ofstream ofs(secret_file);
  25589. ofs << "SECRET_DATA";
  25590. }
  25591. // Create symlink using absolute path so it resolves correctly
  25592. #ifdef PATH_MAX
  25593. char abs_secret[PATH_MAX];
  25594. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25595. #else
  25596. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25597. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25598. ASSERT_NE(nullptr, abs_secret);
  25599. #endif
  25600. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25601. auto se = detail::scope_exit([&] {
  25602. unlink(symlink_path.c_str());
  25603. unlink(secret_file.c_str());
  25604. rmdir(served_dir.c_str());
  25605. rmdir(secret_dir.c_str());
  25606. });
  25607. Server svr;
  25608. svr.set_mount_point("/", served_dir);
  25609. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25610. auto se2 = detail::scope_exit([&] {
  25611. svr.stop();
  25612. listen_thread.join();
  25613. });
  25614. svr.wait_until_ready();
  25615. Client cli("localhost", PORT);
  25616. // Symlink pointing outside base dir should be blocked
  25617. auto res = cli.Get("/escape/secret.txt");
  25618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25619. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25620. }
  25621. #endif
  25622. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25623. // "GET /smuggled" request), reads the first response, and only then sends the
  25624. // embedded request as the body. Returns how many times /smuggled ran.
  25625. //
  25626. // The body is sent AFTER receiving the first response (as in the original
  25627. // PoC) so that the stream_line_reader cannot buffer it together with the
  25628. // headers of the first request.
  25629. static int count_smuggled_requests(const std::string &outer_head,
  25630. std::string &first_response) {
  25631. Server svr;
  25632. svr.set_mount_point("/", "./www");
  25633. std::atomic<int> smuggled_count(0);
  25634. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25635. smuggled_count++;
  25636. res.set_content("oops", "text/plain");
  25637. });
  25638. svr.Post("/post", [&](const Request &req, Response &res) {
  25639. res.set_content(req.body, "text/plain");
  25640. });
  25641. auto port = svr.bind_to_any_port("localhost");
  25642. thread t = thread([&] { svr.listen_after_bind(); });
  25643. auto se = detail::scope_exit([&] {
  25644. svr.stop();
  25645. t.join();
  25646. });
  25647. svr.wait_until_ready();
  25648. auto error = Error::Success;
  25649. auto sock = detail::create_client_socket(
  25650. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25651. /*connection_timeout_sec=*/2, 0,
  25652. /*read_timeout_sec=*/2, 0,
  25653. /*write_timeout_sec=*/2, 0, std::string(), error);
  25654. EXPECT_NE(INVALID_SOCKET, sock);
  25655. if (sock == INVALID_SOCKET) { return -1; }
  25656. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25657. // The "smuggled" request will be sent as the body of the outer request
  25658. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25659. "Host: localhost\r\n"
  25660. "Connection: close\r\n"
  25661. "\r\n";
  25662. auto head = outer_head;
  25663. auto len = std::to_string(smuggled.size());
  25664. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25665. pos = head.find("{len}", pos + len.size())) {
  25666. head.replace(pos, 5, len);
  25667. }
  25668. // Step 1: Send only the outer request headers (no body yet)
  25669. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25670. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25671. // Step 2: Read the first response
  25672. char buf[4096];
  25673. for (;;) {
  25674. auto n = recv(sock, buf, sizeof(buf), 0);
  25675. if (n <= 0) break;
  25676. first_response.append(buf, static_cast<size_t>(n));
  25677. // Stop once we have a complete response (headers + body)
  25678. auto hdr_end = first_response.find("\r\n\r\n");
  25679. if (hdr_end != std::string::npos) {
  25680. // Check for Content-Length to know when the body is complete
  25681. auto cl_pos = first_response.find("Content-Length:");
  25682. if (cl_pos != std::string::npos) {
  25683. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25684. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25685. auto cl = std::stoul(
  25686. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25687. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25688. } else {
  25689. break; // No Content-Length, assume headers-only response
  25690. }
  25691. }
  25692. }
  25693. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25694. // vulnerable server the keep-alive loop reads this as a second request. The
  25695. // server may already have closed the connection, so the result is ignored.
  25696. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25697. // Half-close so that a server which drained the body sees EOF and closes,
  25698. // instead of the read below waiting for the read timeout.
  25699. #ifdef _WIN32
  25700. ::shutdown(sock, SD_SEND);
  25701. #else
  25702. ::shutdown(sock, SHUT_WR);
  25703. #endif
  25704. // Step 4: Read until the server closes the connection
  25705. for (;;) {
  25706. auto n = recv(sock, buf, sizeof(buf), 0);
  25707. if (n <= 0) break;
  25708. }
  25709. return smuggled_count.load();
  25710. }
  25711. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25712. // A GET request with Content-Length to a static file handler must have its
  25713. // body drained before the keep-alive connection is reused. Otherwise the
  25714. // unread body bytes are interpreted as the next HTTP request.
  25715. std::string first_response;
  25716. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25717. "Host: localhost\r\n"
  25718. "Content-Length: {len}\r\n"
  25719. "\r\n",
  25720. first_response));
  25721. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25722. }
  25723. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25724. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25725. // be answered with 400 and the connection closed. Treating it as "no body"
  25726. // leaves the body to be parsed as the next request.
  25727. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25728. const char *targets[] = {
  25729. "GET /file", // handler that never reads the body
  25730. "GET /not-found", // no handler matches (404)
  25731. "POST /post", // handler that reads the body
  25732. };
  25733. for (auto target : targets) {
  25734. for (auto value : values) {
  25735. std::string first_response;
  25736. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25737. " HTTP/1.1\r\n"
  25738. "Host: localhost\r\n"
  25739. "Content-Length: " +
  25740. value + "\r\n\r\n",
  25741. first_response))
  25742. << target << " with Content-Length: " << value;
  25743. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25744. << target << " with Content-Length: " << value;
  25745. }
  25746. }
  25747. }
  25748. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25749. // A 400 for an unparseable request line leaves the rest of the message
  25750. // unread, so the connection must be closed rather than reused.
  25751. std::string first_response;
  25752. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25753. "Host: localhost\r\n"
  25754. "Content-Length: {len}\r\n"
  25755. "\r\n",
  25756. first_response));
  25757. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25758. }
  25759. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25760. // Same as above for a header block that fails to parse.
  25761. std::string first_response;
  25762. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25763. "Host: localhost\r\n"
  25764. "Bad Header\r\n"
  25765. "Content-Length: {len}\r\n"
  25766. "\r\n",
  25767. first_response));
  25768. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25769. }
  25770. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25771. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25772. // server must not read another request on that connection, even when the
  25773. // request had no body to drain.
  25774. std::string first_response;
  25775. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25776. "Host: localhost\r\n"
  25777. "\r\n",
  25778. first_response));
  25779. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25780. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25781. }
  25782. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25783. // A content reader that stops early leaves the stream inside the body.
  25784. // Draining the whole Content-Length from there, or reading the body again,
  25785. // reads into the next request, and whatever follows is parsed as a request
  25786. // of its own.
  25787. Server svr;
  25788. std::atomic<int> smuggled_count(0);
  25789. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25790. svr.Post("/upload", [](const Request &req, Response &res,
  25791. const ContentReader &content_reader) {
  25792. // Stop at the last chunk, so the whole body has been read however it
  25793. // arrives.
  25794. auto length = req.get_header_value_u64("Content-Length");
  25795. size_t total = 0;
  25796. auto consumed = content_reader([&](const char *, size_t n) {
  25797. total += n;
  25798. return total < length;
  25799. });
  25800. EXPECT_FALSE(consumed);
  25801. if (req.has_param("retry")) {
  25802. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25803. }
  25804. // Replace the 400 the aborted read set, which would close the connection.
  25805. res.set_redirect("/done");
  25806. });
  25807. auto port = svr.bind_to_any_port(HOST);
  25808. thread t = thread([&] { svr.listen_after_bind(); });
  25809. auto se = detail::scope_exit([&] {
  25810. svr.stop();
  25811. t.join();
  25812. });
  25813. svr.wait_until_ready();
  25814. // A front end sees the second request as a POST whose body is the GET. The
  25815. // first body is as long as the POST's headers, so draining it again reads
  25816. // exactly those and leaves the GET to be parsed next.
  25817. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25818. "Host: localhost\r\n"
  25819. "\r\n";
  25820. std::string second_head = "POST /post HTTP/1.1\r\n"
  25821. "Host: localhost\r\n"
  25822. "Content-Length: " +
  25823. std::to_string(inner.size()) +
  25824. "\r\n"
  25825. "\r\n";
  25826. for (auto target : {"/upload", "/upload?retry"}) {
  25827. smuggled_count = 0;
  25828. std::string request = "POST " + std::string(target) +
  25829. " HTTP/1.1\r\n"
  25830. "Host: localhost\r\n"
  25831. "Content-Length: " +
  25832. std::to_string(second_head.size()) +
  25833. "\r\n"
  25834. "\r\n" +
  25835. std::string(second_head.size(), 'A') + second_head +
  25836. inner;
  25837. std::string response;
  25838. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25839. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25840. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25841. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25842. EXPECT_EQ(0, smuggled_count.load()) << target;
  25843. }
  25844. }
  25845. // An error response closes the connection anyway, so the body is left unread
  25846. // with a redirect, such as one to a login page.
  25847. static void serve_redirects(Server &svr,
  25848. const std::function<void(int)> &client) {
  25849. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25850. res.set_redirect("/login");
  25851. return Server::HandlerResponse::Handled;
  25852. });
  25853. auto port = svr.bind_to_any_port(HOST);
  25854. ASSERT_GT(port, 0);
  25855. thread t = thread([&] { svr.listen_after_bind(); });
  25856. auto se = detail::scope_exit([&] {
  25857. svr.stop();
  25858. t.join();
  25859. ASSERT_FALSE(svr.is_running());
  25860. });
  25861. svr.wait_until_ready();
  25862. client(port);
  25863. }
  25864. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25865. Server svr;
  25866. serve_redirects(svr, [](int port) {
  25867. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25868. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25869. std::to_string(body.size()) + "\r\n\r\n" + body +
  25870. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25871. std::string resp;
  25872. ASSERT_TRUE(send_request(1, req, &resp, port));
  25873. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25874. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25875. });
  25876. }
  25877. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25878. Server svr;
  25879. svr.set_read_timeout(0, 200000);
  25880. serve_redirects(svr, [](int port) {
  25881. // A byte every 100 ms keeps each read within the read timeout, but not the
  25882. // body as a whole, so the server closes and the bytes sent after that fail.
  25883. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25884. "Content-Length: 10\r\n\r\n"};
  25885. parts.resize(11, "x");
  25886. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25887. });
  25888. }
  25889. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25890. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25891. // must be rejected with 400 Bad Request.
  25892. Server svr;
  25893. svr.Post("/test", [&](const Request &, Response &res) {
  25894. res.set_content("ok", "text/plain");
  25895. });
  25896. thread t = thread([&] { svr.listen(HOST, PORT); });
  25897. auto se = detail::scope_exit([&] {
  25898. svr.stop();
  25899. t.join();
  25900. ASSERT_FALSE(svr.is_running());
  25901. });
  25902. svr.wait_until_ready();
  25903. // Exact "chunked"
  25904. {
  25905. auto req = "POST /test HTTP/1.1\r\n"
  25906. "Host: localhost\r\n"
  25907. "Content-Length: 5\r\n"
  25908. "Transfer-Encoding: chunked\r\n"
  25909. "Connection: close\r\n"
  25910. "\r\n"
  25911. "hello";
  25912. std::string response;
  25913. ASSERT_TRUE(send_request(1, req, &response));
  25914. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25915. response.substr(0, response.find("\r\n")));
  25916. }
  25917. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25918. {
  25919. auto req = "POST /test HTTP/1.1\r\n"
  25920. "Host: localhost\r\n"
  25921. "Content-Length: 5\r\n"
  25922. "Transfer-Encoding: gzip, chunked\r\n"
  25923. "Connection: close\r\n"
  25924. "\r\n"
  25925. "hello";
  25926. std::string response;
  25927. ASSERT_TRUE(send_request(1, req, &response));
  25928. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25929. response.substr(0, response.find("\r\n")));
  25930. }
  25931. }
  25932. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25933. Server svr;
  25934. svr.Post("/test", [&](const Request &, Response &res) {
  25935. res.set_content("ok", "text/plain");
  25936. });
  25937. thread t = thread([&] { svr.listen(HOST, PORT); });
  25938. auto se = detail::scope_exit([&] {
  25939. svr.stop();
  25940. t.join();
  25941. ASSERT_FALSE(svr.is_running());
  25942. });
  25943. svr.wait_until_ready();
  25944. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25945. // length cannot be determined, so the server must answer 400 and close
  25946. // rather than treat the request as bodyless and leave the body in the
  25947. // socket for the next request to pick up.
  25948. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25949. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25950. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25951. std::string response;
  25952. ASSERT_TRUE(send_request(1, req, &response));
  25953. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25954. response.substr(0, response.find("\r\n")))
  25955. << transfer_encoding;
  25956. }
  25957. // RFC 9110 5.3: the codings may also be split across several
  25958. // Transfer-Encoding lines, which combine in the order they were received.
  25959. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25960. // just like the single-line "chunked, gzip" above.
  25961. {
  25962. auto req = "POST /test HTTP/1.1\r\n"
  25963. "Host: localhost\r\n"
  25964. "Transfer-Encoding: chunked\r\n"
  25965. "Transfer-Encoding: gzip\r\n"
  25966. "\r\n"
  25967. "0\r\n\r\n";
  25968. std::string response;
  25969. ASSERT_TRUE(send_request(1, req, &response));
  25970. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25971. response.substr(0, response.find("\r\n")));
  25972. }
  25973. }
  25974. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25975. Server svr;
  25976. svr.Post("/test", [&](const Request &, Response &res) {
  25977. res.set_content("ok", "text/plain");
  25978. });
  25979. auto port = svr.bind_to_any_port(HOST);
  25980. ASSERT_GT(port, 0);
  25981. thread t = thread([&] { svr.listen_after_bind(); });
  25982. auto se = detail::scope_exit([&] {
  25983. svr.stop();
  25984. t.join();
  25985. ASSERT_FALSE(svr.is_running());
  25986. });
  25987. svr.wait_until_ready();
  25988. for (auto transfer_encoding :
  25989. {"Transfer-Encoding: gzip, chunked\r\n",
  25990. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25991. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25992. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25993. transfer_encoding + "\r\n0\r\n\r\n";
  25994. std::string response;
  25995. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25996. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25997. response.substr(0, response.find("\r\n")))
  25998. << transfer_encoding;
  25999. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26000. << transfer_encoding;
  26001. }
  26002. }
  26003. // Regression for issue #2450: a DELETE without Content-Length on a
  26004. // keep-alive connection must not let the post-response drain consume the
  26005. // next request's bytes.
  26006. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26007. Server svr;
  26008. std::atomic<int> delete_count(0);
  26009. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26010. delete_count++;
  26011. res.status = StatusCode::NoContent_204;
  26012. });
  26013. auto port = svr.bind_to_any_port(HOST);
  26014. thread t = thread([&] { svr.listen_after_bind(); });
  26015. auto se = detail::scope_exit([&] {
  26016. svr.stop();
  26017. t.join();
  26018. });
  26019. svr.wait_until_ready();
  26020. auto error = Error::Success;
  26021. auto sock = detail::create_client_socket(
  26022. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26023. /*connection_timeout_sec=*/2, 0,
  26024. /*read_timeout_sec=*/2, 0,
  26025. /*write_timeout_sec=*/2, 0, std::string(), error);
  26026. ASSERT_NE(INVALID_SOCKET, sock);
  26027. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26028. auto send_request_and_read_response = [&](const std::string &req,
  26029. std::string &out) -> bool {
  26030. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26031. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26032. char buf[4096];
  26033. for (;;) {
  26034. auto n = recv(sock, buf, sizeof(buf), 0);
  26035. if (n <= 0) { return !out.empty(); }
  26036. out.append(buf, static_cast<size_t>(n));
  26037. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26038. }
  26039. };
  26040. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26041. "Host: localhost\r\n"
  26042. "\r\n";
  26043. std::string resp1;
  26044. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26045. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26046. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26047. "Host: localhost\r\n"
  26048. "Connection: close\r\n"
  26049. "\r\n";
  26050. std::string resp2;
  26051. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26052. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26053. EXPECT_EQ(2, delete_count.load());
  26054. }
  26055. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26056. Server svr;
  26057. svr.Post("/ingest", [&](const Request &, Response &res,
  26058. const ContentReader &content_reader) {
  26059. auto consumed = content_reader([](const char *, size_t) { return false; });
  26060. EXPECT_FALSE(consumed);
  26061. res.status = StatusCode::Conflict_409;
  26062. res.set_header("Connection", "close");
  26063. });
  26064. auto port = svr.bind_to_any_port(HOST);
  26065. thread t = thread([&] { svr.listen_after_bind(); });
  26066. auto se = detail::scope_exit([&] {
  26067. svr.stop();
  26068. t.join();
  26069. });
  26070. svr.wait_until_ready();
  26071. auto error = Error::Success;
  26072. auto sock = detail::create_client_socket(
  26073. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26074. /*connection_timeout_sec=*/2, 0,
  26075. /*read_timeout_sec=*/1, 0,
  26076. /*write_timeout_sec=*/2, 0, std::string(), error);
  26077. ASSERT_NE(INVALID_SOCKET, sock);
  26078. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26079. std::string request = "POST /ingest HTTP/1.1\r\n"
  26080. "Host: localhost\r\n"
  26081. "Transfer-Encoding: chunked\r\n"
  26082. "\r\n"
  26083. "4\r\n"
  26084. "data\r\n";
  26085. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26086. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26087. std::string response;
  26088. ssize_t received = 0;
  26089. do {
  26090. char buf[4096];
  26091. received = recv(sock, buf, sizeof(buf), 0);
  26092. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26093. } while (received > 0);
  26094. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26095. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26096. EXPECT_EQ(0, received);
  26097. }
  26098. namespace no_proxy_test {
  26099. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26100. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26101. // calling listen().
  26102. class ScopedServer {
  26103. public:
  26104. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26105. ~ScopedServer() {
  26106. svr_.stop();
  26107. if (th_.joinable()) { th_.join(); }
  26108. }
  26109. Server &svr() { return svr_; }
  26110. int port() const { return port_; }
  26111. void listen() {
  26112. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26113. svr_.wait_until_ready();
  26114. }
  26115. private:
  26116. Server svr_;
  26117. std::thread th_;
  26118. int port_ = 0;
  26119. };
  26120. class ProxyAndTargetServers {
  26121. public:
  26122. ProxyAndTargetServers() {
  26123. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26124. proxy_hits_++;
  26125. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26126. res.set_content("via-proxy", "text/plain");
  26127. });
  26128. target_.Get(".*", [this](const Request &req, Response &res) {
  26129. target_hits_++;
  26130. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26131. res.set_content("direct", "text/plain");
  26132. });
  26133. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26134. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26135. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26136. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26137. proxy_mock_.wait_until_ready();
  26138. target_.wait_until_ready();
  26139. }
  26140. ~ProxyAndTargetServers() {
  26141. proxy_mock_.stop();
  26142. target_.stop();
  26143. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26144. if (target_thread_.joinable()) { target_thread_.join(); }
  26145. }
  26146. Server &proxy_mock() { return proxy_mock_; }
  26147. Server &target() { return target_; }
  26148. int proxy_port() const { return proxy_port_; }
  26149. int target_port() const { return target_port_; }
  26150. int proxy_hits() const { return proxy_hits_.load(); }
  26151. int target_hits() const { return target_hits_.load(); }
  26152. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26153. void reset_counters() {
  26154. proxy_hits_ = 0;
  26155. target_hits_ = 0;
  26156. last_had_proxy_authz_ = false;
  26157. }
  26158. private:
  26159. Server proxy_mock_;
  26160. Server target_;
  26161. std::thread proxy_thread_;
  26162. std::thread target_thread_;
  26163. int proxy_port_ = 0;
  26164. int target_port_ = 0;
  26165. std::atomic<int> proxy_hits_{0};
  26166. std::atomic<int> target_hits_{0};
  26167. std::atomic<bool> last_had_proxy_authz_{false};
  26168. };
  26169. inline std::unique_ptr<Client> make_client(const std::string &host,
  26170. ProxyAndTargetServers &s) {
  26171. auto cli = detail::make_unique<Client>(host, s.target_port());
  26172. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  26173. cli->set_proxy("127.0.0.1", s.proxy_port());
  26174. return cli;
  26175. }
  26176. } // namespace no_proxy_test
  26177. using no_proxy_test::make_client;
  26178. using no_proxy_test::ProxyAndTargetServers;
  26179. // A stream request carries the credentials a buffered request does
  26180. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26181. no_proxy_test::ScopedServer origin;
  26182. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26183. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26184. });
  26185. origin.listen();
  26186. Client cli("127.0.0.1", origin.port());
  26187. cli.set_basic_auth("user", "pass");
  26188. auto handle = cli.open_stream("GET", "/x");
  26189. ASSERT_TRUE(handle.is_valid());
  26190. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26191. Client bearer("127.0.0.1", origin.port());
  26192. bearer.set_bearer_token_auth("tok");
  26193. auto handle2 = bearer.open_stream("GET", "/x");
  26194. ASSERT_TRUE(handle2.is_valid());
  26195. EXPECT_EQ("Bearer tok", read_all(handle2));
  26196. }
  26197. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26198. // takes its own credentials, as for a buffered request
  26199. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26200. std::string target, authz, proxy_authz;
  26201. no_proxy_test::ScopedServer proxy;
  26202. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26203. target = req.target;
  26204. authz = req.get_header_value("Authorization");
  26205. proxy_authz = req.get_header_value("Proxy-Authorization");
  26206. res.set_content("ok", "text/plain");
  26207. });
  26208. proxy.listen();
  26209. Client cli("origin.example", 8080);
  26210. cli.set_proxy("127.0.0.1", proxy.port());
  26211. cli.set_proxy_basic_auth("puser", "ppass");
  26212. cli.set_basic_auth("user", "pass");
  26213. auto handle = cli.open_stream("GET", "/x");
  26214. ASSERT_TRUE(handle.is_valid());
  26215. EXPECT_EQ("ok", read_all(handle));
  26216. EXPECT_EQ("http://origin.example:8080/x", target);
  26217. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26218. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26219. }
  26220. // In absolute-form the path follows the authority, so a path that does not
  26221. // begin with '/' would make the proxy connect to another host
  26222. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26223. std::vector<std::string> targets;
  26224. no_proxy_test::ScopedServer proxy;
  26225. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26226. targets.push_back(req.target);
  26227. res.set_content("ok", "text/plain");
  26228. });
  26229. proxy.listen();
  26230. Client cli("origin.example", 8080);
  26231. cli.set_proxy("127.0.0.1", proxy.port());
  26232. cli.set_basic_auth("user", "pass");
  26233. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26234. auto res = cli.Get(path);
  26235. EXPECT_FALSE(res) << path;
  26236. auto handle = cli.open_stream("GET", path);
  26237. EXPECT_FALSE(handle.is_valid()) << path;
  26238. }
  26239. EXPECT_TRUE(targets.empty());
  26240. auto res = cli.Get("/x");
  26241. ASSERT_TRUE(res);
  26242. ASSERT_EQ(1u, targets.size());
  26243. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26244. }
  26245. TEST(NoProxyTest, ExactHostnameBypasses) {
  26246. ProxyAndTargetServers s;
  26247. auto cli = make_client("example.com", s);
  26248. cli->set_no_proxy({"example.com"});
  26249. auto res = cli->Get("/");
  26250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26251. EXPECT_EQ(0, s.proxy_hits());
  26252. EXPECT_EQ(1, s.target_hits());
  26253. }
  26254. TEST(NoProxyTest, SubdomainBypasses) {
  26255. ProxyAndTargetServers s;
  26256. auto cli = make_client("foo.example.com", s);
  26257. cli->set_no_proxy({"example.com"});
  26258. auto res = cli->Get("/");
  26259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26260. EXPECT_EQ(0, s.proxy_hits());
  26261. EXPECT_EQ(1, s.target_hits());
  26262. }
  26263. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26264. // Regression guard: "evilexample.com" must not be considered a subdomain
  26265. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26266. // check would let traffic bypass the proxy and leak credentials direct
  26267. // to the attacker host.
  26268. ProxyAndTargetServers s;
  26269. auto cli = make_client("evilexample.com", s);
  26270. cli->set_no_proxy({"example.com"});
  26271. auto res = cli->Get("/");
  26272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26273. EXPECT_GE(s.proxy_hits(), 1);
  26274. EXPECT_EQ(0, s.target_hits());
  26275. }
  26276. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26277. ProxyAndTargetServers s;
  26278. auto cli = make_client("example.com.evil.com", s);
  26279. cli->set_no_proxy({"example.com"});
  26280. auto res = cli->Get("/");
  26281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26282. EXPECT_GE(s.proxy_hits(), 1);
  26283. EXPECT_EQ(0, s.target_hits());
  26284. }
  26285. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26286. ProxyAndTargetServers s;
  26287. auto cli = make_client("example.com", s);
  26288. cli->set_no_proxy({".example.com"});
  26289. auto res = cli->Get("/");
  26290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26291. EXPECT_EQ(0, s.proxy_hits());
  26292. EXPECT_EQ(1, s.target_hits());
  26293. }
  26294. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26295. ProxyAndTargetServers s;
  26296. auto cli = make_client("Example.COM", s);
  26297. cli->set_no_proxy({"EXAMPLE.com"});
  26298. auto res = cli->Get("/");
  26299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26300. EXPECT_EQ(0, s.proxy_hits());
  26301. EXPECT_EQ(1, s.target_hits());
  26302. }
  26303. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26304. ProxyAndTargetServers s;
  26305. auto cli = make_client("example.com.", s);
  26306. cli->set_no_proxy({"example.com"});
  26307. auto res = cli->Get("/");
  26308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26309. EXPECT_EQ(0, s.proxy_hits());
  26310. EXPECT_EQ(1, s.target_hits());
  26311. }
  26312. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26313. // Trailing dots must be normalized on BOTH sides — host and entry.
  26314. // An implementation that only strips the host-side trailing dot would
  26315. // fail to match host "example.com" against entry "example.com." because
  26316. // a literal substring search would compare 11 chars against 12.
  26317. ProxyAndTargetServers s;
  26318. auto cli = make_client("example.com", s);
  26319. cli->set_no_proxy({"example.com."});
  26320. auto res = cli->Get("/");
  26321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26322. EXPECT_EQ(0, s.proxy_hits());
  26323. EXPECT_EQ(1, s.target_hits());
  26324. }
  26325. TEST(NoProxyTest, WildcardBypassesEverything) {
  26326. ProxyAndTargetServers s;
  26327. auto cli = make_client("anything.invalid.test", s);
  26328. cli->set_no_proxy({"*"});
  26329. auto res = cli->Get("/");
  26330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26331. EXPECT_EQ(0, s.proxy_hits());
  26332. EXPECT_EQ(1, s.target_hits());
  26333. }
  26334. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26335. ProxyAndTargetServers s;
  26336. Client cli("127.0.0.1", s.target_port());
  26337. cli.set_proxy("127.0.0.1", s.proxy_port());
  26338. cli.set_no_proxy({"127.0.0.1"});
  26339. auto res = cli.Get("/");
  26340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26341. EXPECT_EQ(0, s.proxy_hits());
  26342. EXPECT_EQ(1, s.target_hits());
  26343. }
  26344. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26345. ProxyAndTargetServers s;
  26346. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26347. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26348. cli.set_proxy("127.0.0.1", s.proxy_port());
  26349. cli.set_no_proxy({"::1"});
  26350. auto res = cli.Get("/");
  26351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26352. EXPECT_EQ(0, s.proxy_hits());
  26353. EXPECT_EQ(1, s.target_hits());
  26354. }
  26355. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26356. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26357. // must still be recognized as IPv6 for CIDR matching. Implementations
  26358. // that detect IPv6 only when the host begins with '[' would parse the
  26359. // host as a hostname and miss the match.
  26360. ProxyAndTargetServers s;
  26361. Client cli("fe80::1", s.target_port());
  26362. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26363. cli.set_proxy("127.0.0.1", s.proxy_port());
  26364. cli.set_no_proxy({"fe80::/10"});
  26365. auto res = cli.Get("/");
  26366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26367. EXPECT_EQ(0, s.proxy_hits());
  26368. EXPECT_EQ(1, s.target_hits());
  26369. }
  26370. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26371. ProxyAndTargetServers s;
  26372. Client cli("::1", s.target_port());
  26373. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  26374. cli.set_proxy("127.0.0.1", s.proxy_port());
  26375. cli.set_no_proxy({"[::1]"});
  26376. auto res = cli.Get("/");
  26377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26378. EXPECT_EQ(0, s.proxy_hits());
  26379. EXPECT_EQ(1, s.target_hits());
  26380. }
  26381. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26382. ProxyAndTargetServers s;
  26383. Client cli("fe80::1", s.target_port());
  26384. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26385. cli.set_proxy("127.0.0.1", s.proxy_port());
  26386. cli.set_no_proxy({"[fe80::]/10"});
  26387. auto res = cli.Get("/");
  26388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26389. EXPECT_EQ(0, s.proxy_hits());
  26390. EXPECT_EQ(1, s.target_hits());
  26391. }
  26392. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26393. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26394. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26395. // tricks via address-family conversion.
  26396. ProxyAndTargetServers s;
  26397. Client cli("::ffff:127.0.0.1", s.target_port());
  26398. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26399. cli.set_proxy("127.0.0.1", s.proxy_port());
  26400. cli.set_no_proxy({"127.0.0.1"});
  26401. auto res = cli.Get("/");
  26402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26403. EXPECT_GE(s.proxy_hits(), 1);
  26404. EXPECT_EQ(0, s.target_hits());
  26405. }
  26406. TEST(NoProxyTest, IPv4CidrMatch) {
  26407. ProxyAndTargetServers s;
  26408. Client cli("127.0.0.1", s.target_port());
  26409. cli.set_proxy("127.0.0.1", s.proxy_port());
  26410. cli.set_no_proxy({"127.0.0.0/8"});
  26411. auto res = cli.Get("/");
  26412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26413. EXPECT_EQ(0, s.proxy_hits());
  26414. EXPECT_EQ(1, s.target_hits());
  26415. }
  26416. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26417. ProxyAndTargetServers s;
  26418. Client cli("127.0.0.1", s.target_port());
  26419. cli.set_proxy("127.0.0.1", s.proxy_port());
  26420. cli.set_no_proxy({"10.0.0.0/8"});
  26421. auto res = cli.Get("/");
  26422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26423. EXPECT_GE(s.proxy_hits(), 1);
  26424. EXPECT_EQ(0, s.target_hits());
  26425. }
  26426. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26427. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26428. // IPv4 target matches.
  26429. ProxyAndTargetServers s;
  26430. Client cli("127.0.0.1", s.target_port());
  26431. cli.set_proxy("127.0.0.1", s.proxy_port());
  26432. cli.set_no_proxy({"0.0.0.0/0"});
  26433. auto res = cli.Get("/");
  26434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26435. EXPECT_EQ(0, s.proxy_hits());
  26436. EXPECT_EQ(1, s.target_hits());
  26437. }
  26438. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  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.1"});
  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, MalformedCidrPrefixIsDropped) {
  26449. ProxyAndTargetServers s;
  26450. Client cli("127.0.0.1", s.target_port());
  26451. cli.set_proxy("127.0.0.1", s.proxy_port());
  26452. cli.set_no_proxy({"127.0.0.0/33"});
  26453. auto res = cli.Get("/");
  26454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26455. EXPECT_GE(s.proxy_hits(), 1);
  26456. EXPECT_EQ(0, s.target_hits());
  26457. }
  26458. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26459. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26460. ProxyAndTargetServers s;
  26461. Client cli("127.0.0.1", s.target_port());
  26462. cli.set_proxy("127.0.0.1", s.proxy_port());
  26463. cli.set_no_proxy({"127.0.0.1/"});
  26464. auto res = cli.Get("/");
  26465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26466. EXPECT_GE(s.proxy_hits(), 1);
  26467. EXPECT_EQ(0, s.target_hits());
  26468. }
  26469. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26470. ProxyAndTargetServers s;
  26471. auto cli = make_client("internal.corp", s);
  26472. cli->set_proxy_basic_auth("u", "p");
  26473. cli->set_no_proxy({"internal.corp"});
  26474. auto res = cli->Get("/");
  26475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26476. EXPECT_EQ(1, s.target_hits());
  26477. EXPECT_EQ(0, s.proxy_hits());
  26478. EXPECT_FALSE(s.last_had_proxy_authz())
  26479. << "Proxy-Authorization must not be sent direct to the target";
  26480. }
  26481. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26482. ProxyAndTargetServers s;
  26483. auto cli = make_client("public.example", s);
  26484. cli->set_proxy_basic_auth("u", "p");
  26485. cli->set_no_proxy({"internal.corp"}); // does not match
  26486. auto res = cli->Get("/");
  26487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26488. EXPECT_GE(s.proxy_hits(), 1);
  26489. EXPECT_TRUE(s.last_had_proxy_authz());
  26490. }
  26491. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26492. std::atomic<int> hits{0};
  26493. std::atomic<int> hits_with_authz{0};
  26494. no_proxy_test::ScopedServer proxy_mock;
  26495. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26496. hits++;
  26497. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26498. if (req.target.find("/redir") != std::string::npos) {
  26499. res.set_redirect("http://other.example/landed");
  26500. } else {
  26501. res.set_content("via-proxy", "text/plain");
  26502. }
  26503. });
  26504. proxy_mock.listen();
  26505. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26506. hits = 0;
  26507. hits_with_authz = 0;
  26508. Client cli("public.example", 80);
  26509. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26510. cli.set_proxy_basic_auth(c.first, c.second);
  26511. cli.set_follow_location(true);
  26512. // The redirect to another host goes through the proxy as well
  26513. auto res = cli.Get("/redir");
  26514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26515. EXPECT_EQ(2, hits.load());
  26516. EXPECT_EQ(2, hits_with_authz.load());
  26517. }
  26518. }
  26519. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26520. ProxyAndTargetServers s;
  26521. auto cli = make_client("anything.test", s);
  26522. auto res = cli->Get("/");
  26523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26524. EXPECT_GE(s.proxy_hits(), 1);
  26525. EXPECT_EQ(0, s.target_hits());
  26526. }
  26527. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26528. ProxyAndTargetServers s;
  26529. auto cli = make_client("example.com", s);
  26530. cli->set_no_proxy({"example.com:8080"});
  26531. auto res = cli->Get("/");
  26532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26533. EXPECT_GE(s.proxy_hits(), 1);
  26534. EXPECT_EQ(0, s.target_hits());
  26535. }
  26536. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26537. ProxyAndTargetServers s;
  26538. auto cli = make_client("anything.test", s);
  26539. cli->set_no_proxy({"", " ", "\t"});
  26540. auto res = cli->Get("/");
  26541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26542. EXPECT_GE(s.proxy_hits(), 1);
  26543. EXPECT_EQ(0, s.target_hits());
  26544. }
  26545. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26546. // An entry with leading/trailing whitespace must still match — env-style
  26547. // values are commonly pasted with stray spaces and an implementation
  26548. // that feeds the raw token directly to inet_pton would fail to match
  26549. // valid CIDRs because of the spaces.
  26550. ProxyAndTargetServers s;
  26551. Client cli("127.0.0.1", s.target_port());
  26552. cli.set_proxy("127.0.0.1", s.proxy_port());
  26553. cli.set_no_proxy({" 127.0.0.0/8 "});
  26554. auto res = cli.Get("/");
  26555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26556. EXPECT_EQ(0, s.proxy_hits());
  26557. EXPECT_EQ(1, s.target_hits());
  26558. }
  26559. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26560. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26561. // go direct and must NOT carry Proxy-Authorization.
  26562. std::atomic<int> proxy_hits{0};
  26563. std::atomic<int> target_hits{0};
  26564. std::atomic<bool> target_saw_authz{false};
  26565. no_proxy_test::ScopedServer proxy_mock, target;
  26566. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26567. proxy_hits++;
  26568. res.status = 302;
  26569. res.set_header("Location", "http://127.0.0.1:" +
  26570. std::to_string(target.port()) + "/landed");
  26571. });
  26572. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26573. target_hits++;
  26574. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26575. res.set_content("direct", "text/plain");
  26576. });
  26577. proxy_mock.listen();
  26578. target.listen();
  26579. Client cli("public.example", target.port());
  26580. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26581. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26582. cli.set_proxy_basic_auth("u", "p");
  26583. cli.set_no_proxy({"127.0.0.1"});
  26584. cli.set_follow_location(true);
  26585. auto res = cli.Get("/redir");
  26586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26587. EXPECT_GE(proxy_hits.load(), 1);
  26588. EXPECT_GE(target_hits.load(), 1);
  26589. EXPECT_FALSE(target_saw_authz.load());
  26590. }
  26591. #ifdef CPPHTTPLIB_SSL_ENABLED
  26592. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26593. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26594. // proxy creds would be sent to the (possibly hostile) origin.
  26595. std::atomic<int> target_hits{0};
  26596. std::atomic<bool> target_saw_proxy_authz{false};
  26597. no_proxy_test::ScopedServer target;
  26598. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26599. target_hits++;
  26600. if (req.has_header("Proxy-Authorization")) {
  26601. target_saw_proxy_authz = true;
  26602. }
  26603. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26604. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26605. "nonce=\"abc\", algorithm=MD5");
  26606. });
  26607. target.listen();
  26608. // The proxy address is set to the target's port: the bypass MUST kick in;
  26609. // if it doesn't, the test still routes "via proxy" to the same server and
  26610. // the Proxy-Authorization assertion below catches the leak.
  26611. Client cli("evil.example", target.port());
  26612. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26613. cli.set_proxy("127.0.0.1", target.port());
  26614. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26615. cli.set_no_proxy({"evil.example"});
  26616. auto res = cli.Get("/x");
  26617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26618. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26619. EXPECT_EQ(1, target_hits.load());
  26620. EXPECT_FALSE(target_saw_proxy_authz.load());
  26621. }
  26622. #endif
  26623. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26624. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26625. std::atomic<int> proxy_hits{0};
  26626. std::atomic<int> bypass_hits{0};
  26627. std::atomic<bool> proxy_saw_c_url{false};
  26628. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26629. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26630. proxy_hits++;
  26631. if (req.path.find("/start") != std::string::npos) {
  26632. res.status = 302;
  26633. res.set_header("Location", "http://127.0.0.1:" +
  26634. std::to_string(bypass_server.port()) +
  26635. "/middle");
  26636. return;
  26637. }
  26638. if (req.path.find("/end") != std::string::npos) {
  26639. proxy_saw_c_url = true;
  26640. res.set_content("c-via-proxy", "text/plain");
  26641. return;
  26642. }
  26643. res.set_content("unexpected", "text/plain");
  26644. });
  26645. // public.example's "advertised" port is arbitrary (the request never lands
  26646. // there — it goes through the proxy), but use a dynamic value to stay
  26647. // friendly with sharded parallel runs.
  26648. int public_port = bypass_server.port();
  26649. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26650. bypass_hits++;
  26651. res.status = 302;
  26652. res.set_header("Location", "http://public.example:" +
  26653. std::to_string(public_port) + "/end");
  26654. });
  26655. proxy_mock.listen();
  26656. bypass_server.listen();
  26657. Client cli("public.example", public_port);
  26658. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26659. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26660. cli.set_no_proxy({"127.0.0.1"});
  26661. cli.set_follow_location(true);
  26662. auto res = cli.Get("/start");
  26663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26664. EXPECT_EQ(StatusCode::OK_200, res->status);
  26665. EXPECT_EQ("c-via-proxy", res->body);
  26666. EXPECT_GE(proxy_hits.load(), 2);
  26667. EXPECT_GE(bypass_hits.load(), 1);
  26668. EXPECT_TRUE(proxy_saw_c_url.load());
  26669. }
  26670. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26671. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26672. // request reconnects to the correct endpoint.
  26673. std::atomic<int> proxy_hits{0};
  26674. std::atomic<int> target_hits{0};
  26675. no_proxy_test::ScopedServer proxy_mock, target;
  26676. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26677. proxy_hits++;
  26678. res.set_content("via-proxy", "text/plain");
  26679. });
  26680. target.svr().Get(".*", [&](const Request &, Response &res) {
  26681. target_hits++;
  26682. res.set_content("direct", "text/plain");
  26683. });
  26684. proxy_mock.listen();
  26685. target.listen();
  26686. Client cli("public.example", target.port());
  26687. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26688. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26689. cli.set_keep_alive(true);
  26690. auto res1 = cli.Get("/a");
  26691. ASSERT_TRUE(res1);
  26692. EXPECT_EQ("via-proxy", res1->body);
  26693. EXPECT_EQ(1, proxy_hits.load());
  26694. EXPECT_EQ(0, target_hits.load());
  26695. cli.set_no_proxy({"public.example"});
  26696. auto res2 = cli.Get("/b");
  26697. ASSERT_TRUE(res2);
  26698. EXPECT_EQ("direct", res2->body);
  26699. EXPECT_EQ(1, proxy_hits.load());
  26700. EXPECT_EQ(1, target_hits.load());
  26701. }
  26702. // Forward declarations (see the base64_encode note).
  26703. namespace httplib {
  26704. namespace detail {
  26705. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26706. int shutdown_socket(socket_t sock) noexcept;
  26707. } // namespace detail
  26708. } // namespace httplib
  26709. namespace proxy_tunnel_test {
  26710. const char *const kTunnelEstablished =
  26711. "HTTP/1.1 200 Connection established\r\n\r\n";
  26712. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26713. using ConnectReply = std::function<std::string(const std::string &head)>;
  26714. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26715. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26716. class ScopedConnectProxy {
  26717. public:
  26718. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26719. : forward_port_(forward_port), reply_(std::move(reply)) {
  26720. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26721. if (listen_sock_ == INVALID_SOCKET) { return; }
  26722. auto a = loopback(0);
  26723. auto addr = reinterpret_cast<sockaddr *>(&a);
  26724. socklen_t alen = sizeof(a);
  26725. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26726. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26727. ::listen(listen_sock_, 4) != 0) {
  26728. return;
  26729. }
  26730. port_ = ntohs(a.sin_port);
  26731. th_ = std::thread([this] { run(); });
  26732. }
  26733. ~ScopedConnectProxy() {
  26734. if (th_.joinable()) {
  26735. stop_ = true;
  26736. auto wake = connect_to(port_);
  26737. th_.join();
  26738. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26739. }
  26740. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26741. }
  26742. int port() const { return port_; }
  26743. int connect_hits() const { return connect_hits_.load(); }
  26744. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26745. std::string connect_request() const {
  26746. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26747. return connect_request_;
  26748. }
  26749. private:
  26750. static sockaddr_in loopback(int port) {
  26751. sockaddr_in a{};
  26752. a.sin_family = AF_INET;
  26753. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26754. a.sin_port = htons(static_cast<unsigned short>(port));
  26755. return a;
  26756. }
  26757. static socket_t connect_to(int port) {
  26758. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26759. if (sock == INVALID_SOCKET) { return sock; }
  26760. auto a = loopback(port);
  26761. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26762. detail::close_socket(sock);
  26763. return INVALID_SOCKET;
  26764. }
  26765. return sock;
  26766. }
  26767. static bool send_all(socket_t sock, const char *data, size_t size) {
  26768. while (size > 0) {
  26769. auto n = detail::send_socket(sock, data, size, 0);
  26770. if (n <= 0) { return false; }
  26771. data += n;
  26772. size -= static_cast<size_t>(n);
  26773. }
  26774. return true;
  26775. }
  26776. void run() {
  26777. for (;;) {
  26778. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26779. if (stop_) {
  26780. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26781. return;
  26782. }
  26783. if (client == INVALID_SOCKET) { continue; }
  26784. serve(client);
  26785. detail::close_socket(client);
  26786. }
  26787. }
  26788. void serve(socket_t client) {
  26789. std::string head;
  26790. char buf[2048];
  26791. while (head.find("\r\n\r\n") == std::string::npos) {
  26792. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26793. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26794. if (n <= 0) { return; }
  26795. head.append(buf, static_cast<size_t>(n));
  26796. }
  26797. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26798. connect_hits_++;
  26799. {
  26800. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26801. connect_request_ = head;
  26802. }
  26803. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26804. if (!send_all(client, res.data(), res.size()) ||
  26805. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26806. return;
  26807. }
  26808. auto origin = connect_to(forward_port_);
  26809. if (origin == INVALID_SOCKET) { return; }
  26810. // When either side stops, shut both down so the other pump returns too.
  26811. auto pump = [&](socket_t from, socket_t to) {
  26812. char b[8192];
  26813. for (;;) {
  26814. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26815. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26816. }
  26817. detail::shutdown_socket(client);
  26818. detail::shutdown_socket(origin);
  26819. };
  26820. std::thread up([&] { pump(client, origin); });
  26821. pump(origin, client);
  26822. up.join();
  26823. detail::close_socket(origin);
  26824. }
  26825. int forward_port_;
  26826. ConnectReply reply_;
  26827. socket_t listen_sock_ = INVALID_SOCKET;
  26828. int port_ = 0;
  26829. std::thread th_;
  26830. std::atomic<bool> stop_{false};
  26831. std::atomic<int> connect_hits_{0};
  26832. mutable std::mutex connect_request_mutex_;
  26833. std::string connect_request_;
  26834. };
  26835. } // namespace proxy_tunnel_test
  26836. #ifdef CPPHTTPLIB_SSL_ENABLED
  26837. namespace proxy_tunnel_test {
  26838. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26839. class ScopedSSLServer {
  26840. public:
  26841. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26842. port_ = svr_.bind_to_any_port("127.0.0.1");
  26843. }
  26844. ~ScopedSSLServer() {
  26845. svr_.stop();
  26846. if (th_.joinable()) { th_.join(); }
  26847. }
  26848. SSLServer &svr() { return svr_; }
  26849. int port() const { return port_; }
  26850. void listen() {
  26851. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26852. svr_.wait_until_ready();
  26853. }
  26854. private:
  26855. SSLServer svr_;
  26856. std::thread th_;
  26857. int port_ = 0;
  26858. };
  26859. // Sends one request through the CONNECT proxy to the TLS origin with a
  26860. // credential configured for each hop, and checks that each credential reaches
  26861. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26862. // origin's (every header in origin_headers) on the tunnelled request.
  26863. void CredentialsStayWithTheirHop(
  26864. const std::function<void(SSLClient &)> &set_credentials,
  26865. const std::string &scheme,
  26866. const std::vector<std::string> &origin_headers = {"Authorization"},
  26867. bool stream = false) {
  26868. std::atomic<int> origin_hits{0};
  26869. std::atomic<bool> origin_saw_proxy_authz{false};
  26870. std::atomic<bool> origin_saw_headers{false};
  26871. ScopedSSLServer origin;
  26872. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26873. origin_hits++;
  26874. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26875. origin_saw_headers =
  26876. std::all_of(origin_headers.begin(), origin_headers.end(),
  26877. [&](const std::string &h) { return req.has_header(h); });
  26878. res.set_content("ok", "text/plain");
  26879. });
  26880. origin.listen();
  26881. ScopedConnectProxy proxy(origin.port());
  26882. ASSERT_NE(0, proxy.port());
  26883. // Pinned to 127.0.0.1 for the same reason as the test below.
  26884. SSLClient cli("127.0.0.1", origin.port());
  26885. cli.enable_server_certificate_verification(false);
  26886. cli.set_proxy("127.0.0.1", proxy.port());
  26887. set_credentials(cli);
  26888. if (stream) {
  26889. auto handle = cli.open_stream("GET", "/x");
  26890. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26891. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26892. } else {
  26893. auto res = cli.Get("/x");
  26894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26895. EXPECT_EQ(StatusCode::OK_200, res->status);
  26896. }
  26897. EXPECT_EQ(1, origin_hits.load());
  26898. EXPECT_EQ(1, proxy.connect_hits());
  26899. EXPECT_TRUE(origin_saw_headers.load());
  26900. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26901. << "Proxy-Authorization must not be sent inside the tunnel";
  26902. auto connect_req = proxy.connect_request();
  26903. EXPECT_NE(std::string::npos,
  26904. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26905. for (const auto &h : origin_headers) {
  26906. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26907. << h << " must not be sent to the proxy on CONNECT";
  26908. }
  26909. }
  26910. } // namespace proxy_tunnel_test
  26911. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26912. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26913. [](SSLClient &cli) {
  26914. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26915. cli.set_basic_auth("origin-user", "origin-pass");
  26916. },
  26917. "Basic");
  26918. }
  26919. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26920. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26921. [](SSLClient &cli) {
  26922. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26923. cli.set_basic_auth("origin-user", "origin-pass");
  26924. },
  26925. "Basic", {"Authorization"}, true);
  26926. }
  26927. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26928. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26929. [](SSLClient &cli) {
  26930. cli.set_proxy_bearer_token_auth("proxy-token");
  26931. cli.set_bearer_token_auth("origin-token");
  26932. },
  26933. "Bearer");
  26934. }
  26935. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26936. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26937. [](SSLClient &cli) {
  26938. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26939. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26940. {"Cookie", "sid=origin-session"},
  26941. {"X-Api-Key", "origin-key"}});
  26942. },
  26943. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26944. }
  26945. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26946. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26947. // retry; otherwise proxy creds would be sent to the origin.
  26948. std::atomic<int> origin_hits{0};
  26949. std::atomic<bool> origin_saw_proxy_authz{false};
  26950. proxy_tunnel_test::ScopedSSLServer origin;
  26951. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26952. origin_hits++;
  26953. if (req.has_header("Proxy-Authorization")) {
  26954. origin_saw_proxy_authz = true;
  26955. }
  26956. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26957. res.set_header("Proxy-Authenticate",
  26958. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26959. "algorithm=MD5");
  26960. });
  26961. origin.listen();
  26962. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26963. ASSERT_NE(0, proxy.port());
  26964. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26965. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26966. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26967. // and answer with its own status, making this test flaky.
  26968. SSLClient cli("127.0.0.1", origin.port());
  26969. cli.enable_server_certificate_verification(false);
  26970. cli.set_proxy("127.0.0.1", proxy.port());
  26971. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26972. auto res = cli.Get("/x");
  26973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26974. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26975. EXPECT_EQ(1, origin_hits.load());
  26976. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26977. EXPECT_EQ(1, proxy.connect_hits());
  26978. }
  26979. #endif
  26980. namespace proxy_tunnel_test {
  26981. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26982. // anything else gets a 407 with `challenge`.
  26983. ConnectReply require_proxy_auth(const std::string &expected,
  26984. const std::string &challenge) {
  26985. return [=](const std::string &head) -> std::string {
  26986. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26987. std::string::npos) {
  26988. return kTunnelEstablished;
  26989. }
  26990. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26991. "Proxy-Authenticate: " +
  26992. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26993. };
  26994. }
  26995. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26996. // request, then echoes.
  26997. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26998. ws.send(
  26999. "authorization:" + req.get_header_value("Authorization") +
  27000. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27001. std::string msg;
  27002. while (ws.read(msg)) {
  27003. ws.send(msg);
  27004. }
  27005. }
  27006. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27007. class ScopedWebSocketOrigin {
  27008. public:
  27009. ScopedWebSocketOrigin() {
  27010. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27011. server_.listen();
  27012. }
  27013. int port() const { return server_.port(); }
  27014. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27015. std::string url() const {
  27016. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27017. }
  27018. private:
  27019. no_proxy_test::ScopedServer server_;
  27020. };
  27021. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27022. // passed as a constructor header, and checks that each reaches only its hop.
  27023. void WebSocketCredentialsStayWithTheirHop(
  27024. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27025. const std::string &proxy_authz, const std::string &origin_authz) {
  27026. ScopedWebSocketOrigin origin;
  27027. ScopedConnectProxy proxy(
  27028. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27029. ASSERT_NE(0, proxy.port());
  27030. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27031. client.set_proxy("127.0.0.1", proxy.port());
  27032. set_proxy_credentials(client);
  27033. auto res = client.connect();
  27034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27035. std::string msg;
  27036. ASSERT_TRUE(client.read(msg));
  27037. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27038. client.close();
  27039. EXPECT_EQ(1, proxy.connect_hits());
  27040. EXPECT_EQ(std::string::npos,
  27041. proxy.connect_request().find("\r\nAuthorization: "))
  27042. << "origin credentials must not be sent to the proxy";
  27043. }
  27044. } // namespace proxy_tunnel_test
  27045. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27046. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27047. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27048. ASSERT_NE(0, proxy.port());
  27049. ws::WebSocketClient client(origin.url());
  27050. client.set_proxy("127.0.0.1", proxy.port());
  27051. auto res = client.connect();
  27052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27053. std::string msg;
  27054. ASSERT_TRUE(client.read(msg));
  27055. ASSERT_TRUE(client.send("hello"));
  27056. ASSERT_TRUE(client.read(msg));
  27057. EXPECT_EQ("hello", msg);
  27058. client.close();
  27059. EXPECT_EQ(1, proxy.connect_hits());
  27060. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27061. auto connect_req = proxy.connect_request();
  27062. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27063. EXPECT_NE(std::string::npos,
  27064. connect_req.find("\r\nHost: " + target + "\r\n"));
  27065. }
  27066. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27067. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27068. [](ws::WebSocketClient &cli) {
  27069. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27070. },
  27071. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27072. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27073. }
  27074. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27075. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27076. [](ws::WebSocketClient &cli) {
  27077. cli.set_proxy_bearer_token_auth("proxy-token");
  27078. },
  27079. "Bearer proxy-token", "Bearer origin-token");
  27080. }
  27081. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27082. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27083. proxy_tunnel_test::ScopedConnectProxy proxy(
  27084. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27085. "Basic " + detail::base64_encode("proxy-user:"),
  27086. "Basic realm=\"proxy\""));
  27087. ASSERT_NE(0, proxy.port());
  27088. ws::WebSocketClient client(origin.url());
  27089. client.set_proxy("127.0.0.1", proxy.port());
  27090. client.set_proxy_basic_auth("proxy-user", "");
  27091. auto res = client.connect();
  27092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27093. client.close();
  27094. EXPECT_EQ(1, proxy.connect_hits());
  27095. }
  27096. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27097. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27098. proxy_tunnel_test::ScopedConnectProxy proxy(
  27099. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27100. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27101. ASSERT_NE(0, proxy.port());
  27102. ws::WebSocketClient client(origin.url());
  27103. client.set_proxy("127.0.0.1", proxy.port());
  27104. auto res = client.connect();
  27105. EXPECT_FALSE(res);
  27106. EXPECT_EQ(Error::ProxyConnection, res.error());
  27107. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27108. EXPECT_EQ("Basic realm=\"proxy\"",
  27109. res.get_header_value("Proxy-Authenticate"));
  27110. EXPECT_FALSE(client.is_open());
  27111. }
  27112. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27113. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27114. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27115. ASSERT_NE(0, proxy.port());
  27116. ws::WebSocketClient client(origin.url());
  27117. client.set_proxy("127.0.0.1", proxy.port());
  27118. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27119. client.set_no_proxy({"127.0.0.1"});
  27120. auto res = client.connect();
  27121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27122. std::string msg;
  27123. ASSERT_TRUE(client.read(msg));
  27124. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27125. << "proxy credentials must not reach a bypassed origin";
  27126. client.close();
  27127. EXPECT_EQ(0, proxy.connect_hits());
  27128. }
  27129. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27130. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27131. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27132. ASSERT_NE(0, proxy.port());
  27133. ws::WebSocketClient client(origin.url());
  27134. client.set_proxy("127.0.0.1", proxy.port());
  27135. ASSERT_TRUE(client.connect());
  27136. ASSERT_TRUE(client.connect());
  27137. client.close();
  27138. EXPECT_EQ(2, proxy.connect_hits());
  27139. }
  27140. #ifdef CPPHTTPLIB_SSL_ENABLED
  27141. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27142. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27143. proxy_tunnel_test::ScopedConnectProxy proxy(
  27144. origin.port(), [](const std::string &head) -> std::string {
  27145. if (head.find(
  27146. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27147. std::string::npos) {
  27148. return proxy_tunnel_test::kTunnelEstablished;
  27149. }
  27150. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27151. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27152. "nonce=\"abc\", algorithm=MD5\r\n"
  27153. "Content-Length: 0\r\n\r\n";
  27154. });
  27155. ASSERT_NE(0, proxy.port());
  27156. ws::WebSocketClient client(origin.url());
  27157. client.set_proxy("127.0.0.1", proxy.port());
  27158. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27159. auto res = client.connect();
  27160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27161. std::string msg;
  27162. ASSERT_TRUE(client.read(msg));
  27163. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27164. client.close();
  27165. EXPECT_EQ(2, proxy.connect_hits());
  27166. }
  27167. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27168. proxy_tunnel_test::ScopedSSLServer origin;
  27169. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27170. origin.listen();
  27171. proxy_tunnel_test::ScopedConnectProxy proxy(
  27172. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27173. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27174. ASSERT_NE(0, proxy.port());
  27175. ws::WebSocketClient client(
  27176. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27177. client.enable_server_certificate_verification(false);
  27178. client.set_proxy("127.0.0.1", proxy.port());
  27179. client.set_proxy_bearer_token_auth("proxy-token");
  27180. auto res = client.connect();
  27181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27182. std::string msg;
  27183. ASSERT_TRUE(client.read(msg));
  27184. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27185. << "Proxy-Authorization must not be sent inside the tunnel";
  27186. client.close();
  27187. EXPECT_EQ(1, proxy.connect_hits());
  27188. }
  27189. #endif