test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  71. namespace impl {
  72. SecTrustSettingsResult
  73. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  74. } // namespace impl
  75. #endif
  76. } // namespace tls
  77. } // namespace httplib
  78. #endif
  79. using namespace std;
  80. using namespace httplib;
  81. const char *HOST = "localhost";
  82. static int get_base_port() {
  83. const char *shard = getenv("GTEST_SHARD_INDEX");
  84. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  85. }
  86. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  87. // New standalone tests MUST use svr.bind_to_any_port() instead.
  88. const int PORT = get_base_port();
  89. const string LONG_QUERY_VALUE = string(25000, '@');
  90. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  91. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  92. const string TOO_LONG_QUERY_URL =
  93. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  94. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  95. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  96. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  97. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  98. return file.name == key;
  99. });
  100. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  101. return *it;
  102. #else
  103. if (it != items.end()) { return *it; }
  104. throw std::runtime_error("invalid multipart form data name error");
  105. #endif
  106. }
  107. static void read_file(const std::string &path, std::string &out) {
  108. std::ifstream fs(path, std::ios_base::binary);
  109. if (!fs) {
  110. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  111. return;
  112. #else
  113. throw std::runtime_error("File not found: " + path);
  114. #endif
  115. }
  116. fs.seekg(0, std::ios_base::end);
  117. auto size = fs.tellg();
  118. fs.seekg(0);
  119. out.resize(static_cast<size_t>(size));
  120. fs.read(&out[0], static_cast<std::streamsize>(size));
  121. }
  122. class UnixSocketTest : public ::testing::Test {
  123. protected:
  124. void TearDown() override { std::remove(pathname_.c_str()); }
  125. void client_GET(const std::string &addr) {
  126. httplib::Client cli{addr};
  127. cli.set_address_family(AF_UNIX);
  128. ASSERT_TRUE(cli.is_valid());
  129. const auto &result = cli.Get(pattern_);
  130. ASSERT_TRUE(result) << "error: " << result.error();
  131. const auto &resp = result.value();
  132. EXPECT_EQ(resp.status, StatusCode::OK_200);
  133. EXPECT_EQ(resp.body, content_);
  134. }
  135. static std::string make_sock_path() {
  136. const char *shard = getenv("GTEST_SHARD_INDEX");
  137. return shard ? std::string("./httplib-server-") + shard + ".sock"
  138. : "./httplib-server.sock";
  139. }
  140. const std::string pathname_{make_sock_path()};
  141. const std::string pattern_{"/hi"};
  142. const std::string content_{"Hello World!"};
  143. };
  144. TEST_F(UnixSocketTest, pathname) {
  145. httplib::Server svr;
  146. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  147. res.set_content(content_, "text/plain");
  148. });
  149. std::thread t{[&] {
  150. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  151. }};
  152. auto se = detail::scope_exit([&] {
  153. svr.stop();
  154. t.join();
  155. ASSERT_FALSE(svr.is_running());
  156. });
  157. svr.wait_until_ready();
  158. ASSERT_TRUE(svr.is_running());
  159. client_GET(pathname_);
  160. // ".//x.sock", which is not taken for a URL
  161. client_GET("./" + pathname_.substr(1));
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_TRUE(s0.is_peer_alive());
  254. EXPECT_EQ(0, close(fds[1]));
  255. EXPECT_FALSE(s0.is_peer_alive());
  256. return true;
  257. });
  258. EXPECT_EQ(0, close(fds[0]));
  259. }
  260. TEST(SocketStream, wait_writable_INET) {
  261. sockaddr_in addr;
  262. memset(&addr, 0, sizeof(addr));
  263. addr.sin_family = AF_INET;
  264. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  265. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  266. int disconnected_svr_sock = -1;
  267. std::thread svr{[&] {
  268. const int s = socket(AF_INET, SOCK_STREAM, 0);
  269. ASSERT_LE(0, s);
  270. // PORT + 1 is shared with the SSL redirect tests and with
  271. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  272. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  273. // because that happens on a worker thread the ASSERT does not stop the
  274. // test: it runs on and fails at the disconnected_svr_sock check instead.
  275. default_socket_options(s);
  276. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  277. ASSERT_EQ(0, listen(s, 1));
  278. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  282. std::thread cli{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, close(s));
  287. }};
  288. cli.join();
  289. svr.join();
  290. ASSERT_NE(disconnected_svr_sock, -1);
  291. const auto asSocketStream = [&](socket_t fd,
  292. std::function<bool(Stream &)> func) {
  293. return detail::process_client_socket(
  294. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  295. };
  296. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  297. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  298. // wait_writable() returns true because select_write() only checks if the
  299. // send buffer has space. Peer disconnection is detected later by send().
  300. EXPECT_TRUE(ss.wait_writable());
  301. return true;
  302. });
  303. ASSERT_EQ(0, close(disconnected_svr_sock));
  304. }
  305. #endif // #ifndef _WIN32
  306. TEST(SetSocketOptTest, TcpNoDelay) {
  307. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  308. ASSERT_NE(sock, INVALID_SOCKET);
  309. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  310. int val = 0;
  311. socklen_t len = sizeof(val);
  312. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  313. reinterpret_cast<char *>(&val), &len));
  314. EXPECT_NE(val, 0);
  315. detail::close_socket(sock);
  316. }
  317. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  318. // accept() reports failures through WSAGetLastError() on Windows and through
  319. // errno everywhere else. Asking the wrong one is what made the accept loop
  320. // treat every recoverable failure as fatal on Windows.
  321. struct Classification {
  322. bool resource;
  323. bool transient;
  324. };
  325. auto classify = [](int err) {
  326. #ifdef _WIN32
  327. WSASetLastError(err);
  328. #else
  329. errno = err;
  330. #endif
  331. // Read both before asserting: an assertion may clobber the error slot.
  332. Classification c;
  333. c.resource = detail::is_accept_resource_error();
  334. c.transient = detail::is_accept_transient_error();
  335. return c;
  336. };
  337. #ifdef _WIN32
  338. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  339. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  340. WSAECONNRESET, WSAECONNABORTED};
  341. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  342. #else
  343. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  344. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  345. ECONNABORTED};
  346. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  347. #endif
  348. for (auto err : resource_errors) {
  349. const auto c = classify(err);
  350. EXPECT_TRUE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. for (auto err : transient_errors) {
  354. const auto c = classify(err);
  355. EXPECT_TRUE(c.transient) << "error " << err;
  356. EXPECT_FALSE(c.resource) << "error " << err;
  357. }
  358. for (auto err : fatal_errors) {
  359. const auto c = classify(err);
  360. EXPECT_FALSE(c.resource) << "error " << err;
  361. EXPECT_FALSE(c.transient) << "error " << err;
  362. }
  363. #ifdef _WIN32
  364. WSASetLastError(0);
  365. #else
  366. errno = 0;
  367. #endif
  368. }
  369. TEST(ClientTest, MoveConstructible) {
  370. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  371. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  372. }
  373. TEST(ClientTest, MoveAssignable) {
  374. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  375. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  376. }
  377. #ifdef _WIN32
  378. TEST(StartupTest, WSAStartup) {
  379. WSADATA wsaData;
  380. int ret = WSAStartup(0x0002, &wsaData);
  381. ASSERT_EQ(0, ret);
  382. }
  383. #endif
  384. TEST(DecodePathTest, PercentCharacter) {
  385. EXPECT_EQ(
  386. decode_path_component(
  387. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  388. U8("descrip=Gastos áéíóúñÑ 6"));
  389. }
  390. TEST(DecodePathTest, PercentCharacterNUL) {
  391. string expected;
  392. expected.push_back('x');
  393. expected.push_back('\0');
  394. expected.push_back('x');
  395. EXPECT_EQ(decode_path_component("x%00x"), expected);
  396. }
  397. TEST(DecodePathTest, UnicodeEncoding) {
  398. // %u0041 = 'A' (1-byte UTF-8)
  399. EXPECT_EQ("A", decode_path_component("%u0041"));
  400. // %u00E9 = 'é' (2-byte UTF-8)
  401. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  402. // %u3042 = 'あ' (3-byte UTF-8)
  403. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  404. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  405. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  406. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  407. // neighbours)
  408. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  409. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  410. }
  411. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  412. // A sign or whitespace inside the two-character escape window must not be
  413. // accepted as a valid percent-encoding; the sequence is passed through
  414. // literally, matching decode_uri_component / decode_path_component.
  415. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  416. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  417. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  418. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  419. // Well-formed escapes still decode.
  420. EXPECT_EQ("-", decode_query_component("%2D", false));
  421. EXPECT_EQ("A", decode_query_component("%41", false));
  422. }
  423. TEST(SanitizeFilenameTest, VariousPatterns) {
  424. // Path traversal
  425. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  426. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  427. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  428. // Normal and edge cases
  429. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  430. EXPECT_EQ("filename.txt",
  431. httplib::sanitize_filename("/path/to/filename.txt"));
  432. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  433. EXPECT_EQ("", httplib::sanitize_filename(".."));
  434. EXPECT_EQ("", httplib::sanitize_filename(""));
  435. // Null bytes stripped
  436. EXPECT_EQ("safe.txt",
  437. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  438. // Whitespace-only rejected
  439. EXPECT_EQ("", httplib::sanitize_filename(" "));
  440. }
  441. // Forward declaration (see the base64_encode note below): split builds move the
  442. // definition into httplib.cc, so re-declaring it here lets the test link.
  443. namespace httplib {
  444. namespace detail {
  445. bool is_chunked_transfer_encoding(const Headers &headers);
  446. } // namespace detail
  447. } // namespace httplib
  448. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  449. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  450. auto make = [](std::initializer_list<const char *> lines) {
  451. Headers h;
  452. for (auto te : lines) {
  453. if (te) { h.emplace("Transfer-Encoding", te); }
  454. }
  455. return h;
  456. };
  457. // Sole coding, matched case-insensitively.
  458. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  460. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  461. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  462. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  464. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  465. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  466. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  470. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  471. // were received, into one list. Headers preserves that order, so the answer
  472. // is decided by the last coding of the last line and the order the lines
  473. // arrived in is significant.
  474. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  475. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  477. // The split can fall anywhere in the list.
  478. EXPECT_TRUE(
  479. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  480. EXPECT_FALSE(
  481. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  482. // A trailing line naming no coding leaves the list ending in nothing, so it
  483. // must not inherit the chunked from the line before it.
  484. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  485. }
  486. // Forward declarations (see the base64_encode note below).
  487. namespace httplib {
  488. namespace detail {
  489. bool parse_status_line(const char *line, std::string &version, int &status,
  490. std::string &reason);
  491. std::string file_extension(const std::string &path);
  492. std::string
  493. find_content_type(const std::string &path,
  494. const std::map<std::string, std::string> &user_data,
  495. const std::string &default_content_type);
  496. bool can_compress_content_type(const std::string &content_type);
  497. bool is_prohibited_header_name(const std::string &name);
  498. bool is_valid_path(const std::string &path);
  499. #ifdef CPPHTTPLIB_SSL_ENABLED
  500. bool match_hostname(const std::string &pattern, const std::string &hostname);
  501. #endif
  502. } // namespace detail
  503. } // namespace httplib
  504. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  505. struct {
  506. const char *line;
  507. const char *version;
  508. int status;
  509. const char *reason;
  510. } cases[] = {
  511. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  512. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  513. // The reason phrase may be empty, or left out along with its space.
  514. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  515. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  516. };
  517. for (const auto &c : cases) {
  518. std::string version;
  519. int status = 0;
  520. std::string reason = "unset";
  521. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  522. << c.line;
  523. EXPECT_EQ(c.version, version);
  524. EXPECT_EQ(c.status, status);
  525. EXPECT_EQ(c.reason, reason);
  526. }
  527. }
  528. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  529. const char *lines[] = {
  530. "HTTP/2 200 OK\r\n",
  531. "HTTP/1.2 200 OK\r\n",
  532. "HTTP/1.1 20 OK\r\n",
  533. "HTTP/1.1 2000 OK\r\n",
  534. "HTTP/1.1 2x0 OK\r\n",
  535. "HTTP/1.1 200 OK\r\n",
  536. "HTTP/1.1 200OK\r\n",
  537. "HTTP/1.1 200 O\rK\r\n",
  538. "HTTP/1.1 200 OK",
  539. "HTTP/1.1 200 OK\r\nX",
  540. "",
  541. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  542. "HTTP/1.1 200 OK\n",
  543. #endif
  544. };
  545. for (auto line : lines) {
  546. std::string version;
  547. int status = 0;
  548. std::string reason;
  549. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  550. << line;
  551. }
  552. }
  553. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  554. // Long enough to overflow the stack when matched with std::regex.
  555. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  556. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  557. std::string version;
  558. int status = 0;
  559. std::string reason;
  560. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  561. EXPECT_EQ(200, status);
  562. EXPECT_EQ(long_reason, reason);
  563. }
  564. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  565. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  566. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  567. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  568. EXPECT_EQ("", detail::file_extension("noext"));
  569. EXPECT_EQ("", detail::file_extension("a."));
  570. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  571. EXPECT_EQ("", detail::file_extension("a.b-c"));
  572. // Long enough to overflow the stack when matched with std::regex.
  573. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  574. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  575. }
  576. #ifdef CPPHTTPLIB_SSL_ENABLED
  577. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  578. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  579. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  580. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  581. // A wildcard needs two labels after it, in the leftmost label only
  582. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  583. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  584. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  585. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  586. EXPECT_FALSE(
  587. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  588. // No name may have an empty label
  589. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  590. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  591. }
  592. #endif
  593. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  594. detail::case_ignore::hash hash;
  595. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  596. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  597. // Long enough to overflow the stack if hashed one call per character.
  598. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  599. }
  600. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  601. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  602. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  603. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  604. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  605. // Same 26-bit hash as html, svg and js.
  606. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  607. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  608. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  609. }
  610. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  611. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  612. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  613. }
  614. }
  615. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  616. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  617. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  618. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  619. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  620. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  621. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  622. // Same 26-bit hash as application/json.
  623. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  624. }
  625. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  626. Request req;
  627. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  628. EXPECT_TRUE(req.is_multipart_form_data());
  629. std::string boundary;
  630. EXPECT_TRUE(detail::parse_multipart_boundary(
  631. req.get_header_value("Content-Type"), boundary));
  632. EXPECT_EQ("x", boundary);
  633. }
  634. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  635. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  636. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  637. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  638. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  639. // Same 26-bit hash as REMOTE_ADDR.
  640. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  641. }
  642. // Forward declaration: in split builds split.py strips `inline` and moves the
  643. // definition into httplib.cc, so detail::base64_encode is not visible from the
  644. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  645. // in both header-only and split builds.
  646. namespace httplib {
  647. namespace detail {
  648. std::string base64_encode(const std::string &in);
  649. } // namespace detail
  650. } // namespace httplib
  651. TEST(Base64EncodeTest, KnownAnswers) {
  652. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  653. // where the accumulator's top bit is already set before the next shift.
  654. EXPECT_EQ("", detail::base64_encode(""));
  655. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  656. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  657. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  658. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  659. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  660. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  661. // High bytes keep the top bit set across several rounds.
  662. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  663. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  664. }
  665. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  666. string unescapedCharacters = "-_.!~*'()";
  667. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  668. }
  669. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  670. string reservedCharacters = ";,/?:@&=+$";
  671. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  672. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  673. }
  674. TEST(ClientQueryOrder, PreserveOrder) {
  675. // This test reproduces Issue #2259: client may reorder query parameters
  676. // when sending a GET request. The expected behavior is that the client
  677. // preserves the original query string order when the caller supplied it
  678. // as part of the path.
  679. Server svr;
  680. svr.Get("/", [&](const Request &req, Response &res) {
  681. // Echo back the raw target so the test can assert ordering
  682. res.set_content(req.target, "text/plain");
  683. });
  684. std::thread t{[&] { svr.listen(HOST, PORT); }};
  685. auto se = detail::scope_exit([&] {
  686. svr.stop();
  687. t.join();
  688. ASSERT_FALSE(svr.is_running());
  689. });
  690. svr.wait_until_ready();
  691. Client cli(HOST, PORT);
  692. ASSERT_TRUE(cli.is_valid());
  693. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  694. auto res = cli.Get(original);
  695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  696. // Expect the echoed target to exactly match the original path (order
  697. // preserved)
  698. EXPECT_EQ(res->body, original);
  699. }
  700. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  701. string chineseCharacters = U8("中国語");
  702. string russianCharacters = U8("дом");
  703. string brazilianCharacters = U8("óculos");
  704. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  705. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  706. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  707. "%D0%B4%D0%BE%D0%BC");
  708. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  709. }
  710. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  711. string unescapedCharacters = "-_.!~*'()";
  712. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  713. }
  714. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  715. string reservedCharacters = ";,/?:@&=+$";
  716. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  717. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  718. }
  719. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  720. string chineseCharacters = U8("中国語");
  721. string russianCharacters = U8("дом");
  722. string brazilianCharacters = U8("óculos");
  723. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  724. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  725. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  726. "%D0%B4%D0%BE%D0%BC");
  727. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  728. }
  729. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  730. // Issue #2082 use case: encoding path component with ampersand
  731. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  732. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  733. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  734. }
  735. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  736. string unescapedCharacters = "-_.!~*'()";
  737. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  738. }
  739. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  740. string reservedCharacters = ";,/?:@&=+$#";
  741. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  742. }
  743. TEST(EncodeUriTest, TestUTF8Characters) {
  744. string chineseCharacters = U8("中国語");
  745. string russianCharacters = U8("дом");
  746. string brazilianCharacters = U8("óculos");
  747. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  748. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  749. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  750. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  751. }
  752. TEST(EncodeUriTest, TestCompleteUri) {
  753. string uri =
  754. "https://example.com/path/to/resource?query=value&param=test#fragment";
  755. EXPECT_EQ(
  756. httplib::encode_uri(uri),
  757. "https://example.com/path/to/resource?query=value&param=test#fragment");
  758. }
  759. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  760. string uri =
  761. "https://example.com/path with spaces/file name.html?q=hello world";
  762. EXPECT_EQ(httplib::encode_uri(uri),
  763. "https://example.com/path%20with%20spaces/"
  764. "file%20name.html?q=hello%20world");
  765. }
  766. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  767. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  768. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  769. }
  770. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'()";
  772. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  773. }
  774. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  775. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  776. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  777. string encodedBrazilian = "%C3%B3culos";
  778. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  779. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  780. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  781. }
  782. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  783. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  784. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  785. "Piri Tommy Villiers - on & on");
  786. }
  787. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  788. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  789. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  790. }
  791. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  792. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  793. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  794. }
  795. TEST(DecodeUriTest, TestUTF8Characters) {
  796. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  797. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  798. string encodedBrazilian = "%C3%B3culos";
  799. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  800. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  801. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  802. }
  803. TEST(DecodeUriTest, TestCompleteUri) {
  804. string encodedUri = "https://example.com/path%20with%20spaces/"
  805. "file%20name.html?q=hello%20world";
  806. EXPECT_EQ(
  807. httplib::decode_uri(encodedUri),
  808. "https://example.com/path with spaces/file name.html?q=hello world");
  809. }
  810. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  811. string original =
  812. "https://example.com/path with spaces/file name.html?q=hello world";
  813. string encoded = httplib::encode_uri(original);
  814. string decoded = httplib::decode_uri(encoded);
  815. EXPECT_EQ(decoded, original);
  816. }
  817. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  818. // decode_uri is the inverse of encode_uri: an escaped reserved character
  819. // stays encoded so it is not promoted into a real delimiter, while
  820. // non-reserved escapes still decode (like JS decodeURI).
  821. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  822. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  823. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  824. "%3F%3A%40%26%3D%2B%24%2C%3B");
  825. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  826. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  827. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  828. "http://example.com/a%2Fb");
  829. // decode_uri_component still decodes the reserved character.
  830. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  831. }
  832. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  833. string original = "Piri Tommy Villiers - on & on";
  834. string encoded = httplib::encode_uri_component(original);
  835. string decoded = httplib::decode_uri_component(encoded);
  836. EXPECT_EQ(decoded, original);
  837. }
  838. TEST(TrimTests, TrimStringTests) {
  839. EXPECT_EQ("abc", detail::trim_copy("abc"));
  840. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  841. EXPECT_TRUE(detail::trim_copy("").empty());
  842. }
  843. TEST(AsciiTest, LocaleIndependentClassification) {
  844. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  845. // which consult the global C locale: std::isalnum(0xC5) can return true
  846. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  847. // helpers must classify every byte by the ASCII grammar alone.
  848. for (int i = 0; i < 256; i++) {
  849. auto c = static_cast<char>(i);
  850. auto is_digit = i >= '0' && i <= '9';
  851. auto is_upper = i >= 'A' && i <= 'Z';
  852. auto is_lower = i >= 'a' && i <= 'z';
  853. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  854. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  855. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  856. << "byte " << i;
  857. }
  858. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  859. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  860. // Non-ASCII bytes must be percent-encoded, never passed through as
  861. // alphanumeric.
  862. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  863. }
  864. TEST(FromCharsTest, Double) {
  865. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  866. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  867. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  868. auto parse = [](const std::string &s, double &v) {
  869. return detail::from_chars(s.data(), s.data() + s.size(), v);
  870. };
  871. double v = -1.0;
  872. // Representative quality values.
  873. EXPECT_EQ(parse("0", v).ec, std::errc{});
  874. EXPECT_DOUBLE_EQ(v, 0.0);
  875. EXPECT_EQ(parse("1", v).ec, std::errc{});
  876. EXPECT_DOUBLE_EQ(v, 1.0);
  877. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.8);
  879. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  880. EXPECT_DOUBLE_EQ(v, 0.001);
  881. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  882. EXPECT_DOUBLE_EQ(v, 1.0);
  883. // A missing integer or fractional part is tolerated.
  884. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  885. EXPECT_DOUBLE_EQ(v, 0.5);
  886. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 5.0);
  888. // Values outside [0, 1] still parse; the caller range-checks them.
  889. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  890. EXPECT_DOUBLE_EQ(v, 123.456);
  891. // Stops at the first byte that is not part of the number and reports where.
  892. std::string trailing = "0.9, text/html";
  893. auto r = parse(trailing, v);
  894. EXPECT_EQ(r.ec, std::errc{});
  895. EXPECT_DOUBLE_EQ(v, 0.9);
  896. EXPECT_EQ(*r.ptr, ',');
  897. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  898. // outright, and an 'e'/'E' simply ends the number.
  899. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  900. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  901. std::string exp_input = "1.5e3";
  902. r = parse(exp_input, v);
  903. EXPECT_EQ(r.ec, std::errc{});
  904. EXPECT_DOUBLE_EQ(v, 1.5);
  905. EXPECT_EQ(*r.ptr, 'e');
  906. // Invalid inputs.
  907. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  908. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  909. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  910. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  911. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  912. // Pathological but well-formed inputs must stay bounded (no overflow, no
  913. // out-of-bounds table access) and stay within [0, 1] for the caller.
  914. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  915. std::errc{});
  916. EXPECT_DOUBLE_EQ(v, 0.0);
  917. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  918. std::errc{});
  919. EXPECT_GE(v, 0.0);
  920. EXPECT_LE(v, 1.0);
  921. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  922. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  923. }
  924. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  925. // Simple case without quality values
  926. std::vector<std::string> result1;
  927. EXPECT_TRUE(detail::parse_accept_header(
  928. "text/html,application/json,text/plain", result1));
  929. EXPECT_EQ(result1.size(), 3U);
  930. EXPECT_EQ(result1[0], "text/html");
  931. EXPECT_EQ(result1[1], "application/json");
  932. EXPECT_EQ(result1[2], "text/plain");
  933. // With quality values
  934. std::vector<std::string> result2;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  937. EXPECT_EQ(result2.size(), 3U);
  938. EXPECT_EQ(result2[0], "application/json"); // highest q value
  939. EXPECT_EQ(result2[1], "text/html");
  940. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  941. }
  942. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  943. // Mixed with and without quality values
  944. std::vector<std::string> result;
  945. EXPECT_TRUE(detail::parse_accept_header(
  946. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  947. EXPECT_EQ(result.size(), 3U);
  948. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  949. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  950. EXPECT_EQ(result[2], "application/json"); // q=0.5
  951. }
  952. TEST(ParseAcceptHeaderTest, EdgeCases) {
  953. // Empty header
  954. std::vector<std::string> empty_result;
  955. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  956. EXPECT_TRUE(empty_result.empty());
  957. // Single type
  958. std::vector<std::string> single_result;
  959. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  960. EXPECT_EQ(single_result.size(), 1U);
  961. EXPECT_EQ(single_result[0], "application/json");
  962. // Wildcard types
  963. std::vector<std::string> wildcard_result;
  964. EXPECT_TRUE(detail::parse_accept_header(
  965. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  966. EXPECT_EQ(wildcard_result.size(), 3U);
  967. EXPECT_EQ(wildcard_result[0], "application/json");
  968. EXPECT_EQ(wildcard_result[1], "text/*");
  969. EXPECT_EQ(wildcard_result[2], "*/*");
  970. }
  971. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  972. // Common browser Accept header
  973. std::vector<std::string> browser_result;
  974. EXPECT_TRUE(
  975. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  976. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  977. browser_result));
  978. EXPECT_EQ(browser_result.size(), 6U);
  979. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  980. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  981. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  982. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  983. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  984. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  985. // API client header
  986. std::vector<std::string> api_result;
  987. EXPECT_TRUE(detail::parse_accept_header(
  988. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  989. api_result));
  990. EXPECT_EQ(api_result.size(), 3U);
  991. EXPECT_EQ(api_result[0], "application/json");
  992. EXPECT_EQ(api_result[1], "application/xml");
  993. EXPECT_EQ(api_result[2], "text/plain");
  994. }
  995. TEST(ParseAcceptHeaderTest, SpecialCases) {
  996. // Quality value with 3 decimal places
  997. std::vector<std::string> decimal_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1000. EXPECT_EQ(decimal_result.size(), 2U);
  1001. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1002. EXPECT_EQ(decimal_result[1], "text/html");
  1003. // Zero quality (should still be included but with lowest priority)
  1004. std::vector<std::string> zero_q_result;
  1005. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1006. zero_q_result));
  1007. EXPECT_EQ(zero_q_result.size(), 2U);
  1008. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1009. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1010. // No spaces around commas
  1011. std::vector<std::string> no_space_result;
  1012. EXPECT_TRUE(detail::parse_accept_header(
  1013. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1014. no_space_result));
  1015. EXPECT_EQ(no_space_result.size(), 3U);
  1016. EXPECT_EQ(no_space_result[0], "text/html");
  1017. EXPECT_EQ(no_space_result[1], "application/json");
  1018. EXPECT_EQ(no_space_result[2], "text/plain");
  1019. }
  1020. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1021. // Quality values always use '.' as the decimal separator, so parsing must
  1022. // not depend on the process locale. An embedding application may have
  1023. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1024. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1025. std::string saved = cur ? cur : "C";
  1026. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1027. "fr_FR.UTF-8"};
  1028. bool switched = false;
  1029. for (const auto loc : comma_locales) {
  1030. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1031. std::localeconv()->decimal_point[0] == ',') {
  1032. switched = true;
  1033. break;
  1034. }
  1035. }
  1036. if (!switched) {
  1037. std::setlocale(LC_NUMERIC, saved.c_str());
  1038. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1039. }
  1040. // The higher-weighted type appears later in the list, so a correct parse
  1041. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1042. // sensitive parse reads both weights as 0 and leaves the original order.
  1043. std::vector<std::string> result;
  1044. EXPECT_TRUE(detail::parse_accept_header(
  1045. "application/json;q=0.1,text/html;q=0.9", result));
  1046. ASSERT_EQ(result.size(), 2U);
  1047. EXPECT_EQ(result[0], "text/html");
  1048. EXPECT_EQ(result[1], "application/json");
  1049. std::setlocale(LC_NUMERIC, saved.c_str());
  1050. }
  1051. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1052. std::vector<std::string> result;
  1053. // Invalid quality value (> 1.0)
  1054. EXPECT_FALSE(
  1055. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1056. // Invalid quality value (< 0.0)
  1057. EXPECT_FALSE(
  1058. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1059. // Invalid quality value (not a number)
  1060. EXPECT_FALSE(detail::parse_accept_header(
  1061. "text/html;q=invalid,application/json", result));
  1062. // A valid numeric prefix does not make the entire quality value valid.
  1063. EXPECT_FALSE(detail::parse_accept_header(
  1064. "text/html;q=0.5junk,application/json", result));
  1065. // Empty quality value
  1066. EXPECT_FALSE(
  1067. detail::parse_accept_header("text/html;q=,application/json", result));
  1068. // Invalid media type format (no slash and not wildcard)
  1069. EXPECT_FALSE(
  1070. detail::parse_accept_header("invalidtype,application/json", result));
  1071. // Valid cases should still work
  1072. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1073. EXPECT_EQ(result.size(), 1U);
  1074. EXPECT_EQ(result[0], "*/*");
  1075. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1076. EXPECT_EQ(result.size(), 1U);
  1077. EXPECT_EQ(result[0], "*");
  1078. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1079. EXPECT_EQ(result.size(), 1U);
  1080. EXPECT_EQ(result[0], "text/*");
  1081. }
  1082. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1083. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1084. // and must not be answered with 400 Bad Request.
  1085. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1086. struct {
  1087. const char *value;
  1088. std::vector<std::string> expected;
  1089. } cases[] = {
  1090. {",application/json", {"application/json"}},
  1091. {"text/html,", {"text/html"}},
  1092. {"text/html,,*/*", {"text/html", "*/*"}},
  1093. // An empty element may be spelled with whitespace in it
  1094. {"text/html, , application/json", {"text/html", "application/json"}},
  1095. // Nothing but empty elements is an empty list, which means the same
  1096. // thing as no Accept header at all
  1097. {",,,", {}},
  1098. // Quality values still apply across ignored empty elements
  1099. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1100. };
  1101. for (const auto &c : cases) {
  1102. std::vector<std::string> result;
  1103. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1104. << "value: " << c.value;
  1105. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1106. }
  1107. // An invalid entry is still rejected when empty elements surround it
  1108. std::vector<std::string> result;
  1109. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1110. }
  1111. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1112. // or ';' inside one does not end the list element or the parameter. Section
  1113. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1114. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1115. struct {
  1116. const char *value;
  1117. std::vector<std::string> expected;
  1118. } cases[] = {
  1119. {"text/html;profile=\"a,b\",application/json",
  1120. {"text/html", "application/json"}},
  1121. // A "q=" inside a quoted value is not the weight
  1122. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1123. {"text/html", "application/json"}},
  1124. // The weight after a quoted value still applies
  1125. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1126. {"application/json", "text/html"}},
  1127. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1128. {"application/json", "text/html"}},
  1129. {"text/html;profile=\"a\\\"b\",application/json",
  1130. {"text/html", "application/json"}},
  1131. // An escaped backslash does not escape the '"' after it
  1132. {"text/html;profile=\"a\\\\\",application/json",
  1133. {"text/html", "application/json"}},
  1134. };
  1135. for (const auto &c : cases) {
  1136. std::vector<std::string> result;
  1137. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1138. << "value: " << c.value;
  1139. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1140. }
  1141. }
  1142. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1143. Server svr;
  1144. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1145. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1146. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1147. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1148. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1149. res.set_content("ok", "text/plain");
  1150. });
  1151. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1152. EXPECT_TRUE(false);
  1153. res.set_content("bad request", "text/plain");
  1154. });
  1155. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1156. auto se = detail::scope_exit([&] {
  1157. svr.stop();
  1158. listen_thread.join();
  1159. ASSERT_FALSE(svr.is_running());
  1160. });
  1161. svr.wait_until_ready();
  1162. Client cli("localhost", PORT);
  1163. {
  1164. auto res = cli.Get(
  1165. "/accept_ok",
  1166. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1168. EXPECT_EQ(StatusCode::OK_200, res->status);
  1169. }
  1170. {
  1171. auto res = cli.Get("/accept_bad_request",
  1172. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1174. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1175. }
  1176. }
  1177. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1178. Server svr;
  1179. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1180. res.set_content("ok", "text/plain");
  1181. });
  1182. std::atomic<int> start_count{0};
  1183. std::atomic<bool> running_when_called{false};
  1184. svr.set_start_handler([&]() {
  1185. running_when_called = svr.is_running();
  1186. start_count++;
  1187. });
  1188. auto port = svr.bind_to_any_port(HOST);
  1189. std::thread t([&]() { svr.listen_after_bind(); });
  1190. auto se = detail::scope_exit([&] {
  1191. svr.stop();
  1192. t.join();
  1193. ASSERT_FALSE(svr.is_running());
  1194. });
  1195. svr.wait_until_ready();
  1196. // A successful request proves the accept loop is running, which the start
  1197. // handler precedes; so by now the handler must have run exactly once.
  1198. Client cli(HOST, port);
  1199. cli.set_connection_timeout(std::chrono::seconds(5));
  1200. auto res = cli.Get("/");
  1201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1202. EXPECT_EQ(StatusCode::OK_200, res->status);
  1203. EXPECT_EQ(1, start_count.load());
  1204. EXPECT_TRUE(running_when_called.load());
  1205. }
  1206. TEST(DivideTest, DivideStringTests) {
  1207. auto divide = [](const std::string &str, char d) {
  1208. std::string lhs;
  1209. std::string rhs;
  1210. detail::divide(str, d,
  1211. [&](const char *lhs_data, std::size_t lhs_size,
  1212. const char *rhs_data, std::size_t rhs_size) {
  1213. lhs.assign(lhs_data, lhs_size);
  1214. rhs.assign(rhs_data, rhs_size);
  1215. });
  1216. return std::make_pair(std::move(lhs), std::move(rhs));
  1217. };
  1218. {
  1219. const auto res = divide("", '=');
  1220. EXPECT_EQ(res.first, "");
  1221. EXPECT_EQ(res.second, "");
  1222. }
  1223. {
  1224. const auto res = divide("=", '=');
  1225. EXPECT_EQ(res.first, "");
  1226. EXPECT_EQ(res.second, "");
  1227. }
  1228. {
  1229. const auto res = divide(" ", '=');
  1230. EXPECT_EQ(res.first, " ");
  1231. EXPECT_EQ(res.second, "");
  1232. }
  1233. {
  1234. const auto res = divide("a", '=');
  1235. EXPECT_EQ(res.first, "a");
  1236. EXPECT_EQ(res.second, "");
  1237. }
  1238. {
  1239. const auto res = divide("a=", '=');
  1240. EXPECT_EQ(res.first, "a");
  1241. EXPECT_EQ(res.second, "");
  1242. }
  1243. {
  1244. const auto res = divide("=b", '=');
  1245. EXPECT_EQ(res.first, "");
  1246. EXPECT_EQ(res.second, "b");
  1247. }
  1248. {
  1249. const auto res = divide("a=b", '=');
  1250. EXPECT_EQ(res.first, "a");
  1251. EXPECT_EQ(res.second, "b");
  1252. }
  1253. {
  1254. const auto res = divide("a=b=", '=');
  1255. EXPECT_EQ(res.first, "a");
  1256. EXPECT_EQ(res.second, "b=");
  1257. }
  1258. {
  1259. const auto res = divide("a=b=c", '=');
  1260. EXPECT_EQ(res.first, "a");
  1261. EXPECT_EQ(res.second, "b=c");
  1262. }
  1263. }
  1264. TEST(SplitTest, ParseQueryString) {
  1265. string s = "key1=val1&key2=val2&key3=val3";
  1266. Params dic;
  1267. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1268. [&](const char *b, const char *e) {
  1269. string key, val;
  1270. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1271. if (key.empty()) {
  1272. key.assign(b2, e2);
  1273. } else {
  1274. val.assign(b2, e2);
  1275. }
  1276. });
  1277. dic.emplace(key, val);
  1278. });
  1279. EXPECT_EQ("val1", dic.find("key1")->second);
  1280. EXPECT_EQ("val2", dic.find("key2")->second);
  1281. EXPECT_EQ("val3", dic.find("key3")->second);
  1282. }
  1283. TEST(SplitTest, ParseInvalidQueryTests) {
  1284. {
  1285. string s = " ";
  1286. Params dict;
  1287. detail::parse_query_text(s, dict);
  1288. EXPECT_TRUE(dict.empty());
  1289. }
  1290. {
  1291. string s = " = =";
  1292. Params dict;
  1293. detail::parse_query_text(s, dict);
  1294. EXPECT_TRUE(dict.empty());
  1295. }
  1296. }
  1297. TEST(ParseQueryTest, ParseQueryString) {
  1298. {
  1299. std::string s = "key1=val1&key2=val2&key3=val3";
  1300. Params dic;
  1301. detail::parse_query_text(s, dic);
  1302. EXPECT_EQ("val1", dic.find("key1")->second);
  1303. EXPECT_EQ("val2", dic.find("key2")->second);
  1304. EXPECT_EQ("val3", dic.find("key3")->second);
  1305. }
  1306. {
  1307. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1308. Params dic;
  1309. detail::parse_query_text(s, dic);
  1310. EXPECT_EQ("", dic.find("key1")->second);
  1311. EXPECT_EQ("val1", dic.find("key2")->second);
  1312. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1313. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1314. }
  1315. }
  1316. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1317. Params dic;
  1318. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1319. dic.emplace("key1", "val1");
  1320. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1321. dic.emplace("key2", "val2");
  1322. dic.emplace("key3", "val3");
  1323. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1324. }
  1325. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1326. Params params;
  1327. params.emplace("a", "1");
  1328. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1329. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1330. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1331. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1332. // Long enough to overflow the stack when matched with std::regex.
  1333. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1334. EXPECT_EQ("/p?" + long_query + "&a=1",
  1335. append_query_params("/p?" + long_query, params));
  1336. }
  1337. // Joins every entry of a Headers or Params into "key=value " so a whole
  1338. // traversal can be compared in one assertion. Both are instantiations of the
  1339. // same insertion-ordered container, so one helper serves both.
  1340. template <typename Map> static std::string entries_to_string(const Map &m) {
  1341. std::string s;
  1342. for (const auto &entry : m) {
  1343. s += entry.first + "=" + entry.second + " ";
  1344. }
  1345. return s;
  1346. }
  1347. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1348. // Params used to be a std::multimap, which sorted by name and handed the
  1349. // caller's query back alphabetised. A client signing its query string could
  1350. // not reproduce the order it asked for.
  1351. Params dic;
  1352. dic.emplace("zulu", "1");
  1353. dic.emplace("alpha", "2");
  1354. dic.emplace("mike", "3");
  1355. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1356. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1357. }
  1358. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1359. Params dic;
  1360. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1361. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1362. }
  1363. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1364. Request req;
  1365. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1366. req.params);
  1367. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1368. EXPECT_EQ("first", req.get_param_value("tag"));
  1369. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1370. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1371. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1372. EXPECT_EQ("", req.get_param_value("tag", 3));
  1373. }
  1374. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1375. // Params shares its container with Headers, which matches field names
  1376. // case-insensitively. Parameter names must not pick that up.
  1377. Params dic;
  1378. dic.emplace("Key", "upper");
  1379. dic.emplace("key", "lower");
  1380. EXPECT_EQ(2U, dic.size());
  1381. EXPECT_EQ(1U, dic.count("Key"));
  1382. EXPECT_EQ(1U, dic.count("key"));
  1383. EXPECT_EQ("upper", dic.find("Key")->second);
  1384. EXPECT_EQ("lower", dic.find("key")->second);
  1385. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1386. }
  1387. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1388. Server svr;
  1389. std::string order;
  1390. svr.Get("/order", [&](const Request &req, Response &res) {
  1391. order = entries_to_string(req.params);
  1392. res.set_content("ok", "text/plain");
  1393. });
  1394. auto port = svr.bind_to_any_port(HOST);
  1395. thread t = thread([&] { svr.listen_after_bind(); });
  1396. auto se = detail::scope_exit([&] {
  1397. svr.stop();
  1398. t.join();
  1399. ASSERT_FALSE(svr.is_running());
  1400. });
  1401. svr.wait_until_ready();
  1402. Client cli(HOST, port);
  1403. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1404. ASSERT_TRUE(res);
  1405. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1406. }
  1407. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1408. Server svr;
  1409. std::string field_order, file_order;
  1410. svr.Post("/order", [&](const Request &req, Response &res) {
  1411. for (const auto &field : req.form.fields) {
  1412. field_order += field.first + "=" + field.second.content + " ";
  1413. }
  1414. for (const auto &file : req.form.files) {
  1415. file_order += file.first + "=" + file.second.filename + " ";
  1416. }
  1417. res.set_content("ok", "text/plain");
  1418. });
  1419. auto port = svr.bind_to_any_port(HOST);
  1420. thread t = thread([&] { svr.listen_after_bind(); });
  1421. auto se = detail::scope_exit([&] {
  1422. svr.stop();
  1423. t.join();
  1424. ASSERT_FALSE(svr.is_running());
  1425. });
  1426. svr.wait_until_ready();
  1427. UploadFormDataItems items = {
  1428. {"zulu", "1", "", ""},
  1429. {"alpha", "2", "", ""},
  1430. {"mike", "3", "", ""},
  1431. {"zebra", "z", "z.txt", "text/plain"},
  1432. {"apple", "a", "a.txt", "text/plain"},
  1433. };
  1434. Client cli(HOST, port);
  1435. auto res = cli.Post("/order", items);
  1436. ASSERT_TRUE(res);
  1437. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1438. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1439. }
  1440. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1441. Server svr;
  1442. std::vector<std::string> values;
  1443. std::string first, second, out_of_range, order;
  1444. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1445. values = req.form.get_fields("tag");
  1446. first = req.form.get_field("tag", 0);
  1447. second = req.form.get_field("tag", 1);
  1448. out_of_range = req.form.get_field("tag", 2);
  1449. for (const auto &field : req.form.fields) {
  1450. order += field.first + "=" + field.second.content + " ";
  1451. }
  1452. res.set_content("ok", "text/plain");
  1453. });
  1454. auto port = svr.bind_to_any_port(HOST);
  1455. thread t = thread([&] { svr.listen_after_bind(); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. t.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1463. // not adjacent in the container.
  1464. UploadFormDataItems items = {
  1465. {"tag", "first", "", ""},
  1466. {"other", "x", "", ""},
  1467. {"tag", "second", "", ""},
  1468. };
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/repeated", items);
  1471. ASSERT_TRUE(res);
  1472. ASSERT_EQ(2U, values.size());
  1473. EXPECT_EQ("first", values[0]);
  1474. EXPECT_EQ("second", values[1]);
  1475. EXPECT_EQ("first", first);
  1476. EXPECT_EQ("second", second);
  1477. // std::multimap already kept entries sharing a name in insertion order, so
  1478. // everything above passes without this change too. The whole traversal is
  1479. // what tells the two apart: sorting by name would hoist "other" to the front
  1480. // and the two "tag" parts would end up adjacent.
  1481. EXPECT_EQ("tag=first other=x tag=second ", order);
  1482. // Advancing past the last entry of a name used to run off the container;
  1483. // the container's saturating increment makes it return the default instead.
  1484. EXPECT_EQ("", out_of_range);
  1485. }
  1486. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1487. Server svr;
  1488. std::string file_names;
  1489. svr.Post("/upload", [&](const Request &req, Response &res) {
  1490. for (const auto &file : req.form.files) {
  1491. file_names += file.first + "|" + file.second.filename + " ";
  1492. }
  1493. res.set_content("ok", "text/plain");
  1494. });
  1495. auto port = svr.bind_to_any_port(HOST);
  1496. thread t = thread([&] { svr.listen_after_bind(); });
  1497. auto se = detail::scope_exit([&] {
  1498. svr.stop();
  1499. t.join();
  1500. ASSERT_FALSE(svr.is_running());
  1501. });
  1502. svr.wait_until_ready();
  1503. // A trailing backslash would otherwise escape the closing quote.
  1504. UploadFormDataItems items = {
  1505. {"dir\\", "x", "a.txt", "text/plain"},
  1506. {"b", "y", "a\\\\b.txt", "text/plain"},
  1507. };
  1508. Client cli(HOST, port);
  1509. auto res = cli.Post("/upload", items);
  1510. ASSERT_TRUE(res);
  1511. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1512. }
  1513. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1514. // Server::read_content() keeps a FormFields::iterator alive across the
  1515. // content callbacks that fill the part it points at. The container is
  1516. // vector-backed, so a later emplace can reallocate and invalidate an older
  1517. // iterator; 64 parts grow the vector through seven reallocations, which
  1518. // checks that every part's content still lands in its own entry.
  1519. const size_t part_count = 64;
  1520. // One formula for both the parts sent and the values expected back, so the
  1521. // two cannot drift apart.
  1522. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1523. auto content_of = [](size_t i) {
  1524. return std::string(64, static_cast<char>('a' + (i % 26)));
  1525. };
  1526. Server svr;
  1527. std::vector<std::pair<std::string, std::string>> received;
  1528. svr.Post("/many", [&](const Request &req, Response &res) {
  1529. for (const auto &field : req.form.fields) {
  1530. received.emplace_back(field.first, field.second.content);
  1531. }
  1532. res.set_content("ok", "text/plain");
  1533. });
  1534. auto port = svr.bind_to_any_port(HOST);
  1535. thread t = thread([&] { svr.listen_after_bind(); });
  1536. auto se = detail::scope_exit([&] {
  1537. svr.stop();
  1538. t.join();
  1539. ASSERT_FALSE(svr.is_running());
  1540. });
  1541. svr.wait_until_ready();
  1542. UploadFormDataItems items;
  1543. for (size_t i = 0; i < part_count; i++) {
  1544. items.push_back({name_of(i), content_of(i), "", ""});
  1545. }
  1546. Client cli(HOST, port);
  1547. auto res = cli.Post("/many", items);
  1548. ASSERT_TRUE(res);
  1549. ASSERT_EQ(part_count, received.size());
  1550. for (size_t i = 0; i < part_count; i++) {
  1551. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1552. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1553. }
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1556. string content_type = "multipart/form-data; boundary=something";
  1557. string boundary;
  1558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1559. EXPECT_TRUE(ret);
  1560. EXPECT_EQ(boundary, "something");
  1561. }
  1562. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1563. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1564. string boundary;
  1565. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1566. EXPECT_TRUE(ret);
  1567. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1568. }
  1569. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1570. string content_type =
  1571. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1572. string boundary;
  1573. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1574. EXPECT_TRUE(ret);
  1575. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1576. }
  1577. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1578. string content_type =
  1579. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1580. string boundary;
  1581. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1582. EXPECT_TRUE(ret);
  1583. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1584. }
  1585. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1586. const string boundary(70, 'a');
  1587. string content_type = "multipart/form-data; boundary=" + boundary;
  1588. string parsed;
  1589. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1590. EXPECT_TRUE(ret);
  1591. EXPECT_EQ(parsed, boundary);
  1592. }
  1593. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1594. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1595. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1596. string parsed;
  1597. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1598. EXPECT_FALSE(ret);
  1599. }
  1600. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1601. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1602. // is 72 characters on the wire and still valid.
  1603. const string boundary(70, 'a');
  1604. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1605. string parsed;
  1606. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1607. EXPECT_EQ(parsed, boundary);
  1608. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1609. parsed.clear();
  1610. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1611. }
  1612. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1613. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1614. // The parameter parser must not treat that '=' as the key/value separator.
  1615. string content_type =
  1616. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1617. "charset=UTF-8";
  1618. string parsed;
  1619. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1620. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1621. }
  1622. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1623. // A ';' inside the quoted-string is part of the value, not a parameter
  1624. // separator, so it must not truncate the boundary.
  1625. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1626. string parsed;
  1627. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1628. EXPECT_EQ(parsed, "a;b");
  1629. }
  1630. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1631. string parsed;
  1632. EXPECT_TRUE(detail::parse_multipart_boundary(
  1633. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1634. EXPECT_EQ("a\\b", parsed);
  1635. EXPECT_TRUE(detail::parse_multipart_boundary(
  1636. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1637. EXPECT_EQ("a\"b", parsed);
  1638. }
  1639. TEST(ParseDispositionParamsTest, QuotedValues) {
  1640. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1641. // ';' and '=' are ordinary characters inside one.
  1642. struct {
  1643. const char *value;
  1644. std::vector<std::pair<const char *, const char *>> expected;
  1645. } cases[] = {
  1646. {"name=\"file1\"; filename=\"a.txt\"",
  1647. {{"name", "file1"}, {"filename", "a.txt"}}},
  1648. // Whitespace around '=' and ';' is still trimmed
  1649. {"name=\"file2\" ;filename = \"a.html\"",
  1650. {{"name", "file2"}, {"filename", "a.html"}}},
  1651. // '=' inside the value used to leave only the text after the last one
  1652. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1653. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1654. {"name=\"x=y\"", {{"name", "x=y"}}},
  1655. // ';' inside the value used to truncate the pair and leave a bogus one
  1656. {"name=\"file3\"; filename=\"a;b.txt\"",
  1657. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1658. // An unquoted value keeps working, and so does filename*
  1659. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1660. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1661. // A parameter with no key is dropped rather than turned into one whose
  1662. // key is the value
  1663. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1664. // An escaped quote does not end the value
  1665. {"name=\"a\\\"; filename=evil.php\"",
  1666. {{"name", "a\"; filename=evil.php"}}},
  1667. // Other backslashes, as in a Windows path, are kept
  1668. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1669. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1670. };
  1671. for (const auto &c : cases) {
  1672. Params params;
  1673. detail::parse_disposition_params(c.value, params);
  1674. for (const auto &kv : c.expected) {
  1675. auto it = params.find(kv.first);
  1676. ASSERT_NE(it, params.end())
  1677. << "value: " << c.value << ", key: " << kv.first;
  1678. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1679. }
  1680. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1681. }
  1682. }
  1683. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1684. Server svr;
  1685. std::string filename;
  1686. std::string content;
  1687. svr.Post("/upload", [&](const Request &req, Response &) {
  1688. const auto &file = req.form.get_file("file");
  1689. filename = file.filename;
  1690. content = file.content;
  1691. });
  1692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1693. auto se = detail::scope_exit([&] {
  1694. svr.stop();
  1695. thread.join();
  1696. ASSERT_FALSE(svr.is_running());
  1697. });
  1698. svr.wait_until_ready();
  1699. std::string body = "--B\r\n"
  1700. "Content-Disposition: form-data; name=\"file\"; "
  1701. "filename=\"a.txt\"\r\n"
  1702. "Content-Type: text/plain\r\n"
  1703. "\r\n"
  1704. "hello\r\n"
  1705. "--B--\r\n";
  1706. Client cli(HOST, PORT);
  1707. auto res = cli.Post(
  1708. "/upload",
  1709. [&](size_t offset, DataSink &sink) {
  1710. if (offset < body.size()) {
  1711. sink.write(&body[offset], 1);
  1712. } else {
  1713. sink.done();
  1714. }
  1715. return true;
  1716. },
  1717. "multipart/form-data; boundary=B");
  1718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1719. EXPECT_EQ(StatusCode::OK_200, res->status);
  1720. EXPECT_EQ("a.txt", filename);
  1721. EXPECT_EQ("hello", content);
  1722. }
  1723. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1724. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1725. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1726. Server svr;
  1727. std::string field_value, file_name, file_filename;
  1728. bool has_field = false, has_file = false;
  1729. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1730. has_field = req.form.has_field("x=y");
  1731. field_value = req.form.get_field("x=y");
  1732. has_file = req.form.has_file("file1");
  1733. const auto &file = req.form.get_file("file1");
  1734. file_name = file.name;
  1735. file_filename = file.filename;
  1736. res.set_content("ok", "text/plain");
  1737. });
  1738. auto port = svr.bind_to_any_port(HOST);
  1739. thread t = thread([&] { svr.listen_after_bind(); });
  1740. auto se = detail::scope_exit([&] {
  1741. svr.stop();
  1742. t.join();
  1743. ASSERT_FALSE(svr.is_running());
  1744. });
  1745. svr.wait_until_ready();
  1746. UploadFormDataItems items = {
  1747. {"x=y", "field-value", "", ""},
  1748. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1749. };
  1750. Client cli(HOST, port);
  1751. auto res = cli.Post("/quoted", items);
  1752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1753. ASSERT_EQ(StatusCode::OK_200, res->status);
  1754. EXPECT_TRUE(has_field);
  1755. EXPECT_EQ("field-value", field_value);
  1756. EXPECT_TRUE(has_file);
  1757. EXPECT_EQ("file1", file_name);
  1758. EXPECT_EQ("a;b=report.pdf", file_filename);
  1759. }
  1760. TEST(GetHeaderValueTest, DefaultValue) {
  1761. Headers headers = {{"Dummy", "Dummy"}};
  1762. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1763. EXPECT_STREQ("text/plain", val);
  1764. }
  1765. TEST(GetHeaderValueTest, DefaultValueInt) {
  1766. Headers headers = {{"Dummy", "Dummy"}};
  1767. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1768. EXPECT_EQ(100ull, val);
  1769. }
  1770. TEST(GetHeaderValueTest, RegularValue) {
  1771. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1772. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1773. EXPECT_STREQ("text/html", val);
  1774. }
  1775. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1776. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1777. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1778. EXPECT_STREQ("text/html", val);
  1779. }
  1780. TEST(GetHeaderValueTest, SetContent) {
  1781. Response res;
  1782. res.set_content("html", "text/html");
  1783. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1784. res.set_content("text", "text/plain");
  1785. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1786. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1787. }
  1788. TEST(GetHeaderValueTest, RegularValueInt) {
  1789. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1790. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1791. EXPECT_EQ(100ull, val);
  1792. }
  1793. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1794. Headers headers = {{"Content-Length", "x"}};
  1795. auto is_invalid_value = false;
  1796. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1797. is_invalid_value);
  1798. EXPECT_EQ(0ull, val);
  1799. EXPECT_TRUE(is_invalid_value);
  1800. }
  1801. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1802. // An all-digit value that overflows size_t must be reported as invalid, not
  1803. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1804. // a large length to a small one on 32-bit builds, leaving the framing length
  1805. // wrong while is_invalid_value stayed false.
  1806. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1807. auto is_invalid_value = false;
  1808. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1809. is_invalid_value);
  1810. EXPECT_TRUE(is_invalid_value);
  1811. // A well-formed length is unaffected.
  1812. Headers ok = {{"Content-Length", "1234"}};
  1813. is_invalid_value = false;
  1814. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1815. is_invalid_value);
  1816. EXPECT_EQ(1234ull, val);
  1817. EXPECT_FALSE(is_invalid_value);
  1818. }
  1819. TEST(GetHeaderValueTest, Range) {
  1820. {
  1821. Headers headers = {make_range_header({{1, -1}})};
  1822. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1823. EXPECT_STREQ("bytes=1-", val);
  1824. }
  1825. {
  1826. Headers headers = {make_range_header({{-1, 1}})};
  1827. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1828. EXPECT_STREQ("bytes=-1", val);
  1829. }
  1830. {
  1831. Headers headers = {make_range_header({{1, 10}})};
  1832. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1833. EXPECT_STREQ("bytes=1-10", val);
  1834. }
  1835. {
  1836. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1837. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1838. EXPECT_STREQ("bytes=1-10, 100-", val);
  1839. }
  1840. {
  1841. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1842. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1843. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1844. }
  1845. {
  1846. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1847. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1848. EXPECT_STREQ("bytes=0-0, -1", val);
  1849. }
  1850. }
  1851. TEST(BearerTokenAuthTest, SchemeValidation) {
  1852. // A value shorter than "Bearer " must not throw from the fixed-length
  1853. // substr, and a non-Bearer scheme must not be reported as a token.
  1854. struct {
  1855. const char *value;
  1856. const char *expected;
  1857. } cases[] = {
  1858. {"x", ""},
  1859. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1860. {"Bearer abc123", "abc123"},
  1861. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1862. };
  1863. for (const auto &c : cases) {
  1864. Request req;
  1865. req.set_header("Authorization", c.value);
  1866. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1867. }
  1868. }
  1869. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1870. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1871. // to depend on the standard library (libstdc++ handed back duplicates in
  1872. // reverse insertion order, libc++ in insertion order).
  1873. Request req;
  1874. req.set_header("Accept-Encoding", "gzip");
  1875. req.set_header("Accept-Encoding", "deflate");
  1876. req.set_header("Accept-Encoding", "br");
  1877. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1878. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1879. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1880. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1881. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1882. }
  1883. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1884. Request req;
  1885. req.set_header("X-Test", "only");
  1886. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1887. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1888. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1889. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1890. }
  1891. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1892. Request req;
  1893. req.set_header("X-First", "1");
  1894. req.set_header("X-Test", "2");
  1895. req.params.emplace("first", "1");
  1896. req.params.emplace("test", "2");
  1897. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1898. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1899. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1900. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1901. // The second one is negative when read as a signed value
  1902. const auto max_id = (std::numeric_limits<size_t>::max)();
  1903. for (auto id : {max_id / 2, max_id}) {
  1904. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1905. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1906. EXPECT_EQ("", req.get_param_value("test", id));
  1907. EXPECT_EQ("", req.form.get_field("test", id));
  1908. EXPECT_EQ("", req.form.get_file("test", id).content);
  1909. }
  1910. }
  1911. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1912. Headers headers;
  1913. headers.emplace("Host", "example.com");
  1914. headers.emplace("Accept-Encoding", "gzip");
  1915. headers.emplace("User-Agent", "test");
  1916. headers.emplace("Accept-Encoding", "deflate");
  1917. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1918. "Accept-Encoding=deflate ",
  1919. entries_to_string(headers));
  1920. }
  1921. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1922. Headers headers = {{"Content-Type", "text/html"},
  1923. {"CONTENT-TYPE", "text/xml"}};
  1924. EXPECT_EQ(2U, headers.count("content-type"));
  1925. auto it = headers.find("content-type");
  1926. ASSERT_TRUE(it != headers.end());
  1927. EXPECT_EQ("text/html", it->second);
  1928. }
  1929. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1930. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1931. // drop only those fields and leave everything positioned between them.
  1932. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1933. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1934. auto rng = headers.equal_range("a");
  1935. headers.erase(rng.first, rng.second);
  1936. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1937. }
  1938. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1939. Headers headers = {
  1940. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1941. EXPECT_EQ(3U, headers.erase("A"));
  1942. EXPECT_EQ(0U, headers.count("A"));
  1943. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1944. }
  1945. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1946. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1947. headers.emplace_front("Host", "example.com");
  1948. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1949. entries_to_string(headers));
  1950. }
  1951. TEST(ParseHeaderValueTest, Range) {
  1952. {
  1953. Ranges ranges;
  1954. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1955. EXPECT_TRUE(ret);
  1956. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1957. }
  1958. {
  1959. Ranges ranges;
  1960. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1961. EXPECT_TRUE(ret);
  1962. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1963. }
  1964. {
  1965. Ranges ranges;
  1966. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1967. EXPECT_TRUE(ret);
  1968. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1969. }
  1970. {
  1971. Ranges ranges;
  1972. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1973. EXPECT_FALSE(ret);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1980. }
  1981. {
  1982. Ranges ranges;
  1983. auto ret =
  1984. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1985. EXPECT_TRUE(ret);
  1986. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1987. }
  1988. {
  1989. Ranges ranges;
  1990. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1996. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1997. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1998. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1999. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2000. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2001. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2003. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2004. EXPECT_FALSE(
  2005. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2006. EXPECT_TRUE(ranges.empty());
  2007. }
  2008. {
  2009. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2010. // remainder of the representation, so it stays accepted.
  2011. Ranges ranges;
  2012. auto ret =
  2013. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2014. EXPECT_TRUE(ret);
  2015. ASSERT_EQ(1u, ranges.size());
  2016. EXPECT_EQ(0, ranges[0].first);
  2017. EXPECT_EQ(-1, ranges[0].second);
  2018. }
  2019. // RFC 9110 14.1: range unit names are case-insensitive.
  2020. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2021. Ranges ranges;
  2022. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2023. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2024. }
  2025. }
  2026. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2027. Request req;
  2028. req.set_header("Accept-Encoding", "gzip");
  2029. Response res;
  2030. res.set_header("Content-Type", "text/plain");
  2031. auto ret = detail::encoding_type(req, res);
  2032. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2033. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2034. #else
  2035. EXPECT_TRUE(ret == detail::EncodingType::None);
  2036. #endif
  2037. }
  2038. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2039. Request req;
  2040. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2041. Response res;
  2042. res.set_header("Content-Type", "text/plain");
  2043. auto ret = detail::encoding_type(req, res);
  2044. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2046. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2047. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2048. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2049. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2050. #else
  2051. EXPECT_TRUE(ret == detail::EncodingType::None);
  2052. #endif
  2053. }
  2054. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2055. Request req;
  2056. req.set_header("Accept-Encoding",
  2057. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2058. Response res;
  2059. res.set_header("Content-Type", "text/plain");
  2060. auto ret = detail::encoding_type(req, res);
  2061. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2063. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2065. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2066. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2067. #else
  2068. EXPECT_TRUE(ret == detail::EncodingType::None);
  2069. #endif
  2070. }
  2071. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2072. // All supported encodings rejected with q=0 should return None
  2073. Request req;
  2074. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2075. Response res;
  2076. res.set_header("Content-Type", "text/plain");
  2077. auto ret = detail::encoding_type(req, res);
  2078. EXPECT_TRUE(ret == detail::EncodingType::None);
  2079. }
  2080. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2081. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2082. Request req;
  2083. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2084. Response res;
  2085. res.set_header("Content-Type", "text/plain");
  2086. auto ret = detail::encoding_type(req, res);
  2087. EXPECT_TRUE(ret == detail::EncodingType::None);
  2088. }
  2089. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2092. Response res;
  2093. res.set_header("Content-Type", "text/plain");
  2094. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2095. }
  2096. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2097. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2098. Request req;
  2099. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2100. Response res;
  2101. res.set_header("Content-Type", "text/plain");
  2102. auto ret = detail::encoding_type(req, res);
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. }
  2105. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2106. // RFC 7231: Accept-Encoding values are case-insensitive
  2107. Request req;
  2108. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2109. Response res;
  2110. res.set_header("Content-Type", "text/plain");
  2111. auto ret = detail::encoding_type(req, res);
  2112. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2113. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2114. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2115. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2116. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2117. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2118. #else
  2119. EXPECT_TRUE(ret == detail::EncodingType::None);
  2120. #endif
  2121. }
  2122. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2123. // q value should determine priority, not hardcoded order
  2124. Request req;
  2125. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2126. Response res;
  2127. res.set_header("Content-Type", "text/plain");
  2128. auto ret = detail::encoding_type(req, res);
  2129. // gzip has highest q=1.0, so it should be selected even though
  2130. // br and zstd are also supported
  2131. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2132. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2133. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2135. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2136. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2137. #else
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. #endif
  2140. }
  2141. TEST(BufferStreamTest, read) {
  2142. detail::BufferStream strm1;
  2143. Stream &strm = strm1;
  2144. EXPECT_EQ(5, strm.write("hello"));
  2145. char buf[512];
  2146. EXPECT_EQ(2, strm.read(buf, 2));
  2147. EXPECT_EQ('h', buf[0]);
  2148. EXPECT_EQ('e', buf[1]);
  2149. EXPECT_EQ(2, strm.read(buf, 2));
  2150. EXPECT_EQ('l', buf[0]);
  2151. EXPECT_EQ('l', buf[1]);
  2152. EXPECT_EQ(1, strm.read(buf, 1));
  2153. EXPECT_EQ('o', buf[0]);
  2154. EXPECT_EQ(0, strm.read(buf, 1));
  2155. }
  2156. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2157. auto host = "www.httpwatch.com";
  2158. auto ip = hosted_at(host);
  2159. EXPECT_EQ("23.96.13.243", ip);
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(1u, addrs.size());
  2163. }
  2164. #if 0 // It depends on each test environment...
  2165. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2166. auto host = "www.youtube.com";
  2167. std::vector<std::string> addrs;
  2168. hosted_at(host, addrs);
  2169. EXPECT_EQ(20u, addrs.size());
  2170. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2171. EXPECT_TRUE(it != addrs.end());
  2172. }
  2173. #endif
  2174. class ChunkedEncodingTest : public ::testing::Test {
  2175. protected:
  2176. ChunkedEncodingTest()
  2177. : cli_(HOST, PORT)
  2178. #ifdef CPPHTTPLIB_SSL_ENABLED
  2179. ,
  2180. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2181. #endif
  2182. {
  2183. cli_.set_connection_timeout(2);
  2184. #ifdef CPPHTTPLIB_SSL_ENABLED
  2185. cli_.enable_server_certificate_verification(false);
  2186. #endif
  2187. }
  2188. virtual void SetUp() {
  2189. read_file("./image.jpg", image_data_);
  2190. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2191. res.set_content("Hello World!", "text/plain");
  2192. });
  2193. svr_.Get(
  2194. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2195. res.set_chunked_content_provider(
  2196. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2197. size_t remaining = image_data_.size() - offset;
  2198. if (remaining == 0) {
  2199. sink.done();
  2200. } else {
  2201. constexpr size_t CHUNK_SIZE = 1024;
  2202. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2203. sink.write(&image_data_[offset], send_size);
  2204. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2205. }
  2206. return true;
  2207. });
  2208. });
  2209. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2210. svr_.wait_until_ready();
  2211. }
  2212. virtual void TearDown() {
  2213. svr_.stop();
  2214. if (!request_threads_.empty()) {
  2215. std::this_thread::sleep_for(std::chrono::seconds(1));
  2216. for (auto &t : request_threads_) {
  2217. t.join();
  2218. }
  2219. }
  2220. t_.join();
  2221. }
  2222. #ifdef CPPHTTPLIB_SSL_ENABLED
  2223. SSLClient cli_;
  2224. SSLServer svr_;
  2225. #else
  2226. Client cli_;
  2227. Server svr_;
  2228. #endif
  2229. thread t_;
  2230. std::vector<thread> request_threads_;
  2231. std::string image_data_;
  2232. };
  2233. TEST_F(ChunkedEncodingTest, NormalGet) {
  2234. auto res = cli_.Get("/chunked");
  2235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2236. std::string out;
  2237. read_file("./image.jpg", out);
  2238. EXPECT_EQ(StatusCode::OK_200, res->status);
  2239. EXPECT_EQ(out, res->body);
  2240. }
  2241. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2242. std::string body;
  2243. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2244. body.append(data, data_length);
  2245. return true;
  2246. });
  2247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2248. std::string out;
  2249. read_file("./image.jpg", out);
  2250. EXPECT_EQ(StatusCode::OK_200, res->status);
  2251. EXPECT_EQ(out, body);
  2252. }
  2253. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2254. std::string body;
  2255. auto res = cli_.Get(
  2256. "/chunked",
  2257. [&](const Response &response) {
  2258. EXPECT_EQ(StatusCode::OK_200, response.status);
  2259. return true;
  2260. },
  2261. [&](const char *data, size_t data_length) {
  2262. body.append(data, data_length);
  2263. return true;
  2264. });
  2265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2266. std::string out;
  2267. read_file("./image.jpg", out);
  2268. EXPECT_EQ(StatusCode::OK_200, res->status);
  2269. EXPECT_EQ(out, body);
  2270. }
  2271. TEST(RangeTest, FromHTTPBin_Online) {
  2272. auto host = "httpbingo.org";
  2273. auto path = std::string{"/range/32"};
  2274. #ifdef CPPHTTPLIB_SSL_ENABLED
  2275. auto port = 443;
  2276. SSLClient cli(host, port);
  2277. #else
  2278. auto port = 80;
  2279. Client cli(host, port);
  2280. #endif
  2281. cli.set_connection_timeout(5);
  2282. {
  2283. auto res = cli.Get(path);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::OK_200, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, -1}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. {
  2296. Headers headers = {make_range_header({{1, 10}})};
  2297. auto res = cli.Get(path, headers);
  2298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2299. EXPECT_EQ("bcdefghijk", res->body);
  2300. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2301. }
  2302. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2303. // entire resource, while the original httpbin returned 200. Both are
  2304. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2305. {
  2306. Headers headers = {make_range_header({{0, 31}})};
  2307. auto res = cli.Get(path, headers);
  2308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2309. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2310. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2311. res->status == StatusCode::PartialContent_206);
  2312. }
  2313. {
  2314. Headers headers = {make_range_header({{0, -1}})};
  2315. auto res = cli.Get(path, headers);
  2316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2317. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2318. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2319. res->status == StatusCode::PartialContent_206);
  2320. }
  2321. // go-httpbin returns 206 with clamped range for over-range requests,
  2322. // while the original httpbin returned 416. Both behaviors are observed
  2323. // in real servers, so we only verify the request succeeds.
  2324. {
  2325. Headers headers = {make_range_header({{0, 32}})};
  2326. auto res = cli.Get(path, headers);
  2327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2328. }
  2329. }
  2330. TEST(RangeTest, IgnoredForPost) {
  2331. Server svr;
  2332. svr.Post("/", [](const Request &, Response &res) {
  2333. res.set_content("abcdefg", "text/plain");
  2334. });
  2335. auto port = svr.bind_to_any_port(HOST);
  2336. ASSERT_GT(port, 0);
  2337. thread t = thread([&] { svr.listen_after_bind(); });
  2338. auto se = detail::scope_exit([&] {
  2339. svr.stop();
  2340. t.join();
  2341. ASSERT_FALSE(svr.is_running());
  2342. });
  2343. svr.wait_until_ready();
  2344. Client cli(HOST, port);
  2345. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2346. auto res = cli.Post("/", Headers{{"Range", range}});
  2347. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2348. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2349. EXPECT_EQ("abcdefg", res->body) << range;
  2350. }
  2351. }
  2352. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2353. auto host = "unresolvableaddress.local";
  2354. auto path = std::string{"/"};
  2355. #ifdef CPPHTTPLIB_SSL_ENABLED
  2356. auto port = 443;
  2357. SSLClient cli(host, port);
  2358. #else
  2359. auto port = 80;
  2360. Client cli(host, port);
  2361. #endif
  2362. cli.set_connection_timeout(1);
  2363. {
  2364. auto res = cli.Get(path);
  2365. ASSERT_FALSE(res);
  2366. }
  2367. std::this_thread::sleep_for(std::chrono::seconds(8));
  2368. }
  2369. #if defined(__linux__) && defined(__GLIBC__) && \
  2370. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2371. // Forward declaration: in split builds split.py strips `inline` and moves the
  2372. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2373. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2374. // against the symbol in both header-only and split builds.
  2375. namespace httplib {
  2376. namespace detail {
  2377. int getaddrinfo_with_timeout(const char *node, const char *service,
  2378. const struct addrinfo *hints,
  2379. struct addrinfo **res, time_t timeout_sec);
  2380. } // namespace detail
  2381. } // namespace httplib
  2382. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2383. //
  2384. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2385. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2386. // gai_suspend() call hits the connection timeout the function calls
  2387. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2388. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2389. // still alive and still references the now-destroyed stack frame.
  2390. //
  2391. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2392. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2393. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2394. // and runs them in a container.
  2395. namespace {
  2396. bool should_run_issue_2431_tests() {
  2397. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2398. return v && *v && std::string(v) != "0";
  2399. }
  2400. std::string unique_unresolvable_host(int n) {
  2401. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2402. // glibc still asks the configured nameserver — which is exactly the path
  2403. // we want to exercise. A unique label per call avoids the resolver cache.
  2404. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2405. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2406. std::to_string(n) + ".invalid";
  2407. }
  2408. } // namespace
  2409. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2410. if (!should_run_issue_2431_tests()) {
  2411. GTEST_SKIP()
  2412. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2413. }
  2414. for (int i = 0; i < 8; ++i) {
  2415. struct addrinfo hints;
  2416. memset(&hints, 0, sizeof(hints));
  2417. hints.ai_family = AF_UNSPEC;
  2418. hints.ai_socktype = SOCK_STREAM;
  2419. auto host = unique_unresolvable_host(i);
  2420. struct addrinfo *result = nullptr;
  2421. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2422. &result, /*timeout_sec=*/1);
  2423. if (rc == 0 && result) { freeaddrinfo(result); }
  2424. }
  2425. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2426. // stack region they still believe holds their gaicb.
  2427. std::this_thread::sleep_for(std::chrono::seconds(3));
  2428. }
  2429. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2430. if (!should_run_issue_2431_tests()) {
  2431. GTEST_SKIP()
  2432. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2433. }
  2434. std::atomic<bool> stop{false};
  2435. std::vector<std::thread> threads;
  2436. for (int t = 0; t < 8; ++t) {
  2437. threads.emplace_back([t, &stop] {
  2438. int i = 0;
  2439. while (!stop.load(std::memory_order_relaxed)) {
  2440. struct addrinfo hints;
  2441. memset(&hints, 0, sizeof(hints));
  2442. hints.ai_family = AF_UNSPEC;
  2443. hints.ai_socktype = SOCK_STREAM;
  2444. auto host = unique_unresolvable_host(t * 100000 + i++);
  2445. struct addrinfo *result = nullptr;
  2446. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2447. &result, /*timeout_sec=*/1);
  2448. if (rc == 0 && result) { freeaddrinfo(result); }
  2449. }
  2450. });
  2451. }
  2452. std::this_thread::sleep_for(std::chrono::seconds(8));
  2453. stop.store(true, std::memory_order_relaxed);
  2454. for (auto &th : threads) {
  2455. th.join();
  2456. }
  2457. std::this_thread::sleep_for(std::chrono::seconds(3));
  2458. }
  2459. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2460. if (!should_run_issue_2431_tests()) {
  2461. GTEST_SKIP()
  2462. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2463. }
  2464. std::atomic<bool> stop{false};
  2465. std::vector<std::thread> threads;
  2466. for (int t = 0; t < 8; ++t) {
  2467. threads.emplace_back([t, &stop] {
  2468. int i = 0;
  2469. while (!stop.load(std::memory_order_relaxed)) {
  2470. auto host = unique_unresolvable_host(t * 100000 + i++);
  2471. Client cli(host, 80);
  2472. cli.set_connection_timeout(1, 0);
  2473. cli.set_read_timeout(1, 0);
  2474. cli.set_write_timeout(1, 0);
  2475. (void)cli.Get("/");
  2476. }
  2477. });
  2478. }
  2479. std::this_thread::sleep_for(std::chrono::seconds(8));
  2480. stop.store(true, std::memory_order_relaxed);
  2481. for (auto &th : threads) {
  2482. th.join();
  2483. }
  2484. std::this_thread::sleep_for(std::chrono::seconds(3));
  2485. }
  2486. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2487. TEST(ConnectionErrorTest, InvalidHost) {
  2488. auto host = "-abcde.com";
  2489. #ifdef CPPHTTPLIB_SSL_ENABLED
  2490. auto port = 443;
  2491. SSLClient cli(host, port);
  2492. #else
  2493. auto port = 80;
  2494. Client cli(host, port);
  2495. #endif
  2496. cli.set_connection_timeout(std::chrono::seconds(2));
  2497. auto res = cli.Get("/");
  2498. ASSERT_TRUE(!res);
  2499. EXPECT_EQ(Error::Connection, res.error());
  2500. }
  2501. TEST(ConnectionErrorTest, InvalidHost2) {
  2502. auto host = "httpcan.org/";
  2503. #ifdef CPPHTTPLIB_SSL_ENABLED
  2504. SSLClient cli(host);
  2505. #else
  2506. Client cli(host);
  2507. #endif
  2508. cli.set_connection_timeout(std::chrono::seconds(2));
  2509. auto res = cli.Get("/");
  2510. ASSERT_TRUE(!res);
  2511. EXPECT_EQ(Error::Connection, res.error());
  2512. }
  2513. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2514. auto host = "httpcan.org/";
  2515. #ifdef CPPHTTPLIB_SSL_ENABLED
  2516. SSLClient cli(host);
  2517. #else
  2518. Client cli(host);
  2519. #endif
  2520. cli.set_connection_timeout(std::chrono::seconds(2));
  2521. auto res = cli.Get("/");
  2522. ASSERT_TRUE(!res);
  2523. stringstream s;
  2524. s << "error code: " << res.error();
  2525. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2526. }
  2527. TEST(ConnectionErrorTest, InvalidPort) {
  2528. auto host = "localhost";
  2529. auto port = 44380;
  2530. #ifdef CPPHTTPLIB_SSL_ENABLED
  2531. SSLClient cli(host, port);
  2532. #else
  2533. Client cli(host, port);
  2534. #endif
  2535. cli.set_connection_timeout(std::chrono::seconds(2));
  2536. auto res = cli.Get("/");
  2537. ASSERT_TRUE(!res);
  2538. EXPECT_TRUE(Error::Connection == res.error() ||
  2539. Error::ConnectionTimeout == res.error());
  2540. }
  2541. TEST(ConnectionErrorTest, Timeout_Online) {
  2542. auto host = "google.com";
  2543. #ifdef CPPHTTPLIB_SSL_ENABLED
  2544. auto port = 44380;
  2545. SSLClient cli(host, port);
  2546. #else
  2547. auto port = 8080;
  2548. Client cli(host, port);
  2549. #endif
  2550. cli.set_connection_timeout(std::chrono::seconds(2));
  2551. // only probe one address type so that the error reason
  2552. // correlates to the timed-out IPv4, not the unsupported
  2553. // IPv6 connection attempt
  2554. cli.set_address_family(AF_INET);
  2555. auto res = cli.Get("/");
  2556. ASSERT_TRUE(!res);
  2557. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2558. }
  2559. TEST(CancelTest, NoCancel_Online) {
  2560. auto host = "httpbingo.org";
  2561. auto path = std::string{"/range/32"};
  2562. #ifdef CPPHTTPLIB_SSL_ENABLED
  2563. auto port = 443;
  2564. SSLClient cli(host, port);
  2565. #else
  2566. auto port = 80;
  2567. Client cli(host, port);
  2568. #endif
  2569. cli.set_connection_timeout(std::chrono::seconds(5));
  2570. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2572. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2573. EXPECT_EQ(StatusCode::OK_200, res->status);
  2574. }
  2575. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2576. // Use /bytes with a large payload so that the DownloadProgress callback
  2577. // (which only fires for Content-Length responses) is invoked before the
  2578. // entire body is received, giving cancellation a chance to fire.
  2579. auto host = "httpbingo.org";
  2580. auto path = std::string{"/bytes/524288"};
  2581. #ifdef CPPHTTPLIB_SSL_ENABLED
  2582. auto port = 443;
  2583. SSLClient cli(host, port);
  2584. #else
  2585. auto port = 80;
  2586. Client cli(host, port);
  2587. #endif
  2588. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2589. cli.set_connection_timeout(std::chrono::seconds(5));
  2590. ASSERT_TRUE(!res);
  2591. EXPECT_EQ(Error::Canceled, res.error());
  2592. }
  2593. TEST(CancelTest, WithCancelLargePayload_Online) {
  2594. auto host = "httpbingo.org";
  2595. auto path = std::string{"/bytes/524288"};
  2596. #ifdef CPPHTTPLIB_SSL_ENABLED
  2597. auto port = 443;
  2598. SSLClient cli(host, port);
  2599. #else
  2600. auto port = 80;
  2601. Client cli(host, port);
  2602. #endif
  2603. cli.set_connection_timeout(std::chrono::seconds(5));
  2604. uint32_t count = 0;
  2605. auto res =
  2606. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2607. ASSERT_TRUE(!res);
  2608. EXPECT_EQ(Error::Canceled, res.error());
  2609. }
  2610. TEST(CancelTest, NoCancelPost) {
  2611. Server svr;
  2612. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2613. res.set_content("Hello World!", "text/plain");
  2614. });
  2615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2616. auto se = detail::scope_exit([&] {
  2617. svr.stop();
  2618. thread.join();
  2619. ASSERT_FALSE(svr.is_running());
  2620. });
  2621. svr.wait_until_ready();
  2622. Client cli(HOST, PORT);
  2623. cli.set_connection_timeout(std::chrono::seconds(5));
  2624. auto res =
  2625. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2626. "application/json", [](uint64_t, uint64_t) { return true; });
  2627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2628. EXPECT_EQ("Hello World!", res->body);
  2629. EXPECT_EQ(StatusCode::OK_200, res->status);
  2630. }
  2631. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2632. Server svr;
  2633. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2634. res.set_content("Hello World!", "text/plain");
  2635. });
  2636. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2637. auto se = detail::scope_exit([&] {
  2638. svr.stop();
  2639. thread.join();
  2640. ASSERT_FALSE(svr.is_running());
  2641. });
  2642. svr.wait_until_ready();
  2643. Client cli(HOST, PORT);
  2644. cli.set_connection_timeout(std::chrono::seconds(5));
  2645. auto res =
  2646. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2647. "application/json", [](uint64_t, uint64_t) { return false; });
  2648. ASSERT_TRUE(!res);
  2649. EXPECT_EQ(Error::Canceled, res.error());
  2650. }
  2651. TEST(CancelTest, WithCancelLargePayloadPost) {
  2652. Server svr;
  2653. svr.set_payload_max_length(200 * 1024 * 1024);
  2654. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2655. res.set_content(LARGE_DATA, "text/plain");
  2656. });
  2657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2658. auto se = detail::scope_exit([&] {
  2659. svr.stop();
  2660. thread.join();
  2661. ASSERT_FALSE(svr.is_running());
  2662. });
  2663. svr.wait_until_ready();
  2664. Client cli(HOST, PORT);
  2665. cli.set_payload_max_length(200 * 1024 * 1024);
  2666. cli.set_connection_timeout(std::chrono::seconds(5));
  2667. auto res =
  2668. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2669. "application/json", [](uint64_t, uint64_t) { return false; });
  2670. ASSERT_TRUE(!res);
  2671. EXPECT_EQ(Error::Canceled, res.error());
  2672. }
  2673. TEST(CancelTest, NoCancelPut) {
  2674. Server svr;
  2675. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2676. res.set_content("Hello World!", "text/plain");
  2677. });
  2678. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2679. auto se = detail::scope_exit([&] {
  2680. svr.stop();
  2681. thread.join();
  2682. ASSERT_FALSE(svr.is_running());
  2683. });
  2684. svr.wait_until_ready();
  2685. Client cli(HOST, PORT);
  2686. cli.set_connection_timeout(std::chrono::seconds(5));
  2687. auto res =
  2688. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2689. "application/json", [](uint64_t, uint64_t) { return true; });
  2690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2691. EXPECT_EQ("Hello World!", res->body);
  2692. EXPECT_EQ(StatusCode::OK_200, res->status);
  2693. }
  2694. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2695. Server svr;
  2696. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2697. res.set_content("Hello World!", "text/plain");
  2698. });
  2699. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2700. auto se = detail::scope_exit([&] {
  2701. svr.stop();
  2702. thread.join();
  2703. ASSERT_FALSE(svr.is_running());
  2704. });
  2705. svr.wait_until_ready();
  2706. Client cli(HOST, PORT);
  2707. cli.set_connection_timeout(std::chrono::seconds(5));
  2708. auto res =
  2709. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2710. "application/json", [](uint64_t, uint64_t) { return false; });
  2711. ASSERT_TRUE(!res);
  2712. EXPECT_EQ(Error::Canceled, res.error());
  2713. }
  2714. TEST(CancelTest, WithCancelLargePayloadPut) {
  2715. Server svr;
  2716. svr.set_payload_max_length(200 * 1024 * 1024);
  2717. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2718. res.set_content(LARGE_DATA, "text/plain");
  2719. });
  2720. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2721. auto se = detail::scope_exit([&] {
  2722. svr.stop();
  2723. thread.join();
  2724. ASSERT_FALSE(svr.is_running());
  2725. });
  2726. svr.wait_until_ready();
  2727. Client cli(HOST, PORT);
  2728. cli.set_payload_max_length(200 * 1024 * 1024);
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. auto res =
  2731. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2732. "application/json", [](uint64_t, uint64_t) { return false; });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelPatch) {
  2737. Server svr;
  2738. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2758. Server svr;
  2759. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. TEST(CancelTest, NoCancelDelete) {
  2800. Server svr;
  2801. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("Hello World!", "text/plain");
  2803. });
  2804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2805. auto se = detail::scope_exit([&] {
  2806. svr.stop();
  2807. thread.join();
  2808. ASSERT_FALSE(svr.is_running());
  2809. });
  2810. svr.wait_until_ready();
  2811. Client cli(HOST, PORT);
  2812. cli.set_connection_timeout(std::chrono::seconds(5));
  2813. auto res =
  2814. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2815. "application/json", [](uint64_t, uint64_t) { return true; });
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ("Hello World!", res->body);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. }
  2820. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2821. Server svr;
  2822. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2823. res.set_content("Hello World!", "text/plain");
  2824. });
  2825. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2826. auto se = detail::scope_exit([&] {
  2827. svr.stop();
  2828. thread.join();
  2829. ASSERT_FALSE(svr.is_running());
  2830. });
  2831. svr.wait_until_ready();
  2832. Client cli(HOST, PORT);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2841. Server svr;
  2842. svr.set_payload_max_length(200 * 1024 * 1024);
  2843. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2844. res.set_content(LARGE_DATA, "text/plain");
  2845. });
  2846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. Client cli(HOST, PORT);
  2854. cli.set_payload_max_length(200 * 1024 * 1024);
  2855. cli.set_connection_timeout(std::chrono::seconds(5));
  2856. auto res =
  2857. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2858. "application/json", [](uint64_t, uint64_t) { return false; });
  2859. ASSERT_TRUE(!res);
  2860. EXPECT_EQ(Error::Canceled, res.error());
  2861. }
  2862. static std::string remove_whitespace(const std::string &input) {
  2863. std::string output;
  2864. output.reserve(input.size());
  2865. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2866. [](unsigned char c) { return !std::isspace(c); });
  2867. return output;
  2868. }
  2869. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2870. auto host = "httpbingo.org";
  2871. auto path = std::string{"/basic-auth/hello/world"};
  2872. #ifdef CPPHTTPLIB_SSL_ENABLED
  2873. auto port = 443;
  2874. SSLClient cli(host, port);
  2875. #else
  2876. auto port = 80;
  2877. Client cli(host, port);
  2878. #endif
  2879. {
  2880. auto res = cli.Get(path);
  2881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2882. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2883. }
  2884. {
  2885. auto res = cli.Get(
  2886. path, Headers{make_basic_authentication_header("hello", "world")});
  2887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2888. auto body = remove_whitespace(res->body);
  2889. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2890. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2891. EXPECT_EQ(StatusCode::OK_200, res->status);
  2892. }
  2893. {
  2894. cli.set_basic_auth("hello", "world");
  2895. auto res = cli.Get(path);
  2896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2897. auto body = remove_whitespace(res->body);
  2898. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2899. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2900. EXPECT_EQ(StatusCode::OK_200, res->status);
  2901. }
  2902. {
  2903. cli.set_basic_auth("hello", "bad");
  2904. auto res = cli.Get(path);
  2905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2906. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2907. }
  2908. {
  2909. cli.set_basic_auth("bad", "world");
  2910. auto res = cli.Get(path);
  2911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2912. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2913. }
  2914. }
  2915. #ifdef CPPHTTPLIB_SSL_ENABLED
  2916. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2917. auto host = "httpbingo.org";
  2918. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2919. auto paths = std::vector<std::string>{
  2920. "/digest-auth/auth/hello/world/MD5",
  2921. "/digest-auth/auth/hello/world/SHA-256",
  2922. };
  2923. auto port = 443;
  2924. SSLClient cli(host, port);
  2925. {
  2926. auto res = cli.Get(unauth_path);
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2929. }
  2930. {
  2931. cli.set_digest_auth("hello", "world");
  2932. for (const auto &path : paths) {
  2933. auto res = cli.Get(path.c_str());
  2934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2935. auto body = remove_whitespace(res->body);
  2936. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2937. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2938. EXPECT_EQ(StatusCode::OK_200, res->status);
  2939. }
  2940. cli.set_digest_auth("hello", "bad");
  2941. for (const auto &path : paths) {
  2942. auto res = cli.Get(path.c_str());
  2943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2944. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2945. }
  2946. }
  2947. }
  2948. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2949. // comma-separated list of challenges, and each challenge may itself carry a
  2950. // comma-separated auth-param list, so a server can legally offer Basic
  2951. // before Digest, either as two field lines or packed into one. Runs one 401
  2952. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2953. // value() joins them in receipt order) and checks that the retry carries a
  2954. // well-formed Digest Authorization header naming expected_realm.
  2955. static void
  2956. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2957. const std::string &expected_realm) {
  2958. std::atomic<int> hits{0};
  2959. Server svr;
  2960. svr.Get("/x", [&](const Request &req, Response &res) {
  2961. if (++hits == 1) {
  2962. res.status = StatusCode::Unauthorized_401;
  2963. for (const auto &challenge : challenges) {
  2964. res.set_header("WWW-Authenticate", challenge);
  2965. }
  2966. } else {
  2967. auto authorization = req.get_header_value("Authorization");
  2968. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2969. EXPECT_NE(std::string::npos,
  2970. authorization.find("realm=\"" + expected_realm + "\""));
  2971. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2972. res.set_content("ok", "text/plain");
  2973. }
  2974. });
  2975. auto port = svr.bind_to_any_port(HOST);
  2976. std::thread t([&]() { svr.listen_after_bind(); });
  2977. auto se = detail::scope_exit([&] {
  2978. svr.stop();
  2979. t.join();
  2980. });
  2981. svr.wait_until_ready();
  2982. Client cli(HOST, port);
  2983. cli.set_digest_auth("hello", "world");
  2984. auto res = cli.Get("/x");
  2985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2986. EXPECT_EQ(2, hits.load());
  2987. }
  2988. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2989. static const char *kDigestChallenge =
  2990. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2991. "algorithm=MD5";
  2992. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2993. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2994. "testrealm");
  2995. }
  2996. // Same challenge list with the schemes in the opposite order, to make sure
  2997. // the fix above didn't just special-case "Basic first".
  2998. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2999. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3000. "testrealm");
  3001. }
  3002. // A comma inside a quoted auth-param value must not be mistaken for the
  3003. // separator between two challenges (or two auth-params).
  3004. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3005. run_digest_challenge_list_test(
  3006. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3007. "algorithm=MD5"},
  3008. "test,realm");
  3009. }
  3010. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3011. // the params and leaves out the fragment.
  3012. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3013. Server svr;
  3014. std::string uri, target;
  3015. svr.Get("/a b", [&](const Request &req, Response &res) {
  3016. auto auth = req.get_header_value("Authorization");
  3017. if (auth.empty()) {
  3018. res.status = StatusCode::Unauthorized_401;
  3019. res.set_header("WWW-Authenticate",
  3020. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3021. return;
  3022. }
  3023. auto b = auth.find("uri=\"") + 5;
  3024. uri = auth.substr(b, auth.find('"', b) - b);
  3025. target = req.target;
  3026. });
  3027. auto port = svr.bind_to_any_port(HOST);
  3028. std::thread t([&]() { svr.listen_after_bind(); });
  3029. auto se = detail::scope_exit([&] {
  3030. svr.stop();
  3031. t.join();
  3032. });
  3033. svr.wait_until_ready();
  3034. Client cli(HOST, port);
  3035. cli.set_digest_auth("hello", "world");
  3036. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3038. EXPECT_EQ("/a%20b?x=1", target);
  3039. EXPECT_EQ(target, uri);
  3040. }
  3041. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3042. // make_digest_authentication_header() dereferences both unconditionally, so
  3043. // a server sending a challenge missing either one must not be treated as
  3044. // usable -- doing so used to crash the client with std::out_of_range.
  3045. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3046. Server svr;
  3047. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3048. res.status = StatusCode::Unauthorized_401;
  3049. res.set_header("WWW-Authenticate", challenge);
  3050. });
  3051. auto port = svr.bind_to_any_port(HOST);
  3052. std::thread t([&]() { svr.listen_after_bind(); });
  3053. auto se = detail::scope_exit([&] {
  3054. svr.stop();
  3055. t.join();
  3056. });
  3057. svr.wait_until_ready();
  3058. Client cli(HOST, port);
  3059. cli.set_digest_auth("hello", "world");
  3060. auto res = cli.Get("/x");
  3061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3062. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3063. }
  3064. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3065. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3066. }
  3067. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3068. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3069. }
  3070. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3071. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3072. }
  3073. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3074. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3075. // when storing the values, so the header builder has to re-escape them (and
  3076. // keep algorithm a bare token); otherwise the value breaks out of its
  3077. // quoted-string and injects extra auth-params into the client's Authorization.
  3078. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3079. std::atomic<int> hits{0};
  3080. std::string authorization;
  3081. Server svr;
  3082. svr.Get("/x", [&](const Request &req, Response &res) {
  3083. if (++hits == 1) {
  3084. res.status = StatusCode::Unauthorized_401;
  3085. // On the wire the quotes embedded in the values are backslash-escaped.
  3086. res.set_header("WWW-Authenticate",
  3087. "Digest realm=\"testrealm\", "
  3088. "nonce=\"n\\\"; injected=\\\"x\", "
  3089. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3090. } else {
  3091. authorization = req.get_header_value("Authorization");
  3092. res.set_content("ok", "text/plain");
  3093. }
  3094. });
  3095. auto port = svr.bind_to_any_port(HOST);
  3096. std::thread t([&]() { svr.listen_after_bind(); });
  3097. auto se = detail::scope_exit([&] {
  3098. svr.stop();
  3099. t.join();
  3100. });
  3101. svr.wait_until_ready();
  3102. Client cli(HOST, port);
  3103. cli.set_digest_auth("hello", "world");
  3104. auto res = cli.Get("/x");
  3105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3106. EXPECT_EQ(2, hits.load());
  3107. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3108. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3109. // inside its quoted-string rather than starting an "injected" auth-param.
  3110. EXPECT_NE(std::string::npos,
  3111. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3112. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3113. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3114. }
  3115. #endif
  3116. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3117. auto host = "google.com";
  3118. auto another_host = "example.com";
  3119. auto wrong_ip = "0.0.0.0";
  3120. #ifdef CPPHTTPLIB_SSL_ENABLED
  3121. SSLClient cli(host);
  3122. #else
  3123. Client cli(host);
  3124. #endif
  3125. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3126. auto res = cli.Get("/");
  3127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3128. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3129. }
  3130. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3131. auto host = "google.com";
  3132. auto wrong_ip = "0.0.0.0";
  3133. #ifdef CPPHTTPLIB_SSL_ENABLED
  3134. SSLClient cli(host);
  3135. #else
  3136. Client cli(host);
  3137. #endif
  3138. cli.set_hostname_addr_map({{host, wrong_ip}});
  3139. auto res = cli.Get("/");
  3140. ASSERT_TRUE(!res);
  3141. EXPECT_EQ(Error::Connection, res.error());
  3142. }
  3143. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3144. // A mapped value that is not an IP literal must be resolved. "localhost"
  3145. // resolves from the hosts file, so this test needs no external DNS.
  3146. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3147. auto host = "target.invalid";
  3148. Server svr;
  3149. std::string received_host;
  3150. svr.Get("/hi", [&](const Request &req, Response &res) {
  3151. received_host = req.get_header_value("Host");
  3152. res.set_content("Hello World!", "text/plain");
  3153. });
  3154. auto port = svr.bind_to_any_port(HOST);
  3155. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3156. auto se = detail::scope_exit([&] {
  3157. svr.stop();
  3158. thread.join();
  3159. ASSERT_FALSE(svr.is_running());
  3160. });
  3161. svr.wait_until_ready();
  3162. Client cli(host, port);
  3163. cli.set_hostname_addr_map({{host, HOST}});
  3164. auto res = cli.Get("/hi");
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::OK_200, res->status);
  3167. // The mapping only redirects the connection; the identity stays host_.
  3168. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3169. }
  3170. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3171. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3172. auto host = "target.invalid";
  3173. Server svr;
  3174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3175. res.set_content("Hello World!", "text/plain");
  3176. });
  3177. auto port = svr.bind_to_any_port("127.0.0.1");
  3178. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3179. auto se = detail::scope_exit([&] {
  3180. svr.stop();
  3181. thread.join();
  3182. ASSERT_FALSE(svr.is_running());
  3183. });
  3184. svr.wait_until_ready();
  3185. Client cli(host, port);
  3186. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3187. auto res = cli.Get("/hi");
  3188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3189. EXPECT_EQ(StatusCode::OK_200, res->status);
  3190. }
  3191. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3192. // An empty mapped value must leave host_ as the connection target. Without
  3193. // that guard the empty value would become the host argument, getaddrinfo
  3194. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3195. // loopback - silently connecting somewhere the caller never asked for.
  3196. // The server listens on loopback, so such a fallback would succeed and is
  3197. // therefore observable as a failure of this test.
  3198. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3199. Server svr;
  3200. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3201. res.set_content("Hello World!", "text/plain");
  3202. });
  3203. auto port = svr.bind_to_any_port(HOST);
  3204. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3205. auto se = detail::scope_exit([&] {
  3206. svr.stop();
  3207. thread.join();
  3208. ASSERT_FALSE(svr.is_running());
  3209. });
  3210. svr.wait_until_ready();
  3211. Client cli(blackhole, port);
  3212. cli.set_hostname_addr_map({{blackhole, ""}});
  3213. cli.set_connection_timeout(1);
  3214. auto res = cli.Get("/hi");
  3215. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3216. }
  3217. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3218. auto host = "httpbingo.org";
  3219. auto path = std::string{"/absolute-redirect/3"};
  3220. #ifdef CPPHTTPLIB_SSL_ENABLED
  3221. SSLClient cli(host);
  3222. #else
  3223. Client cli(host);
  3224. #endif
  3225. cli.set_follow_location(true);
  3226. auto res = cli.Get(path);
  3227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. }
  3230. TEST(RedirectTest, Redirect_Online) {
  3231. auto host = "httpbingo.org";
  3232. auto path = std::string{"/redirect/3"};
  3233. #ifdef CPPHTTPLIB_SSL_ENABLED
  3234. SSLClient cli(host);
  3235. #else
  3236. Client cli(host);
  3237. #endif
  3238. cli.set_follow_location(true);
  3239. auto res = cli.Get(path);
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. }
  3243. TEST(RelativeRedirectTest, Redirect_Online) {
  3244. auto host = "httpbingo.org";
  3245. auto path = std::string{"/relative-redirect/3"};
  3246. #ifdef CPPHTTPLIB_SSL_ENABLED
  3247. SSLClient cli(host);
  3248. #else
  3249. Client cli(host);
  3250. #endif
  3251. cli.set_follow_location(true);
  3252. auto res = cli.Get(path);
  3253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3254. EXPECT_EQ(StatusCode::OK_200, res->status);
  3255. }
  3256. TEST(TooManyRedirectTest, Redirect_Online) {
  3257. auto host = "httpbingo.org";
  3258. auto path = std::string{"/redirect/21"};
  3259. #ifdef CPPHTTPLIB_SSL_ENABLED
  3260. SSLClient cli(host);
  3261. #else
  3262. Client cli(host);
  3263. #endif
  3264. cli.set_follow_location(true);
  3265. auto res = cli.Get(path);
  3266. ASSERT_TRUE(!res);
  3267. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3268. }
  3269. #ifdef CPPHTTPLIB_SSL_ENABLED
  3270. TEST(YahooRedirectTest, Redirect_Online) {
  3271. Client cli("yahoo.com");
  3272. auto res = cli.Get("/");
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3275. cli.set_follow_location(true);
  3276. res = cli.Get("/");
  3277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3278. EXPECT_EQ(StatusCode::OK_200, res->status);
  3279. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3280. }
  3281. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3282. #define REDIR_HOST "httpbingo.org"
  3283. #define REDIR_PATH "/redirect-to"
  3284. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3285. SSLClient cli(REDIR_HOST);
  3286. cli.set_follow_location(true);
  3287. auto res =
  3288. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3290. EXPECT_EQ(StatusCode::OK_200, res->status);
  3291. }
  3292. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3293. SSLClient cli(REDIR_HOST);
  3294. cli.set_follow_location(true);
  3295. Params params;
  3296. params.emplace("url", "http://example.com");
  3297. params.emplace("status_code", "302");
  3298. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3300. EXPECT_EQ(StatusCode::OK_200, res->status);
  3301. }
  3302. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3303. SSLClient cli(REDIR_HOST);
  3304. cli.set_follow_location(true);
  3305. Params params;
  3306. params.emplace("url", "http://example.com");
  3307. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3309. EXPECT_EQ(StatusCode::OK_200, res->status);
  3310. }
  3311. TEST(UrlWithSpace, Redirect_Online) {
  3312. SSLClient cli("edge.forgecdn.net");
  3313. cli.set_follow_location(true);
  3314. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3316. EXPECT_EQ(StatusCode::OK_200, res->status);
  3317. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3318. }
  3319. #endif
  3320. #if !defined(_WIN32) && !defined(_WIN64)
  3321. TEST(ReceiveSignals, Signal) {
  3322. auto setupSignalHandlers = []() {
  3323. struct sigaction act;
  3324. sigemptyset(&act.sa_mask);
  3325. act.sa_flags = SA_SIGINFO;
  3326. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3327. switch (sig) {
  3328. case SIGINT:
  3329. default: break;
  3330. }
  3331. };
  3332. ::sigaction(SIGINT, &act, nullptr);
  3333. };
  3334. Server svr;
  3335. int port = 0;
  3336. auto thread = std::thread([&]() {
  3337. setupSignalHandlers();
  3338. port = svr.bind_to_any_port(HOST);
  3339. svr.listen_after_bind();
  3340. });
  3341. auto se = detail::scope_exit([&] {
  3342. svr.stop();
  3343. thread.join();
  3344. ASSERT_FALSE(svr.is_running());
  3345. });
  3346. svr.wait_until_ready();
  3347. ASSERT_TRUE(svr.is_running());
  3348. pthread_kill(thread.native_handle(), SIGINT);
  3349. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3350. ASSERT_TRUE(svr.is_running());
  3351. }
  3352. #endif
  3353. TEST(RedirectToDifferentPort, Redirect) {
  3354. Server svr1;
  3355. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3356. res.set_content("Hello World!", "text/plain");
  3357. });
  3358. int svr1_port = 0;
  3359. auto thread1 = std::thread([&]() {
  3360. svr1_port = svr1.bind_to_any_port(HOST);
  3361. svr1.listen_after_bind();
  3362. });
  3363. Server svr2;
  3364. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3365. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3366. });
  3367. int svr2_port = 0;
  3368. auto thread2 = std::thread([&]() {
  3369. svr2_port = svr2.bind_to_any_port(HOST);
  3370. svr2.listen_after_bind();
  3371. });
  3372. auto se = detail::scope_exit([&] {
  3373. svr2.stop();
  3374. thread2.join();
  3375. svr1.stop();
  3376. thread1.join();
  3377. ASSERT_FALSE(svr2.is_running());
  3378. ASSERT_FALSE(svr1.is_running());
  3379. });
  3380. svr1.wait_until_ready();
  3381. svr2.wait_until_ready();
  3382. Client cli("localhost", svr2_port);
  3383. cli.set_follow_location(true);
  3384. auto res = cli.Get("/2");
  3385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3386. EXPECT_EQ(StatusCode::OK_200, res->status);
  3387. EXPECT_EQ("Hello World!", res->body);
  3388. }
  3389. // GET /redir on one server redirects to /target on another port, so the
  3390. // client follows it with a new client.
  3391. static Result
  3392. GetThroughRedirectToDifferentPort(Server::Handler target,
  3393. const std::function<void(Client &)> &setup,
  3394. const Headers &headers = Headers()) {
  3395. Server target_svr;
  3396. target_svr.Get("/target", target);
  3397. int target_port = 0;
  3398. auto target_thread = std::thread([&]() {
  3399. target_port = target_svr.bind_to_any_port(HOST);
  3400. target_svr.listen_after_bind();
  3401. });
  3402. Server origin_svr;
  3403. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3404. res.set_redirect(
  3405. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3406. });
  3407. int origin_port = 0;
  3408. auto origin_thread = std::thread([&]() {
  3409. origin_port = origin_svr.bind_to_any_port(HOST);
  3410. origin_svr.listen_after_bind();
  3411. });
  3412. auto se = detail::scope_exit([&] {
  3413. origin_svr.stop();
  3414. origin_thread.join();
  3415. target_svr.stop();
  3416. target_thread.join();
  3417. });
  3418. target_svr.wait_until_ready();
  3419. origin_svr.wait_until_ready();
  3420. Client cli("localhost", origin_port);
  3421. cli.set_follow_location(true);
  3422. setup(cli);
  3423. return cli.Get("/redir", headers);
  3424. }
  3425. static void
  3426. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3427. std::string captured_authorization;
  3428. auto result = GetThroughRedirectToDifferentPort(
  3429. [&](const Request &req, Response &res) {
  3430. captured_authorization = req.get_header_value("Authorization");
  3431. res.set_content("OK", "text/plain");
  3432. },
  3433. set_auth);
  3434. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3435. EXPECT_EQ(StatusCode::OK_200, result->status);
  3436. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3437. EXPECT_TRUE(captured_authorization.empty());
  3438. }
  3439. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3440. TestDoNotForwardCredentialsOnRedirect(
  3441. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3442. }
  3443. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3444. TestDoNotForwardCredentialsOnRedirect(
  3445. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3446. }
  3447. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3448. std::string captured_cookie;
  3449. auto result = GetThroughRedirectToDifferentPort(
  3450. [&](const Request &req, Response &res) {
  3451. captured_cookie = req.get_header_value("Cookie");
  3452. res.set_content("OK", "text/plain");
  3453. },
  3454. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3455. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3456. EXPECT_EQ(StatusCode::OK_200, result->status);
  3457. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3458. EXPECT_TRUE(captured_cookie.empty());
  3459. }
  3460. TEST(RedirectToSamePort, ForwardCookie) {
  3461. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3462. // header so that ordinary session flows keep working.
  3463. Server svr;
  3464. std::string captured_cookie;
  3465. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3466. res.set_redirect("/target", 302);
  3467. });
  3468. svr.Get("/target", [&](const Request &req, Response &res) {
  3469. captured_cookie = req.get_header_value("Cookie");
  3470. res.set_content("OK", "text/plain");
  3471. });
  3472. auto port = svr.bind_to_any_port(HOST);
  3473. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3474. auto se = detail::scope_exit([&] {
  3475. svr.stop();
  3476. thread.join();
  3477. ASSERT_FALSE(svr.is_running());
  3478. });
  3479. svr.wait_until_ready();
  3480. Client cli(HOST, port);
  3481. cli.set_follow_location(true);
  3482. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3483. auto res = cli.Get("/redir", headers);
  3484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3485. EXPECT_EQ(StatusCode::OK_200, res->status);
  3486. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3487. }
  3488. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3489. std::string authorization;
  3490. std::string trace_id;
  3491. auto result = GetThroughRedirectToDifferentPort(
  3492. [&](const Request &req, Response &res) {
  3493. authorization = req.get_header_value("Authorization");
  3494. trace_id = req.get_header_value("X-Trace-Id");
  3495. res.set_content("OK", "text/plain");
  3496. },
  3497. [](Client &cli) {
  3498. cli.set_default_headers(
  3499. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3500. });
  3501. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3502. EXPECT_EQ(StatusCode::OK_200, result->status);
  3503. // Like a header given with the request, a default one goes along unless it
  3504. // carries credentials (RFC 9110 15.4).
  3505. EXPECT_TRUE(authorization.empty());
  3506. EXPECT_EQ("42", trace_id);
  3507. }
  3508. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3509. auto result = GetThroughRedirectToDifferentPort(
  3510. [](const Request &, Response &res) {
  3511. res.set_content(std::string(2048, 'x'), "text/plain");
  3512. },
  3513. [](Client &cli) { cli.set_payload_max_length(1024); });
  3514. EXPECT_FALSE(result);
  3515. }
  3516. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3517. auto result = GetThroughRedirectToDifferentPort(
  3518. [](const Request &req, Response &res) {
  3519. // Answer after a second, or once the client gives up.
  3520. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3521. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3522. }
  3523. res.set_content("late", "text/plain");
  3524. },
  3525. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3526. ASSERT_FALSE(result);
  3527. EXPECT_EQ(Error::Read, result.error());
  3528. }
  3529. #ifdef CPPHTTPLIB_SSL_ENABLED
  3530. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3531. auto result = GetThroughRedirectToDifferentPort(
  3532. [](const Request &, Response &res) {
  3533. res.status = StatusCode::Unauthorized_401;
  3534. res.set_header("WWW-Authenticate",
  3535. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3536. },
  3537. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3538. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3539. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3540. }
  3541. #endif
  3542. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3543. Server svr;
  3544. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3545. // Port number that overflows int — should not crash
  3546. res.set_redirect("http://localhost:99999999999999999999/target");
  3547. });
  3548. auto port = svr.bind_to_any_port(HOST);
  3549. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3550. auto se = detail::scope_exit([&] {
  3551. svr.stop();
  3552. thread.join();
  3553. ASSERT_FALSE(svr.is_running());
  3554. });
  3555. svr.wait_until_ready();
  3556. Client cli(HOST, port);
  3557. cli.set_follow_location(true);
  3558. auto res = cli.Get("/redir");
  3559. // Should fail gracefully, not crash (no valid response due to bad port)
  3560. EXPECT_FALSE(res);
  3561. }
  3562. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3563. Server svr;
  3564. auto port = svr.bind_to_any_port(HOST);
  3565. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3566. // The server's own port followed by junk must not be followed
  3567. res.set_redirect("http://" + std::string(HOST) + ":" +
  3568. std::to_string(port) + "junk/target");
  3569. });
  3570. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3571. res.set_content("target", "text/plain");
  3572. });
  3573. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3574. auto se = detail::scope_exit([&] {
  3575. svr.stop();
  3576. thread.join();
  3577. ASSERT_FALSE(svr.is_running());
  3578. });
  3579. svr.wait_until_ready();
  3580. Client cli(HOST, port);
  3581. cli.set_follow_location(true);
  3582. auto res = cli.Get("/redir");
  3583. EXPECT_FALSE(res);
  3584. }
  3585. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3586. Server svr;
  3587. std::atomic<bool> followed{false};
  3588. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3589. res.status = StatusCode::NotModified_304;
  3590. res.set_header("Location", "/target");
  3591. });
  3592. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3593. res.status = StatusCode::UseProxy_305;
  3594. res.set_header("Location", "/target");
  3595. });
  3596. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3597. followed = true;
  3598. res.set_content("target", "text/plain");
  3599. });
  3600. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3601. auto se = detail::scope_exit([&] {
  3602. svr.stop();
  3603. th.join();
  3604. ASSERT_FALSE(svr.is_running());
  3605. });
  3606. svr.wait_until_ready();
  3607. Client cli("localhost", PORT);
  3608. cli.set_follow_location(true);
  3609. auto res = cli.Get("/304");
  3610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3611. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3612. res = cli.Get("/305");
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3615. EXPECT_FALSE(followed);
  3616. }
  3617. TEST(RedirectFromPageWithContent, Redirect) {
  3618. Server svr;
  3619. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3620. res.set_content("___", "text/plain");
  3621. res.set_redirect("/2");
  3622. });
  3623. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3624. res.set_content("Hello World!", "text/plain");
  3625. });
  3626. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3627. auto se = detail::scope_exit([&] {
  3628. svr.stop();
  3629. th.join();
  3630. ASSERT_FALSE(svr.is_running());
  3631. });
  3632. svr.wait_until_ready();
  3633. {
  3634. Client cli("localhost", PORT);
  3635. cli.set_follow_location(true);
  3636. std::string body;
  3637. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3638. body.append(data, data_length);
  3639. return true;
  3640. });
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ("Hello World!", body);
  3644. }
  3645. {
  3646. Client cli("localhost", PORT);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::Found_302, res->status);
  3654. EXPECT_EQ("___", body);
  3655. }
  3656. }
  3657. // A server can close the connection after a request with "Connection: close"
  3658. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3659. // redirected request must go out on a new connection.
  3660. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3661. #ifndef _WIN32
  3662. signal(SIGPIPE, SIG_IGN);
  3663. #endif
  3664. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3665. default_socket_options(srv);
  3666. sockaddr_in addr{};
  3667. addr.sin_family = AF_INET;
  3668. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3669. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3670. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3671. ASSERT_EQ(0, ::listen(srv, 2));
  3672. auto send_text = [](socket_t sock, const std::string &text) {
  3673. ::send(sock,
  3674. #ifdef _WIN32
  3675. static_cast<const char *>(text.c_str()),
  3676. static_cast<int>(text.size()),
  3677. #else
  3678. text.c_str(), text.size(),
  3679. #endif
  3680. 0);
  3681. };
  3682. auto reused = false;
  3683. auto server_thread = std::thread([&] {
  3684. char buf[4096];
  3685. auto first = ::accept(srv, nullptr, nullptr);
  3686. if (first == INVALID_SOCKET) { return; }
  3687. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3688. ::recv(first, buf, sizeof(buf), 0);
  3689. send_text(
  3690. first,
  3691. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3692. auto next = first;
  3693. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3694. reused = true;
  3695. } else {
  3696. detail::close_socket(first);
  3697. next = ::accept(srv, nullptr, nullptr);
  3698. if (next == INVALID_SOCKET) { return; }
  3699. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3700. ::recv(next, buf, sizeof(buf), 0);
  3701. }
  3702. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3703. "Connection: close\r\n\r\nok");
  3704. detail::close_socket(next);
  3705. });
  3706. Client cli("127.0.0.1", PORT + 2);
  3707. cli.set_follow_location(true);
  3708. cli.set_read_timeout(5, 0);
  3709. auto res = cli.Get("/1");
  3710. server_thread.join();
  3711. detail::close_socket(srv);
  3712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3713. EXPECT_EQ(StatusCode::OK_200, res->status);
  3714. EXPECT_EQ("ok", res->body);
  3715. EXPECT_FALSE(reused);
  3716. }
  3717. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3718. Server svr;
  3719. auto port_str = std::to_string(PORT);
  3720. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3721. auto expected_host = "[::1]:" + port_str;
  3722. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3723. res.set_content("___", "text/plain");
  3724. // res.set_redirect("/2");
  3725. res.set_redirect(redirect_url);
  3726. });
  3727. svr.Get("/2", [&](const Request &req, Response &res) {
  3728. auto host_header = req.headers.find("Host");
  3729. ASSERT_TRUE(host_header != req.headers.end());
  3730. EXPECT_EQ(expected_host, host_header->second);
  3731. res.set_content("Hello World!", "text/plain");
  3732. });
  3733. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3734. auto se = detail::scope_exit([&] {
  3735. svr.stop();
  3736. th.join();
  3737. ASSERT_FALSE(svr.is_running());
  3738. });
  3739. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3740. // actually starts anything, so the condition !svr.is_running() will
  3741. // always remain true, and the loop never stops.
  3742. // This basically counts how many milliseconds have passed since the
  3743. // call to svr.listen(), and if after 5 seconds nothing started yet
  3744. // aborts the test.
  3745. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3746. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3747. ASSERT_LT(milliseconds, 5000U);
  3748. }
  3749. {
  3750. Client cli("::1", PORT);
  3751. cli.set_follow_location(true);
  3752. std::string body;
  3753. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3754. body.append(data, data_length);
  3755. return true;
  3756. });
  3757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3758. EXPECT_EQ(StatusCode::OK_200, res->status);
  3759. EXPECT_EQ("Hello World!", body);
  3760. }
  3761. {
  3762. Client cli("::1", PORT);
  3763. std::string body;
  3764. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3765. body.append(data, data_length);
  3766. return true;
  3767. });
  3768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3769. EXPECT_EQ(StatusCode::Found_302, res->status);
  3770. EXPECT_EQ("___", body);
  3771. }
  3772. }
  3773. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3774. Server svr;
  3775. svr.Get("/foo", [](const Request &req, Response &res) {
  3776. auto a = req.params.find("a");
  3777. if (a != req.params.end()) {
  3778. res.set_content((*a).second, "text/plain");
  3779. res.status = StatusCode::OK_200;
  3780. } else {
  3781. res.status = StatusCode::BadRequest_400;
  3782. }
  3783. });
  3784. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3785. auto se = detail::scope_exit([&] {
  3786. svr.stop();
  3787. thread.join();
  3788. ASSERT_FALSE(svr.is_running());
  3789. });
  3790. svr.wait_until_ready();
  3791. {
  3792. Client cli(HOST, PORT);
  3793. cli.set_path_encode(false);
  3794. auto res = cli.Get("/foo?a=explicitly+encoded");
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. // This expects it back with a space, as the `+` won't have been
  3798. // url-encoded, and server-side the params get decoded turning `+`
  3799. // into spaces.
  3800. EXPECT_EQ("explicitly encoded", res->body);
  3801. }
  3802. }
  3803. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3804. // When path encoding is disabled the client must transmit the supplied
  3805. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3806. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3807. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3808. // than a space (0x20). Assert on the raw wire target to catch this.
  3809. Server svr;
  3810. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3811. svr.Get("/foo", [&](const Request &req, Response &res) {
  3812. EXPECT_EQ(expected_target, req.target);
  3813. res.status = StatusCode::OK_200;
  3814. });
  3815. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3816. auto se = detail::scope_exit([&] {
  3817. svr.stop();
  3818. thread.join();
  3819. ASSERT_FALSE(svr.is_running());
  3820. });
  3821. svr.wait_until_ready();
  3822. {
  3823. Client cli(HOST, PORT);
  3824. cli.set_path_encode(false);
  3825. auto res = cli.Get(expected_target.c_str());
  3826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3827. EXPECT_EQ(StatusCode::OK_200, res->status);
  3828. }
  3829. }
  3830. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3831. // `open_stream()` used to skip the path encoding that the buffered send
  3832. // path applies, so the same `path` produced different bytes in the request
  3833. // line depending on which API was used. Assert the two agree.
  3834. Server svr;
  3835. std::string target;
  3836. svr.Get(".*", [&](const Request &req, Response &res) {
  3837. target = req.target;
  3838. res.status = StatusCode::OK_200;
  3839. });
  3840. auto port = svr.bind_to_any_port(HOST);
  3841. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3842. auto se = detail::scope_exit([&] {
  3843. svr.stop();
  3844. thread.join();
  3845. ASSERT_FALSE(svr.is_running());
  3846. });
  3847. svr.wait_until_ready();
  3848. struct {
  3849. const char *path;
  3850. const char *expected;
  3851. } cases[] = {
  3852. {"/a b?x=1", "/a%20b?x=1"},
  3853. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3854. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3855. };
  3856. for (const auto &c : cases) {
  3857. Client cli(HOST, port);
  3858. target.clear();
  3859. auto res = cli.Get(c.path);
  3860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3861. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3862. auto buffered_target = target;
  3863. target.clear();
  3864. auto handle = cli.open_stream("GET", c.path);
  3865. EXPECT_TRUE(handle.is_valid())
  3866. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3867. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3868. }
  3869. }
  3870. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3871. // The `set_path_encode(false)` contract — transmit the supplied target
  3872. // verbatim — must hold for the streaming API too.
  3873. Server svr;
  3874. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3875. std::string target;
  3876. svr.Get("/foo", [&](const Request &req, Response &res) {
  3877. target = req.target;
  3878. res.status = StatusCode::OK_200;
  3879. });
  3880. auto port = svr.bind_to_any_port(HOST);
  3881. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3882. auto se = detail::scope_exit([&] {
  3883. svr.stop();
  3884. thread.join();
  3885. ASSERT_FALSE(svr.is_running());
  3886. });
  3887. svr.wait_until_ready();
  3888. {
  3889. Client cli(HOST, port);
  3890. cli.set_path_encode(false);
  3891. auto handle = cli.open_stream("GET", expected_target);
  3892. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3893. EXPECT_EQ(expected_target, target);
  3894. }
  3895. }
  3896. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3897. // With path encoding enabled a CR/LF in the target is percent-encoded
  3898. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3899. // write_request_line still backstops `set_path_encode(false)`, which is
  3900. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3901. Server svr;
  3902. // Captured before routing: the decoded path contains a newline, which a
  3903. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3904. std::string target;
  3905. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3906. target = req.target;
  3907. res.status = StatusCode::OK_200;
  3908. return Server::HandlerResponse::Handled;
  3909. });
  3910. auto port = svr.bind_to_any_port(HOST);
  3911. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3912. auto se = detail::scope_exit([&] {
  3913. svr.stop();
  3914. thread.join();
  3915. ASSERT_FALSE(svr.is_running());
  3916. });
  3917. svr.wait_until_ready();
  3918. {
  3919. Client cli(HOST, port);
  3920. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3921. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3922. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3923. }
  3924. }
  3925. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3926. // Every control character is percent-encoded, not just CR/LF, so the target
  3927. // passes the request-target check in write_request_line.
  3928. Server svr;
  3929. std::string target;
  3930. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3931. target = req.target;
  3932. res.status = StatusCode::OK_200;
  3933. return Server::HandlerResponse::Handled;
  3934. });
  3935. auto port = svr.bind_to_any_port(HOST);
  3936. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3937. auto se = detail::scope_exit([&] {
  3938. svr.stop();
  3939. thread.join();
  3940. ASSERT_FALSE(svr.is_running());
  3941. });
  3942. svr.wait_until_ready();
  3943. {
  3944. Client cli(HOST, port);
  3945. auto res = cli.Get("/a\tb\x1b\x7f");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ("/a%09b%1B%7F", target);
  3948. }
  3949. }
  3950. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3951. // Nothing may reach the wire: a raw CR/LF target would split the request
  3952. // line and inject headers.
  3953. Server svr;
  3954. // Pre-routing so that "not called" means nothing reached the server at all,
  3955. // rather than merely failing to match a handler pattern.
  3956. auto handler_called = false;
  3957. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3958. handler_called = true;
  3959. res.status = StatusCode::OK_200;
  3960. return Server::HandlerResponse::Handled;
  3961. });
  3962. auto port = svr.bind_to_any_port(HOST);
  3963. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3964. auto se = detail::scope_exit([&] {
  3965. svr.stop();
  3966. thread.join();
  3967. ASSERT_FALSE(svr.is_running());
  3968. });
  3969. svr.wait_until_ready();
  3970. {
  3971. Client cli(HOST, port);
  3972. cli.set_path_encode(false);
  3973. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3974. EXPECT_FALSE(handle.is_valid());
  3975. EXPECT_EQ(Error::Write, handle.error);
  3976. EXPECT_FALSE(handler_called);
  3977. }
  3978. }
  3979. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3980. // Which of the two branches runs is decided by whether the query component
  3981. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3982. // an empty query and must still fall back to building one from
  3983. // `req.params`, while a non-empty query must win over `req.params`.
  3984. Server svr;
  3985. std::string target;
  3986. svr.Get("/foo", [&](const Request &req, Response &res) {
  3987. target = req.target;
  3988. res.status = StatusCode::OK_200;
  3989. });
  3990. auto port = svr.bind_to_any_port(HOST);
  3991. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3992. auto se = detail::scope_exit([&] {
  3993. svr.stop();
  3994. thread.join();
  3995. ASSERT_FALSE(svr.is_running());
  3996. });
  3997. svr.wait_until_ready();
  3998. {
  3999. // Trailing `?` -> empty query component -> `req.params` is used.
  4000. Client cli(HOST, port);
  4001. Request req;
  4002. req.method = "GET";
  4003. req.path = "/foo?";
  4004. req.params.emplace("a", "1");
  4005. target.clear();
  4006. auto res = cli.send(req);
  4007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4008. EXPECT_EQ("/foo?a=1", target);
  4009. }
  4010. {
  4011. // Non-empty query in `req.path` -> `req.params` is not appended.
  4012. Client cli(HOST, port);
  4013. Request req;
  4014. req.method = "GET";
  4015. req.path = "/foo?b=2";
  4016. req.params.emplace("a", "1");
  4017. target.clear();
  4018. auto res = cli.send(req);
  4019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4020. EXPECT_EQ("/foo?b=2", target);
  4021. }
  4022. }
  4023. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4024. Server svr;
  4025. svr.Get("/", [](const Request &req, Response &) {
  4026. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4027. });
  4028. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4029. auto se = detail::scope_exit([&] {
  4030. svr.stop();
  4031. thread.join();
  4032. ASSERT_FALSE(svr.is_running());
  4033. });
  4034. svr.wait_until_ready();
  4035. {
  4036. Client cli(HOST, PORT);
  4037. cli.set_path_encode(false);
  4038. auto res = cli.Get("/?something=%0A");
  4039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4040. EXPECT_EQ(StatusCode::OK_200, res->status);
  4041. }
  4042. }
  4043. TEST(BindServerTest, BindDualStack) {
  4044. Server svr;
  4045. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4046. res.set_content("Hello World!", "text/plain");
  4047. });
  4048. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4049. auto se = detail::scope_exit([&] {
  4050. svr.stop();
  4051. thread.join();
  4052. ASSERT_FALSE(svr.is_running());
  4053. });
  4054. svr.wait_until_ready();
  4055. {
  4056. Client cli("127.0.0.1", PORT);
  4057. auto res = cli.Get("/1");
  4058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4059. EXPECT_EQ(StatusCode::OK_200, res->status);
  4060. EXPECT_EQ("Hello World!", res->body);
  4061. }
  4062. {
  4063. Client cli("::1", PORT);
  4064. auto res = cli.Get("/1");
  4065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4066. EXPECT_EQ(StatusCode::OK_200, res->status);
  4067. EXPECT_EQ("Hello World!", res->body);
  4068. }
  4069. }
  4070. TEST(BindServerTest, BindAndListenSeparately) {
  4071. Server svr;
  4072. int port = svr.bind_to_any_port("0.0.0.0");
  4073. ASSERT_TRUE(svr.is_valid());
  4074. ASSERT_TRUE(port > 0);
  4075. svr.stop();
  4076. }
  4077. // Reports whether anything is still listening on a loopback port. A plain
  4078. // connect() is used instead of a Client request because a socket left bound by
  4079. // mistake accepts the connection into its backlog and never answers, which
  4080. // would hang the test instead of failing it.
  4081. static bool is_loopback_port_accepting(int port) {
  4082. sockaddr_in addr{};
  4083. addr.sin_family = AF_INET;
  4084. addr.sin_port = htons(static_cast<uint16_t>(port));
  4085. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4086. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4087. EXPECT_NE(sock, INVALID_SOCKET);
  4088. if (sock == INVALID_SOCKET) { return false; }
  4089. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4090. static_cast<socklen_t>(sizeof(addr)));
  4091. detail::close_socket(sock);
  4092. return ret == 0;
  4093. }
  4094. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4095. Server svr;
  4096. auto port = svr.bind_to_any_port("127.0.0.1");
  4097. ASSERT_TRUE(port > 0);
  4098. svr.stop();
  4099. // bind_to_any_port() already called listen(2), so until stop() closed the
  4100. // descriptor the port kept accepting connections into the backlog. ASSERT
  4101. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4102. // below blocks forever in the accept loop.
  4103. ASSERT_FALSE(is_loopback_port_accepting(port));
  4104. // Nothing is left to accept on, so listen_after_bind() must report failure
  4105. // instead of returning success without ever serving.
  4106. EXPECT_FALSE(svr.listen_after_bind());
  4107. // The failed listen marks the server decommissioned, so a waiter returns
  4108. // instead of spinning forever.
  4109. svr.wait_until_ready();
  4110. }
  4111. #ifdef CPPHTTPLIB_SSL_ENABLED
  4112. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4114. CLIENT_CA_CERT_DIR);
  4115. int port = svr.bind_to_any_port("0.0.0.0");
  4116. ASSERT_TRUE(svr.is_valid());
  4117. ASSERT_TRUE(port > 0);
  4118. svr.stop();
  4119. }
  4120. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4121. // or a rejected CustomRoute() registration would not stop the server binding.
  4122. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4123. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4124. CLIENT_CA_CERT_DIR);
  4125. ASSERT_TRUE(svr.is_valid());
  4126. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4127. EXPECT_FALSE(svr.is_valid());
  4128. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4129. }
  4130. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4131. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4132. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4133. int port = svr.bind_to_any_port("0.0.0.0");
  4134. ASSERT_TRUE(svr.is_valid());
  4135. ASSERT_TRUE(port > 0);
  4136. svr.stop();
  4137. }
  4138. TEST(BindServerTest, UpdateCertsPem) {
  4139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4140. int port = svr.bind_to_any_port("0.0.0.0");
  4141. ASSERT_TRUE(svr.is_valid());
  4142. ASSERT_TRUE(port > 0);
  4143. // Read PEM files
  4144. std::string cert_pem, key_pem, ca_pem;
  4145. read_file(SERVER_CERT_FILE, cert_pem);
  4146. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4147. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4148. // Update server certificates using PEM API
  4149. ASSERT_TRUE(
  4150. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4151. ASSERT_TRUE(svr.is_valid());
  4152. svr.stop();
  4153. }
  4154. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4155. // Start server with client CA (enables client auth)
  4156. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4157. ASSERT_TRUE(svr.is_valid());
  4158. bool handler_called = false;
  4159. svr.Get("/test", [&](const Request &req, Response &res) {
  4160. handler_called = true;
  4161. // Verify client certificate is present
  4162. auto cert = req.peer_cert();
  4163. EXPECT_TRUE(static_cast<bool>(cert));
  4164. res.set_content("ok", "text/plain");
  4165. });
  4166. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4167. auto se = detail::scope_exit([&] {
  4168. svr.stop();
  4169. t.join();
  4170. ASSERT_FALSE(svr.is_running());
  4171. });
  4172. svr.wait_until_ready();
  4173. // Read PEM files
  4174. std::string cert_pem, key_pem, ca_pem;
  4175. read_file(SERVER_CERT_FILE, cert_pem);
  4176. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4177. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4178. // Update server certificates and client CA using PEM API while server running
  4179. ASSERT_TRUE(
  4180. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4181. // Connect with client certificate
  4182. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4183. cli.enable_server_certificate_verification(false);
  4184. cli.set_connection_timeout(30);
  4185. auto res = cli.Get("/test");
  4186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4187. ASSERT_EQ(StatusCode::OK_200, res->status);
  4188. ASSERT_TRUE(handler_called);
  4189. EXPECT_EQ("ok", res->body);
  4190. }
  4191. // Puts a CA that did not sign the client's certificate in the old one's place.
  4192. static bool replace_client_ca(SSLServer &svr) {
  4193. std::string cert_pem, key_pem, ca_pem;
  4194. read_file(SERVER_CERT_FILE, cert_pem);
  4195. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4196. read_file(SERVER_CERT2_FILE, ca_pem);
  4197. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4198. ca_pem.c_str());
  4199. }
  4200. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4202. ASSERT_TRUE(svr.is_valid());
  4203. svr.Get("/test", [](const Request &, Response &res) {
  4204. res.set_content("ok", "text/plain");
  4205. });
  4206. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4207. auto se = detail::scope_exit([&] {
  4208. svr.stop();
  4209. t.join();
  4210. ASSERT_FALSE(svr.is_running());
  4211. });
  4212. svr.wait_until_ready();
  4213. auto get = [] {
  4214. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4215. cli.enable_server_certificate_verification(false);
  4216. return cli.Get("/test");
  4217. };
  4218. ASSERT_TRUE(get());
  4219. ASSERT_TRUE(replace_client_ca(svr));
  4220. EXPECT_FALSE(get());
  4221. }
  4222. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4223. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4224. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4225. ASSERT_TRUE(svr.is_valid());
  4226. tls::set_verify_callback(svr.tls_context(),
  4227. [](const tls::VerifyContext &) -> bool {
  4228. throw std::runtime_error("verify");
  4229. });
  4230. svr.Get("/test", [](const Request &, Response &res) {
  4231. res.set_content("ok", "text/plain");
  4232. });
  4233. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4234. auto se = detail::scope_exit([&] {
  4235. svr.stop();
  4236. t.join();
  4237. ASSERT_FALSE(svr.is_running());
  4238. });
  4239. svr.wait_until_ready();
  4240. auto get = [] {
  4241. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4242. cli.enable_server_certificate_verification(false);
  4243. return cli.Get("/test");
  4244. };
  4245. EXPECT_FALSE(get());
  4246. // The handshake is over, so an update does not wait for it.
  4247. std::string cert_pem, key_pem;
  4248. read_file(SERVER_CERT_FILE, cert_pem);
  4249. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4250. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4251. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4252. return v.preverify_ok;
  4253. });
  4254. auto res = get();
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ("ok", res->body);
  4257. }
  4258. #endif
  4259. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4260. // Sends each request over a new connection with a client certificate,
  4261. // resuming the session of the one before when there is one.
  4262. class ResumingClient {
  4263. public:
  4264. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4265. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4266. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4267. SSL_FILETYPE_PEM);
  4268. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4269. // callback, not through SSL_get1_session().
  4270. SSL_CTX_set_app_data(ctx_, this);
  4271. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4272. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4273. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4274. auto self = static_cast<ResumingClient *>(
  4275. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4276. SSL_SESSION_free(self->session_);
  4277. self->session_ = session;
  4278. return 1; // Keeps the reference
  4279. });
  4280. }
  4281. ~ResumingClient() {
  4282. SSL_SESSION_free(session_);
  4283. SSL_CTX_free(ctx_);
  4284. }
  4285. // Tells whether the request was answered.
  4286. bool get() {
  4287. auto error = Error::Success;
  4288. auto sock = detail::create_client_socket(
  4289. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4290. /*connection_timeout_sec=*/5, 0,
  4291. /*read_timeout_sec=*/5, 0,
  4292. /*write_timeout_sec=*/5, 0, std::string(), error);
  4293. if (sock == INVALID_SOCKET) { return false; }
  4294. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4295. auto ssl = SSL_new(ctx_);
  4296. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4297. SSL_set_fd(ssl, static_cast<int>(sock));
  4298. if (session_) { SSL_set_session(ssl, session_); }
  4299. if (SSL_connect(ssl) != 1) { return false; }
  4300. reused_ = SSL_session_reused(ssl) == 1;
  4301. // Reading the response also takes in a TLS 1.3 session ticket.
  4302. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4303. "Connection: close\r\n\r\n";
  4304. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4305. std::string res;
  4306. char buf[256];
  4307. int n;
  4308. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4309. res.append(buf, static_cast<size_t>(n));
  4310. }
  4311. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4312. SSL_shutdown(ssl);
  4313. return res.find("200 OK") != std::string::npos;
  4314. }
  4315. // Whether the last connection resumed a session
  4316. bool reused() const { return reused_; }
  4317. private:
  4318. SSL_CTX *ctx_;
  4319. SSL_SESSION *session_ = nullptr;
  4320. bool reused_ = false;
  4321. };
  4322. // A client that resumes its session gets through, but not once the client CA
  4323. // has changed, as a resumed session does not show the certificate again.
  4324. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4325. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4326. ASSERT_TRUE(svr.is_valid());
  4327. svr.Get("/test", [](const Request &, Response &res) {
  4328. res.set_content("ok", "text/plain");
  4329. });
  4330. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4331. auto se = detail::scope_exit([&] {
  4332. svr.stop();
  4333. t.join();
  4334. ASSERT_FALSE(svr.is_running());
  4335. });
  4336. svr.wait_until_ready();
  4337. ResumingClient cli;
  4338. ASSERT_TRUE(cli.get());
  4339. ASSERT_TRUE(cli.get());
  4340. EXPECT_TRUE(cli.reused());
  4341. ASSERT_TRUE(replace_client_ca(svr));
  4342. EXPECT_FALSE(cli.get());
  4343. }
  4344. // A resumed session does not show the certificate again, so the server does
  4345. // not resume one with a verify callback to run on it.
  4346. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4348. ASSERT_TRUE(svr.is_valid());
  4349. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4350. return v.preverify_ok;
  4351. });
  4352. svr.Get("/test", [](const Request &, Response &res) {
  4353. res.set_content("ok", "text/plain");
  4354. });
  4355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4356. auto se = detail::scope_exit([&] {
  4357. svr.stop();
  4358. t.join();
  4359. ASSERT_FALSE(svr.is_running());
  4360. });
  4361. svr.wait_until_ready();
  4362. ResumingClient cli;
  4363. ASSERT_TRUE(cli.get());
  4364. ASSERT_TRUE(cli.get());
  4365. EXPECT_FALSE(cli.reused());
  4366. }
  4367. #endif
  4368. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4369. // wolfSSL shares its session cache between contexts, so a resumed session
  4370. // could carry a client certificate checked against another server's CA, or
  4371. // against a client CA since replaced.
  4372. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4374. ASSERT_TRUE(svr.is_valid());
  4375. // Trusts a CA that did not sign the client's certificate.
  4376. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4377. ASSERT_TRUE(other.is_valid());
  4378. for (auto s : {&svr, &other}) {
  4379. s->Get("/test", [](const Request &, Response &res) {
  4380. res.set_content("ok", "text/plain");
  4381. });
  4382. }
  4383. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4384. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4385. auto se = detail::scope_exit([&] {
  4386. other.stop();
  4387. svr.stop();
  4388. t2.join();
  4389. t.join();
  4390. });
  4391. svr.wait_until_ready();
  4392. other.wait_until_ready();
  4393. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4394. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4395. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4396. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4397. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4398. ASSERT_EQ(WOLFSSL_SUCCESS,
  4399. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4400. WOLFSSL_FILETYPE_PEM));
  4401. WOLFSSL_SESSION *session = nullptr;
  4402. auto session_se = detail::scope_exit([&] {
  4403. if (session) { wolfSSL_SESSION_free(session); }
  4404. });
  4405. // A request over a new connection, resuming `session` when there is one and
  4406. // keeping the connection's own in its place. Tells whether it was answered.
  4407. auto get = [&](int port) {
  4408. auto error = Error::Success;
  4409. auto sock = detail::create_client_socket(
  4410. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4411. /*connection_timeout_sec=*/5, 0,
  4412. /*read_timeout_sec=*/5, 0,
  4413. /*write_timeout_sec=*/5, 0, std::string(), error);
  4414. if (sock == INVALID_SOCKET) { return false; }
  4415. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4416. auto ssl = wolfSSL_new(ctx);
  4417. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4418. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4419. if (session) { wolfSSL_set_session(ssl, session); }
  4420. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4421. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4422. "Connection: close\r\n\r\n";
  4423. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4424. std::string res;
  4425. char buf[256];
  4426. int n;
  4427. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4428. res.append(buf, static_cast<size_t>(n));
  4429. }
  4430. wolfSSL_shutdown(ssl);
  4431. if (session) { wolfSSL_SESSION_free(session); }
  4432. session = wolfSSL_get1_session(ssl);
  4433. return res.find("200 OK") != std::string::npos;
  4434. };
  4435. ASSERT_TRUE(get(PORT));
  4436. EXPECT_FALSE(get(PORT + 1));
  4437. ASSERT_TRUE(get(PORT));
  4438. ASSERT_TRUE(replace_client_ca(svr));
  4439. EXPECT_FALSE(get(PORT));
  4440. }
  4441. #endif
  4442. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4444. ASSERT_TRUE(svr.is_valid());
  4445. svr.Get("/test", [](const Request &, Response &res) {
  4446. res.set_content("ok", "text/plain");
  4447. });
  4448. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4449. auto se = detail::scope_exit([&] {
  4450. svr.stop();
  4451. t.join();
  4452. ASSERT_FALSE(svr.is_running());
  4453. });
  4454. svr.wait_until_ready();
  4455. // A connection that sends no ClientHello keeps its handshake in progress,
  4456. // once the server has had a moment to start it.
  4457. auto error = Error::Success;
  4458. auto sock = detail::create_client_socket(
  4459. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4460. /*connection_timeout_sec=*/5, 0,
  4461. /*read_timeout_sec=*/5, 0,
  4462. /*write_timeout_sec=*/5, 0, std::string(), error);
  4463. ASSERT_NE(INVALID_SOCKET, sock);
  4464. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4465. std::string cert_pem, key_pem;
  4466. read_file(SERVER_CERT_FILE, cert_pem);
  4467. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4468. auto update = std::async(std::launch::async, [&]() {
  4469. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4470. });
  4471. EXPECT_EQ(std::future_status::timeout,
  4472. update.wait_for(std::chrono::milliseconds(200)));
  4473. detail::close_socket(sock);
  4474. EXPECT_TRUE(update.get());
  4475. SSLClient cli(HOST, PORT);
  4476. cli.enable_server_certificate_verification(false);
  4477. auto res = cli.Get("/test");
  4478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4479. EXPECT_EQ(StatusCode::OK_200, res->status);
  4480. }
  4481. #endif
  4482. TEST(ErrorHandlerTest, ContentLength) {
  4483. Server svr;
  4484. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4485. res.status = StatusCode::OK_200;
  4486. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4487. "text/html"); // <= Content-Length still 13
  4488. });
  4489. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4490. res.set_content("Hello World!\n", "text/plain");
  4491. res.status = 524;
  4492. });
  4493. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4494. auto se = detail::scope_exit([&] {
  4495. svr.stop();
  4496. thread.join();
  4497. ASSERT_FALSE(svr.is_running());
  4498. });
  4499. svr.wait_until_ready();
  4500. {
  4501. Client cli(HOST, PORT);
  4502. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ(StatusCode::OK_200, res->status);
  4505. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4506. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4507. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4508. }
  4509. }
  4510. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4511. TEST(ExceptionTest, WithoutExceptionHandler) {
  4512. Server svr;
  4513. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4514. throw std::runtime_error("exception...");
  4515. });
  4516. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4517. throw std::runtime_error("exception\r\n...");
  4518. });
  4519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4520. auto se = detail::scope_exit([&] {
  4521. svr.stop();
  4522. listen_thread.join();
  4523. ASSERT_FALSE(svr.is_running());
  4524. });
  4525. svr.wait_until_ready();
  4526. Client cli("localhost", PORT);
  4527. {
  4528. auto res = cli.Get("/exception");
  4529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4530. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4531. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4532. }
  4533. {
  4534. auto res = cli.Get("/unknown");
  4535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4536. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4537. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4538. }
  4539. }
  4540. TEST(ExceptionTest, WithExceptionHandler) {
  4541. Server svr;
  4542. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4543. std::exception_ptr ep) {
  4544. EXPECT_FALSE(ep == nullptr);
  4545. try {
  4546. std::rethrow_exception(ep);
  4547. } catch (std::exception &e) {
  4548. EXPECT_EQ("abc", std::string(e.what()));
  4549. } catch (...) {}
  4550. res.status = StatusCode::InternalServerError_500;
  4551. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4552. "text/html"); // <= Content-Length still 13 at this point
  4553. });
  4554. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4555. res.set_content("Hello World!\n", "text/plain");
  4556. throw std::runtime_error("abc");
  4557. });
  4558. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4559. auto se = detail::scope_exit([&] {
  4560. svr.stop();
  4561. thread.join();
  4562. ASSERT_FALSE(svr.is_running());
  4563. });
  4564. svr.wait_until_ready();
  4565. for (size_t i = 0; i < 10; i++) {
  4566. Client cli(HOST, PORT);
  4567. for (size_t j = 0; j < 100; j++) {
  4568. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4570. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4571. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4572. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4573. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4574. }
  4575. cli.set_keep_alive(true);
  4576. for (size_t j = 0; j < 100; j++) {
  4577. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4579. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4580. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4581. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4582. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4583. }
  4584. }
  4585. }
  4586. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4587. Server svr;
  4588. svr.set_exception_handler(
  4589. [](const Request &, Response &res, std::exception_ptr) {
  4590. res.set_content("oops", "text/plain");
  4591. });
  4592. svr.Get("/throw", [](const Request &, Response &) {
  4593. throw std::runtime_error("throw");
  4594. });
  4595. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4596. res.status = StatusCode::Created_201;
  4597. throw std::runtime_error("created-then-throw");
  4598. });
  4599. auto port = svr.bind_to_any_port(HOST);
  4600. ASSERT_GT(port, 0);
  4601. thread t = thread([&] { svr.listen_after_bind(); });
  4602. auto se = detail::scope_exit([&] {
  4603. svr.stop();
  4604. t.join();
  4605. ASSERT_FALSE(svr.is_running());
  4606. });
  4607. svr.wait_until_ready();
  4608. Client cli(HOST, port);
  4609. for (auto path : {"/throw", "/created-then-throw"}) {
  4610. auto res = cli.Get(path);
  4611. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4612. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4613. }
  4614. }
  4615. TEST(ExceptionTest, AndErrorHandler) {
  4616. Server svr;
  4617. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4618. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4619. });
  4620. svr.set_exception_handler(
  4621. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4622. EXPECT_FALSE(ep == nullptr);
  4623. try {
  4624. std::rethrow_exception(ep);
  4625. } catch (std::exception &e) {
  4626. res.set_content(e.what(), "text/html");
  4627. } catch (...) {}
  4628. res.status = StatusCode::InternalServerError_500;
  4629. });
  4630. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4631. throw std::runtime_error("EXCEPTION");
  4632. });
  4633. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4634. res.set_content("ERROR", "text/html");
  4635. res.status = StatusCode::InternalServerError_500;
  4636. });
  4637. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4638. auto se = detail::scope_exit([&] {
  4639. svr.stop();
  4640. thread.join();
  4641. ASSERT_FALSE(svr.is_running());
  4642. });
  4643. svr.wait_until_ready();
  4644. Client cli(HOST, PORT);
  4645. {
  4646. auto res = cli.Get("/exception");
  4647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4648. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4649. EXPECT_EQ("EXCEPTION", res->body);
  4650. }
  4651. {
  4652. auto res = cli.Get("/error");
  4653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4654. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4655. EXPECT_EQ("ERROR", res->body);
  4656. }
  4657. {
  4658. auto res = cli.Get("/invalid");
  4659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4660. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4661. EXPECT_EQ("NOT_FOUND", res->body);
  4662. }
  4663. }
  4664. #endif
  4665. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4666. // An exception from a user callback outside process_request()'s try/catch
  4667. // used to unwind into the task queue - which does not catch - and terminate
  4668. // the process. Each test below runs the server on a single worker thread: a
  4669. // guard that catches the exception but still loses the thread would otherwise
  4670. // be hidden by a spare worker serving the follow-up request. Note that a
  4671. // regression here aborts the whole test binary rather than failing one test.
  4672. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4673. Server svr;
  4674. svr.new_task_queue = [] { return new ThreadPool(1); };
  4675. std::atomic<int> reported{0};
  4676. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4677. if (err == Error::UserCallbackException) { reported++; }
  4678. });
  4679. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4680. res.set_content_provider(
  4681. 1024, "text/plain",
  4682. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4683. sink.write("hello", 5);
  4684. throw std::runtime_error("from the content provider");
  4685. });
  4686. });
  4687. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4688. res.set_content("ok", "text/plain");
  4689. });
  4690. auto port = svr.bind_to_any_port(HOST);
  4691. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4692. auto se = detail::scope_exit([&] {
  4693. svr.stop();
  4694. listen_thread.join();
  4695. ASSERT_FALSE(svr.is_running());
  4696. });
  4697. svr.wait_until_ready();
  4698. {
  4699. Client cli(HOST, port);
  4700. cli.set_read_timeout(5, 0);
  4701. EXPECT_FALSE(cli.Get("/throw"));
  4702. }
  4703. EXPECT_TRUE(svr.is_running());
  4704. EXPECT_EQ(1, reported.load());
  4705. // A request on a fresh connection is still served.
  4706. {
  4707. Client cli(HOST, port);
  4708. auto res = cli.Get("/ok");
  4709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4710. EXPECT_EQ(StatusCode::OK_200, res->status);
  4711. EXPECT_EQ("ok", res->body);
  4712. }
  4713. }
  4714. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4715. Server svr;
  4716. svr.new_task_queue = [] { return new ThreadPool(1); };
  4717. std::atomic<bool> should_throw{true};
  4718. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4719. res.set_content("hi", "text/plain");
  4720. });
  4721. svr.set_post_routing_handler(
  4722. [&](const Request & /*req*/, Response & /*res*/) {
  4723. if (should_throw) {
  4724. throw std::runtime_error("from the post-routing handler");
  4725. }
  4726. });
  4727. auto port = svr.bind_to_any_port(HOST);
  4728. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4729. auto se = detail::scope_exit([&] {
  4730. svr.stop();
  4731. listen_thread.join();
  4732. ASSERT_FALSE(svr.is_running());
  4733. });
  4734. svr.wait_until_ready();
  4735. {
  4736. Client cli(HOST, port);
  4737. cli.set_read_timeout(5, 0);
  4738. EXPECT_FALSE(cli.Get("/hi"));
  4739. }
  4740. EXPECT_TRUE(svr.is_running());
  4741. should_throw = false;
  4742. {
  4743. Client cli(HOST, port);
  4744. auto res = cli.Get("/hi");
  4745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. EXPECT_EQ("hi", res->body);
  4748. }
  4749. }
  4750. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4751. // The guard reports the caught exception through the error logger, which is
  4752. // a user callback too. A logger that throws has to be contained as well, or
  4753. // the process would terminate from inside the catch.
  4754. Server svr;
  4755. svr.new_task_queue = [] { return new ThreadPool(1); };
  4756. std::atomic<int> reported{0};
  4757. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4758. if (err == Error::UserCallbackException) {
  4759. reported++;
  4760. throw std::runtime_error("from the error logger");
  4761. }
  4762. });
  4763. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4764. res.set_content_provider(
  4765. 1024, "text/plain",
  4766. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4767. sink.write("hello", 5);
  4768. throw std::runtime_error("from the content provider");
  4769. });
  4770. });
  4771. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4772. res.set_content("ok", "text/plain");
  4773. });
  4774. auto port = svr.bind_to_any_port(HOST);
  4775. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4776. auto se = detail::scope_exit([&] {
  4777. svr.stop();
  4778. listen_thread.join();
  4779. ASSERT_FALSE(svr.is_running());
  4780. });
  4781. svr.wait_until_ready();
  4782. {
  4783. Client cli(HOST, port);
  4784. cli.set_read_timeout(5, 0);
  4785. EXPECT_FALSE(cli.Get("/throw"));
  4786. }
  4787. EXPECT_TRUE(svr.is_running());
  4788. EXPECT_EQ(1, reported.load());
  4789. {
  4790. Client cli(HOST, port);
  4791. auto res = cli.Get("/ok");
  4792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4793. EXPECT_EQ(StatusCode::OK_200, res->status);
  4794. EXPECT_EQ("ok", res->body);
  4795. }
  4796. }
  4797. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4798. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4799. // so the exception unwinds through the ws::WebSocket object on its way to
  4800. // the guard. None of the HTTP cases above cross that.
  4801. Server svr;
  4802. svr.new_task_queue = [] { return new ThreadPool(1); };
  4803. std::atomic<int> reported{0};
  4804. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4805. if (err == Error::UserCallbackException) { reported++; }
  4806. });
  4807. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4808. throw std::runtime_error("from the WebSocket handler");
  4809. });
  4810. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4811. res.set_content("ok", "text/plain");
  4812. });
  4813. auto port = svr.bind_to_any_port(HOST);
  4814. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4815. auto se = detail::scope_exit([&] {
  4816. svr.stop();
  4817. listen_thread.join();
  4818. ASSERT_FALSE(svr.is_running());
  4819. });
  4820. svr.wait_until_ready();
  4821. {
  4822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4823. "/ws");
  4824. auto res = client.connect();
  4825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4826. // The server dropped the connection instead of dying.
  4827. std::string msg;
  4828. EXPECT_FALSE(client.read(msg));
  4829. client.close();
  4830. }
  4831. EXPECT_TRUE(svr.is_running());
  4832. EXPECT_EQ(1, reported.load());
  4833. {
  4834. Client cli(HOST, port);
  4835. auto res = cli.Get("/ok");
  4836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4837. EXPECT_EQ(StatusCode::OK_200, res->status);
  4838. EXPECT_EQ("ok", res->body);
  4839. }
  4840. }
  4841. #ifdef CPPHTTPLIB_SSL_ENABLED
  4842. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4843. // SSLServer::process_and_close_socket() is a separate overload with its own
  4844. // guard, so it is exercised on its own.
  4845. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4846. ASSERT_TRUE(svr.is_valid());
  4847. svr.new_task_queue = [] { return new ThreadPool(1); };
  4848. std::atomic<int> reported{0};
  4849. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4850. if (err == Error::UserCallbackException) { reported++; }
  4851. });
  4852. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4853. res.set_content_provider(
  4854. 1024, "text/plain",
  4855. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4856. sink.write("hello", 5);
  4857. throw std::runtime_error("from the content provider");
  4858. });
  4859. });
  4860. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4861. res.set_content("ok", "text/plain");
  4862. });
  4863. auto port = svr.bind_to_any_port(HOST);
  4864. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4865. auto se = detail::scope_exit([&] {
  4866. svr.stop();
  4867. listen_thread.join();
  4868. ASSERT_FALSE(svr.is_running());
  4869. });
  4870. svr.wait_until_ready();
  4871. {
  4872. SSLClient cli(HOST, port);
  4873. cli.enable_server_certificate_verification(false);
  4874. cli.set_read_timeout(5, 0);
  4875. EXPECT_FALSE(cli.Get("/throw"));
  4876. }
  4877. EXPECT_TRUE(svr.is_running());
  4878. EXPECT_EQ(1, reported.load());
  4879. {
  4880. SSLClient cli(HOST, port);
  4881. cli.enable_server_certificate_verification(false);
  4882. auto res = cli.Get("/ok");
  4883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4884. EXPECT_EQ(StatusCode::OK_200, res->status);
  4885. EXPECT_EQ("ok", res->body);
  4886. }
  4887. }
  4888. #endif
  4889. #endif
  4890. TEST(NoContentTest, ContentLength) {
  4891. Server svr;
  4892. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4893. res.status = StatusCode::NoContent_204;
  4894. });
  4895. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4896. auto se = detail::scope_exit([&] {
  4897. svr.stop();
  4898. thread.join();
  4899. ASSERT_FALSE(svr.is_running());
  4900. });
  4901. svr.wait_until_ready();
  4902. {
  4903. Client cli(HOST, PORT);
  4904. auto res = cli.Get("/hi");
  4905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4906. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4907. // RFC 9110 8.6: none in a 204 response
  4908. EXPECT_FALSE(res->has_header("Content-Length"));
  4909. }
  4910. }
  4911. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4912. Server svr;
  4913. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4914. res.set_header("Content-Length", "5");
  4915. res.set_content("hello world", "text/plain");
  4916. });
  4917. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4918. // A body that reads as the last chunk, were it taken as chunked
  4919. res.set_header("Transfer-Encoding", "chunked");
  4920. res.set_content("0\r\n\r\n", "text/plain");
  4921. });
  4922. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4923. res.set_header("Content-Length", "2");
  4924. res.set_content_provider(5, "text/plain",
  4925. [](size_t offset, size_t length, DataSink &sink) {
  4926. sink.write(&"hello"[offset], length);
  4927. return true;
  4928. });
  4929. });
  4930. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4931. res.set_header("Content-Length", "1234");
  4932. });
  4933. thread t = thread([&] { svr.listen(HOST, PORT); });
  4934. auto se = detail::scope_exit([&] {
  4935. svr.stop();
  4936. t.join();
  4937. ASSERT_FALSE(svr.is_running());
  4938. });
  4939. svr.wait_until_ready();
  4940. Client cli(HOST, PORT);
  4941. cli.set_read_timeout(1, 0);
  4942. auto expect_body = [&](const Result &res, const std::string &body) {
  4943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4944. EXPECT_EQ(body, res->body);
  4945. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4946. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4947. };
  4948. Headers identity{{"Accept-Encoding", ""}};
  4949. expect_body(cli.Get("/body", identity), "hello world");
  4950. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4951. expect_body(cli.Get("/body",
  4952. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4953. "he");
  4954. expect_body(cli.Get("/provider", identity), "hello");
  4955. expect_body(cli.Get("/empty", identity), "");
  4956. // A HEAD response may give the length of the body a GET would get.
  4957. auto res = cli.Head("/empty");
  4958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4959. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4960. }
  4961. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4962. Server svr;
  4963. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4964. res.set_content("short", "text/plain");
  4965. });
  4966. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4967. res.body += " with a footer";
  4968. res.set_header("Transfer-Encoding", "chunked");
  4969. });
  4970. thread t = thread([&] { svr.listen(HOST, PORT); });
  4971. auto se = detail::scope_exit([&] {
  4972. svr.stop();
  4973. t.join();
  4974. ASSERT_FALSE(svr.is_running());
  4975. });
  4976. svr.wait_until_ready();
  4977. Client cli(HOST, PORT);
  4978. cli.set_read_timeout(1, 0);
  4979. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ("short with a footer", res->body);
  4982. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4983. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4984. }
  4985. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4986. Server svr;
  4987. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4988. res.set_header("Content-Length", "3");
  4989. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4990. sink.write("abc", 3);
  4991. sink.done();
  4992. return true;
  4993. });
  4994. });
  4995. thread t = thread([&] { svr.listen(HOST, PORT); });
  4996. auto se = detail::scope_exit([&] {
  4997. svr.stop();
  4998. t.join();
  4999. ASSERT_FALSE(svr.is_running());
  5000. });
  5001. svr.wait_until_ready();
  5002. Client cli(HOST, PORT);
  5003. cli.set_keep_alive(true);
  5004. auto res = cli.Get("/");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ("abc", res->body);
  5007. EXPECT_FALSE(res->has_header("Content-Length"));
  5008. EXPECT_EQ("close", res->get_header_value("Connection"));
  5009. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5010. // No body to delimit
  5011. auto head = cli.Head("/");
  5012. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5013. EXPECT_FALSE(head->has_header("Connection"));
  5014. }
  5015. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5016. #ifdef CPPHTTPLIB_SSL_ENABLED
  5017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5018. ASSERT_TRUE(svr.is_valid());
  5019. #else
  5020. Server svr;
  5021. #endif
  5022. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5023. if (req.path == "/routing_handler") {
  5024. res.set_header("PRE_ROUTING", "on");
  5025. res.set_content("Routing Handler", "text/plain");
  5026. return httplib::Server::HandlerResponse::Handled;
  5027. }
  5028. return httplib::Server::HandlerResponse::Unhandled;
  5029. });
  5030. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5031. res.set_content("Error", "text/html");
  5032. });
  5033. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5034. if (req.path == "/routing_handler") {
  5035. res.set_header("POST_ROUTING", "on");
  5036. }
  5037. });
  5038. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5039. res.set_content("Hello World!\n", "text/plain");
  5040. });
  5041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5042. auto se = detail::scope_exit([&] {
  5043. svr.stop();
  5044. thread.join();
  5045. ASSERT_FALSE(svr.is_running());
  5046. });
  5047. svr.wait_until_ready();
  5048. {
  5049. #ifdef CPPHTTPLIB_SSL_ENABLED
  5050. SSLClient cli(HOST, PORT);
  5051. cli.enable_server_certificate_verification(false);
  5052. #else
  5053. Client cli(HOST, PORT);
  5054. #endif
  5055. auto res = cli.Get("/routing_handler");
  5056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5057. EXPECT_EQ(StatusCode::OK_200, res->status);
  5058. EXPECT_EQ("Routing Handler", res->body);
  5059. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5060. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5061. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5062. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5063. }
  5064. {
  5065. #ifdef CPPHTTPLIB_SSL_ENABLED
  5066. SSLClient cli(HOST, PORT);
  5067. cli.enable_server_certificate_verification(false);
  5068. #else
  5069. Client cli(HOST, PORT);
  5070. #endif
  5071. auto res = cli.Get("/hi");
  5072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5073. EXPECT_EQ(StatusCode::OK_200, res->status);
  5074. EXPECT_EQ("Hello World!\n", res->body);
  5075. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5076. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5077. }
  5078. {
  5079. #ifdef CPPHTTPLIB_SSL_ENABLED
  5080. SSLClient cli(HOST, PORT);
  5081. cli.enable_server_certificate_verification(false);
  5082. #else
  5083. Client cli(HOST, PORT);
  5084. #endif
  5085. auto res = cli.Get("/aaa");
  5086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5087. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5088. EXPECT_EQ("Error", res->body);
  5089. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5090. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5091. }
  5092. }
  5093. TEST(RequestHandlerTest, PreRequestHandler) {
  5094. auto route_path = "/user/:user";
  5095. Server svr;
  5096. svr.Get("/hi", [](const Request &, Response &res) {
  5097. res.set_content("hi", "text/plain");
  5098. });
  5099. svr.Get(route_path, [](const Request &req, Response &res) {
  5100. res.set_content(req.path_params.at("user"), "text/plain");
  5101. });
  5102. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5103. if (req.matched_route == route_path) {
  5104. auto user = req.path_params.at("user");
  5105. if (user != "john") {
  5106. res.status = StatusCode::Forbidden_403;
  5107. res.set_content("error", "text/html");
  5108. return Server::HandlerResponse::Handled;
  5109. }
  5110. }
  5111. return Server::HandlerResponse::Unhandled;
  5112. });
  5113. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5114. auto se = detail::scope_exit([&] {
  5115. svr.stop();
  5116. thread.join();
  5117. ASSERT_FALSE(svr.is_running());
  5118. });
  5119. svr.wait_until_ready();
  5120. Client cli(HOST, PORT);
  5121. {
  5122. auto res = cli.Get("/hi");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::OK_200, res->status);
  5125. EXPECT_EQ("hi", res->body);
  5126. }
  5127. {
  5128. auto res = cli.Get("/user/john");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ(StatusCode::OK_200, res->status);
  5131. EXPECT_EQ("john", res->body);
  5132. }
  5133. {
  5134. auto res = cli.Get("/user/invalid-user");
  5135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5136. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5137. EXPECT_EQ("error", res->body);
  5138. }
  5139. }
  5140. // The pre-request handler must run before the request body is read, so a
  5141. // rejected request never forces the server to buffer a (potentially large)
  5142. // body. Here the posted body is larger than the payload limit: if the body
  5143. // were read first the server would answer 413, but because the pre-request
  5144. // handler runs first it answers 403 and the body is never read.
  5145. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5146. Server svr;
  5147. svr.set_payload_max_length(8);
  5148. auto handler_ran = false;
  5149. svr.Post("/reject", [&](const Request &req, Response &res) {
  5150. handler_ran = true;
  5151. res.set_content(req.body, "text/plain");
  5152. });
  5153. svr.Post("/accept", [](const Request &req, Response &res) {
  5154. res.set_content(req.body, "text/plain");
  5155. });
  5156. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5157. if (req.matched_route == "/reject") {
  5158. res.status = StatusCode::Forbidden_403;
  5159. res.set_content("denied", "text/plain");
  5160. return Server::HandlerResponse::Handled;
  5161. }
  5162. return Server::HandlerResponse::Unhandled;
  5163. });
  5164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5165. auto se = detail::scope_exit([&] {
  5166. svr.stop();
  5167. thread.join();
  5168. ASSERT_FALSE(svr.is_running());
  5169. });
  5170. svr.wait_until_ready();
  5171. Client cli(HOST, PORT);
  5172. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5173. // rejects with 403 before the body is read, so 413 is never reached.
  5174. {
  5175. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5177. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5178. EXPECT_EQ("denied", res->body);
  5179. EXPECT_FALSE(handler_ran);
  5180. }
  5181. // An approved route still reads the body and enforces the payload limit.
  5182. {
  5183. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5185. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5186. }
  5187. }
  5188. TEST(UserDataTest, BasicOperations) {
  5189. httplib::UserData ud;
  5190. // Initially empty
  5191. EXPECT_FALSE(ud.has("key"));
  5192. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5193. // set and get
  5194. ud.set("key", 42);
  5195. EXPECT_TRUE(ud.has("key"));
  5196. auto *p = ud.get<int>("key");
  5197. ASSERT_NE(nullptr, p);
  5198. EXPECT_EQ(42, *p);
  5199. // Type mismatch → nullptr
  5200. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5201. // Overwrite with different type
  5202. ud.set("key", std::string("hello"));
  5203. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5204. auto *s = ud.get<std::string>("key");
  5205. ASSERT_NE(nullptr, s);
  5206. EXPECT_EQ("hello", *s);
  5207. // erase
  5208. ud.erase("key");
  5209. EXPECT_FALSE(ud.has("key"));
  5210. // clear
  5211. ud.set("a", 1);
  5212. ud.set("b", 2);
  5213. ud.clear();
  5214. EXPECT_FALSE(ud.has("a"));
  5215. EXPECT_FALSE(ud.has("b"));
  5216. }
  5217. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5218. struct AuthCtx {
  5219. std::string user_id;
  5220. };
  5221. Server svr;
  5222. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5223. res.user_data.set("auth", AuthCtx{"alice"});
  5224. return Server::HandlerResponse::Unhandled;
  5225. });
  5226. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5227. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5228. ASSERT_NE(nullptr, ctx);
  5229. res.set_content("Hello " + ctx->user_id, "text/plain");
  5230. });
  5231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5232. auto se = detail::scope_exit([&] {
  5233. svr.stop();
  5234. thread.join();
  5235. ASSERT_FALSE(svr.is_running());
  5236. });
  5237. svr.wait_until_ready();
  5238. Client cli(HOST, PORT);
  5239. auto res = cli.Get("/me");
  5240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5241. EXPECT_EQ(StatusCode::OK_200, res->status);
  5242. EXPECT_EQ("Hello alice", res->body);
  5243. }
  5244. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5245. struct RoleCtx {
  5246. std::string role;
  5247. };
  5248. Server svr;
  5249. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5250. res.user_data.set("role", RoleCtx{"admin"});
  5251. return Server::HandlerResponse::Unhandled;
  5252. });
  5253. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5254. auto *ctx = res.user_data.get<RoleCtx>("role");
  5255. ASSERT_NE(nullptr, ctx);
  5256. res.set_content(ctx->role, "text/plain");
  5257. });
  5258. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5259. auto se = detail::scope_exit([&] {
  5260. svr.stop();
  5261. thread.join();
  5262. ASSERT_FALSE(svr.is_running());
  5263. });
  5264. svr.wait_until_ready();
  5265. Client cli(HOST, PORT);
  5266. auto res = cli.Get("/role");
  5267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5268. EXPECT_EQ(StatusCode::OK_200, res->status);
  5269. EXPECT_EQ("admin", res->body);
  5270. }
  5271. TEST(InvalidFormatTest, StatusCode) {
  5272. Server svr;
  5273. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5274. res.set_content("Hello World!\n", "text/plain");
  5275. res.status = 9999; // Status should be a three-digit code...
  5276. });
  5277. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5278. auto se = detail::scope_exit([&] {
  5279. svr.stop();
  5280. thread.join();
  5281. ASSERT_FALSE(svr.is_running());
  5282. });
  5283. svr.wait_until_ready();
  5284. {
  5285. Client cli(HOST, PORT);
  5286. auto res = cli.Get("/hi");
  5287. ASSERT_FALSE(res);
  5288. }
  5289. }
  5290. TEST(URLFragmentTest, WithFragment) {
  5291. Server svr;
  5292. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5293. EXPECT_TRUE(req.target == "/hi");
  5294. });
  5295. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5296. auto se = detail::scope_exit([&] {
  5297. svr.stop();
  5298. thread.join();
  5299. ASSERT_FALSE(svr.is_running());
  5300. });
  5301. svr.wait_until_ready();
  5302. {
  5303. Client cli(HOST, PORT);
  5304. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5305. EXPECT_TRUE(res);
  5306. EXPECT_EQ(StatusCode::OK_200, res->status);
  5307. res = cli.Get("/hi%23key1=val1=key2=val2");
  5308. EXPECT_TRUE(res);
  5309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5310. }
  5311. }
  5312. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5313. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5314. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5315. Server svr;
  5316. std::vector<std::string> targets;
  5317. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5318. targets.push_back(req.target);
  5319. });
  5320. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5321. auto se = detail::scope_exit([&] {
  5322. svr.stop();
  5323. thread.join();
  5324. ASSERT_FALSE(svr.is_running());
  5325. });
  5326. svr.wait_until_ready();
  5327. Client cli(HOST, PORT);
  5328. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5329. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5330. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5331. // A '?' after the '#' belongs to the fragment, not to the query.
  5332. Request req;
  5333. req.method = "GET";
  5334. req.path = "/hi#f?x=1";
  5335. req.params.emplace("a", "1");
  5336. Response res;
  5337. auto error = Error::Success;
  5338. EXPECT_TRUE(cli.send(req, res, error));
  5339. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5340. "/hi?a=1"}),
  5341. targets);
  5342. }
  5343. TEST(HeaderWriter, SetHeaderWriter) {
  5344. Server svr;
  5345. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5346. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5347. return detail::write_headers(strm, hdrs);
  5348. });
  5349. svr.Get("/hi", [](const Request &req, Response &res) {
  5350. auto it = req.headers.find("CustomClientHeader");
  5351. EXPECT_TRUE(it != req.headers.end());
  5352. EXPECT_EQ(it->second, "CustomClientValue");
  5353. res.set_content("Hello World!\n", "text/plain");
  5354. });
  5355. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5356. auto se = detail::scope_exit([&] {
  5357. svr.stop();
  5358. thread.join();
  5359. ASSERT_FALSE(svr.is_running());
  5360. });
  5361. svr.wait_until_ready();
  5362. {
  5363. Client cli(HOST, PORT);
  5364. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5365. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5366. return detail::write_headers(strm, hdrs);
  5367. });
  5368. auto res = cli.Get("/hi");
  5369. EXPECT_TRUE(res);
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. auto it = res->headers.find("CustomServerHeader");
  5372. EXPECT_TRUE(it != res->headers.end());
  5373. EXPECT_EQ(it->second, "CustomServerValue");
  5374. }
  5375. }
  5376. class ServerTest : public ::testing::Test {
  5377. protected:
  5378. ServerTest()
  5379. : cli_(HOST, PORT)
  5380. #ifdef CPPHTTPLIB_SSL_ENABLED
  5381. ,
  5382. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5383. #endif
  5384. {
  5385. #ifdef CPPHTTPLIB_SSL_ENABLED
  5386. cli_.enable_server_certificate_verification(false);
  5387. #endif
  5388. // Allow LARGE_DATA (100MB) responses
  5389. cli_.set_payload_max_length(200 * 1024 * 1024);
  5390. }
  5391. virtual void SetUp() {
  5392. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5393. svr_.set_payload_max_length(200 * 1024 * 1024);
  5394. svr_.set_mount_point("/", "./www");
  5395. svr_.set_mount_point("/mount", "./www2");
  5396. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5397. svr_.Get("/hi",
  5398. [&](const Request & /*req*/, Response &res) {
  5399. res.set_content("Hello World!", "text/plain");
  5400. })
  5401. .Get("/file_content",
  5402. [&](const Request & /*req*/, Response &res) {
  5403. res.set_file_content("./www/dir/test.html");
  5404. })
  5405. .Get("/file_content_with_content_type",
  5406. [&](const Request & /*req*/, Response &res) {
  5407. res.set_file_content("./www/file", "text/plain");
  5408. })
  5409. .Get("/invalid_file_content",
  5410. [&](const Request & /*req*/, Response &res) {
  5411. res.set_file_content("./www/dir/invalid_file_path");
  5412. })
  5413. .Get("/http_response_splitting",
  5414. [&](const Request & /*req*/, Response &res) {
  5415. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5416. EXPECT_EQ(0U, res.headers.size());
  5417. EXPECT_FALSE(res.has_header("a"));
  5418. res.set_header("a", "1\nSet-Cookie: a=1");
  5419. EXPECT_EQ(0U, res.headers.size());
  5420. EXPECT_FALSE(res.has_header("a"));
  5421. res.set_header("a", "1\rSet-Cookie: a=1");
  5422. EXPECT_EQ(0U, res.headers.size());
  5423. EXPECT_FALSE(res.has_header("a"));
  5424. res.set_header("a\r\nb", "0");
  5425. EXPECT_EQ(0U, res.headers.size());
  5426. EXPECT_FALSE(res.has_header("a"));
  5427. res.set_header("a\rb", "0");
  5428. EXPECT_EQ(0U, res.headers.size());
  5429. EXPECT_FALSE(res.has_header("a"));
  5430. res.set_header("a\nb", "0");
  5431. EXPECT_EQ(0U, res.headers.size());
  5432. EXPECT_FALSE(res.has_header("a"));
  5433. res.set_redirect("1\r\nSet-Cookie: a=1");
  5434. EXPECT_EQ(0U, res.headers.size());
  5435. EXPECT_FALSE(res.has_header("Location"));
  5436. })
  5437. .Get("/slow",
  5438. [&](const Request & /*req*/, Response &res) {
  5439. std::this_thread::sleep_for(std::chrono::seconds(4));
  5440. res.set_content("slow", "text/plain");
  5441. })
  5442. #if 0
  5443. .Post("/slowpost",
  5444. [&](const Request & /*req*/, Response &res) {
  5445. std::this_thread::sleep_for(std::chrono::seconds(2));
  5446. res.set_content("slow", "text/plain");
  5447. })
  5448. #endif
  5449. .Get("/remote_addr",
  5450. [&](const Request &req, Response &res) {
  5451. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5452. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5453. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5454. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5455. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5456. #endif
  5457. res.set_content(req.remote_addr, "text/plain");
  5458. })
  5459. .Get("/local_addr",
  5460. [&](const Request &req, Response &res) {
  5461. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5462. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5463. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5464. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5465. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5466. #endif
  5467. auto local_addr = req.local_addr;
  5468. auto local_port = std::to_string(req.local_port);
  5469. res.set_content(local_addr.append(":").append(local_port),
  5470. "text/plain");
  5471. })
  5472. .Get("/endwith%",
  5473. [&](const Request & /*req*/, Response &res) {
  5474. res.set_content("Hello World!", "text/plain");
  5475. })
  5476. .Get("/a\\+\\+b",
  5477. [&](const Request &req, Response &res) {
  5478. ASSERT_TRUE(req.has_param("a +b"));
  5479. auto val = req.get_param_value("a +b");
  5480. res.set_content(val, "text/plain");
  5481. })
  5482. .Get("/", [&](const Request & /*req*/,
  5483. Response &res) { res.set_redirect("/hi"); })
  5484. .Post("/1",
  5485. [](const Request & /*req*/, Response &res) {
  5486. res.set_redirect("/2", StatusCode::SeeOther_303);
  5487. })
  5488. .Get("/2",
  5489. [](const Request & /*req*/, Response &res) {
  5490. res.set_content("redirected.", "text/plain");
  5491. res.status = StatusCode::OK_200;
  5492. })
  5493. .Post("/person",
  5494. [&](const Request &req, Response &res) {
  5495. if (req.has_param("name") && req.has_param("note")) {
  5496. persons_[req.get_param_value("name")] =
  5497. req.get_param_value("note");
  5498. } else {
  5499. res.status = StatusCode::BadRequest_400;
  5500. }
  5501. })
  5502. .Put("/person",
  5503. [&](const Request &req, Response &res) {
  5504. if (req.has_param("name") && req.has_param("note")) {
  5505. persons_[req.get_param_value("name")] =
  5506. req.get_param_value("note");
  5507. } else {
  5508. res.status = StatusCode::BadRequest_400;
  5509. }
  5510. })
  5511. .Get("/person/(.*)",
  5512. [&](const Request &req, Response &res) {
  5513. string name = req.matches[1];
  5514. if (persons_.find(name) != persons_.end()) {
  5515. auto note = persons_[name];
  5516. res.set_content(note, "text/plain");
  5517. } else {
  5518. res.status = StatusCode::NotFound_404;
  5519. }
  5520. })
  5521. .Delete("/person",
  5522. [&](const Request &req, Response &res) {
  5523. if (req.has_param("name")) {
  5524. string name = req.get_param_value("name");
  5525. if (persons_.find(name) != persons_.end()) {
  5526. persons_.erase(name);
  5527. res.set_content("DELETED", "text/plain");
  5528. } else {
  5529. res.status = StatusCode::NotFound_404;
  5530. }
  5531. } else {
  5532. res.status = StatusCode::BadRequest_400;
  5533. }
  5534. })
  5535. .Post("/x-www-form-urlencoded-json",
  5536. [&](const Request &req, Response &res) {
  5537. auto json = req.get_param_value("json");
  5538. ASSERT_EQ(JSON_DATA, json);
  5539. res.set_content(json, "appliation/json");
  5540. res.status = StatusCode::OK_200;
  5541. })
  5542. .Get("/streamed-chunked",
  5543. [&](const Request & /*req*/, Response &res) {
  5544. res.set_chunked_content_provider(
  5545. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5546. sink.os << "123";
  5547. sink.os << "456";
  5548. sink.os << "789";
  5549. sink.done();
  5550. return true;
  5551. });
  5552. })
  5553. .Get("/streamed-chunked-with-prohibited-trailer",
  5554. [&](const Request & /*req*/, Response &res) {
  5555. auto i = new int(0);
  5556. // Declare both a prohibited trailer (Content-Length) and an
  5557. // allowed one
  5558. res.set_header("Trailer", "Content-Length, X-Allowed");
  5559. res.set_chunked_content_provider(
  5560. "text/plain",
  5561. [i](size_t /*offset*/, DataSink &sink) {
  5562. switch (*i) {
  5563. case 0: sink.os << "123"; break;
  5564. case 1: sink.os << "456"; break;
  5565. case 2: sink.os << "789"; break;
  5566. case 3: {
  5567. sink.done_with_trailer(
  5568. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5569. } break;
  5570. }
  5571. (*i)++;
  5572. return true;
  5573. },
  5574. [i](bool success) {
  5575. EXPECT_TRUE(success);
  5576. delete i;
  5577. });
  5578. })
  5579. .Get("/streamed-chunked2",
  5580. [&](const Request & /*req*/, Response &res) {
  5581. auto i = new int(0);
  5582. res.set_chunked_content_provider(
  5583. "text/plain",
  5584. [i](size_t /*offset*/, DataSink &sink) {
  5585. switch (*i) {
  5586. case 0: sink.os << "123"; break;
  5587. case 1: sink.os << "456"; break;
  5588. case 2: sink.os << "789"; break;
  5589. case 3: sink.done(); break;
  5590. }
  5591. (*i)++;
  5592. return true;
  5593. },
  5594. [i](bool success) {
  5595. EXPECT_TRUE(success);
  5596. delete i;
  5597. });
  5598. })
  5599. .Get("/streamed-chunked-with-trailer",
  5600. [&](const Request & /*req*/, Response &res) {
  5601. auto i = new int(0);
  5602. res.set_header("Trailer", "Dummy1, Dummy2");
  5603. res.set_chunked_content_provider(
  5604. "text/plain",
  5605. [i](size_t /*offset*/, DataSink &sink) {
  5606. switch (*i) {
  5607. case 0: sink.os << "123"; break;
  5608. case 1: sink.os << "456"; break;
  5609. case 2: sink.os << "789"; break;
  5610. case 3: {
  5611. sink.done_with_trailer(
  5612. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5613. } break;
  5614. }
  5615. (*i)++;
  5616. return true;
  5617. },
  5618. [i](bool success) {
  5619. EXPECT_TRUE(success);
  5620. delete i;
  5621. });
  5622. })
  5623. .Get("/streamed",
  5624. [&](const Request & /*req*/, Response &res) {
  5625. res.set_content_provider(
  5626. 6, "text/plain",
  5627. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5628. sink.os << (offset < 3 ? "a" : "b");
  5629. return true;
  5630. });
  5631. })
  5632. .Get("/streamed-without-length",
  5633. [&](const Request & /*req*/, Response &res) {
  5634. auto data = new std::string("abcdefg");
  5635. res.set_content_provider(
  5636. "text/plain",
  5637. [data](size_t offset, DataSink &sink) {
  5638. if (offset < data->size()) {
  5639. sink.os << data->substr(offset);
  5640. }
  5641. sink.done();
  5642. return true;
  5643. },
  5644. [data](bool success) {
  5645. EXPECT_TRUE(success);
  5646. delete data;
  5647. });
  5648. })
  5649. .Get("/streamed-with-range",
  5650. [&](const Request &req, Response &res) {
  5651. auto data = new std::string("abcdefg");
  5652. // An explicit status keeps the server from picking the 206 it
  5653. // would otherwise choose for a ranged request, so the response
  5654. // is not a partial representation.
  5655. auto status = req.get_param_value("status");
  5656. if (status == "200") {
  5657. res.status = StatusCode::OK_200;
  5658. } else if (status == "403") {
  5659. res.status = StatusCode::Forbidden_403;
  5660. }
  5661. res.set_content_provider(
  5662. data->size(), "text/plain",
  5663. [data](size_t offset, size_t length, DataSink &sink) {
  5664. size_t DATA_CHUNK_SIZE = 4;
  5665. const auto &d = *data;
  5666. auto out_len =
  5667. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5668. auto ret =
  5669. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5670. EXPECT_TRUE(ret);
  5671. return true;
  5672. },
  5673. [data, &req](bool success) {
  5674. EXPECT_EQ(success, !req.has_param("error"));
  5675. delete data;
  5676. });
  5677. })
  5678. .Get("/streamed-cancel",
  5679. [&](const Request & /*req*/, Response &res) {
  5680. res.set_content_provider(
  5681. size_t(-1), "text/plain",
  5682. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5683. sink.os << "data_chunk";
  5684. return true;
  5685. });
  5686. })
  5687. .Get("/regex-with-delimiter",
  5688. [&](const Request &req, Response & /*res*/) {
  5689. ASSERT_TRUE(req.has_param("key"));
  5690. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5691. })
  5692. .Get("/with-range",
  5693. [&](const Request & /*req*/, Response &res) {
  5694. res.set_content("abcdefg", "text/plain");
  5695. })
  5696. .Get("/test-start-time",
  5697. [&](const Request &req, Response & /*res*/) {
  5698. EXPECT_NE(req.start_time_,
  5699. std::chrono::steady_clock::time_point::min());
  5700. })
  5701. .Get("/with-range-customized-response",
  5702. [&](const Request & /*req*/, Response &res) {
  5703. res.status = StatusCode::BadRequest_400;
  5704. res.set_content(JSON_DATA, "application/json");
  5705. })
  5706. .Post("/chunked",
  5707. [&](const Request &req, Response & /*res*/) {
  5708. EXPECT_EQ(req.body, "dechunked post body");
  5709. })
  5710. .Post("/large-chunked",
  5711. [&](const Request &req, Response & /*res*/) {
  5712. std::string expected(6 * 30 * 1024u, 'a');
  5713. EXPECT_EQ(req.body, expected);
  5714. })
  5715. .Post("/multipart",
  5716. [&](const Request &req, Response & /*res*/) {
  5717. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5718. req.form.get_field_count("text2") +
  5719. req.form.get_field_count("file3") +
  5720. req.form.get_field_count("file4"));
  5721. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5722. req.form.get_file_count("file2"));
  5723. ASSERT_TRUE(!req.form.has_file("???"));
  5724. ASSERT_TRUE(!req.form.has_field("???"));
  5725. ASSERT_TRUE(req.body.empty());
  5726. {
  5727. const auto &text = req.form.get_field("text1");
  5728. EXPECT_EQ("text default", text);
  5729. }
  5730. {
  5731. const auto &text = req.form.get_field("text2");
  5732. EXPECT_EQ("aωb", text);
  5733. }
  5734. {
  5735. const auto &file = req.form.get_file("file1");
  5736. EXPECT_EQ("hello.txt", file.filename);
  5737. EXPECT_EQ("text/plain", file.content_type);
  5738. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5739. }
  5740. {
  5741. const auto &file = req.form.get_file("file2");
  5742. EXPECT_EQ("world.json", file.filename);
  5743. EXPECT_EQ("application/json", file.content_type);
  5744. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5745. }
  5746. {
  5747. const auto &text = req.form.get_field("file3");
  5748. EXPECT_EQ(0u, text.size());
  5749. }
  5750. {
  5751. const auto &text = req.form.get_field("file4");
  5752. EXPECT_EQ(0u, text.size());
  5753. }
  5754. })
  5755. .Post("/multipart/multi_file_values",
  5756. [&](const Request &req, Response & /*res*/) {
  5757. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5758. req.form.get_field_count("multi_text1"));
  5759. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5760. ASSERT_TRUE(!req.form.has_file("???"));
  5761. ASSERT_TRUE(!req.form.has_field("???"));
  5762. ASSERT_TRUE(req.body.empty());
  5763. {
  5764. const auto &text = req.form.get_field("text");
  5765. EXPECT_EQ("default text", text);
  5766. }
  5767. {
  5768. const auto &text1_values = req.form.get_fields("multi_text1");
  5769. EXPECT_EQ(2u, text1_values.size());
  5770. EXPECT_EQ("aaaaa", text1_values[0]);
  5771. EXPECT_EQ("bbbbb", text1_values[1]);
  5772. }
  5773. {
  5774. const auto &file1_values = req.form.get_files("multi_file1");
  5775. EXPECT_EQ(2u, file1_values.size());
  5776. auto file1 = file1_values[0];
  5777. EXPECT_EQ(file1.filename, "hello.txt");
  5778. EXPECT_EQ(file1.content_type, "text/plain");
  5779. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5780. auto file2 = file1_values[1];
  5781. EXPECT_EQ(file2.filename, "world.json");
  5782. EXPECT_EQ(file2.content_type, "application/json");
  5783. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5784. }
  5785. })
  5786. .Post("/empty",
  5787. [&](const Request &req, Response &res) {
  5788. EXPECT_EQ(req.body, "");
  5789. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5790. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5791. res.set_content("empty", "text/plain");
  5792. })
  5793. .Post("/empty-no-content-type",
  5794. [&](const Request &req, Response &res) {
  5795. EXPECT_EQ(req.body, "");
  5796. EXPECT_FALSE(req.has_header("Content-Type"));
  5797. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5798. res.set_content("empty-no-content-type", "text/plain");
  5799. })
  5800. .Post("/path-only",
  5801. [&](const Request &req, Response &res) {
  5802. EXPECT_EQ(req.body, "");
  5803. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5804. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5805. res.set_content("path-only", "text/plain");
  5806. })
  5807. .Post("/path-headers-only",
  5808. [&](const Request &req, Response &res) {
  5809. EXPECT_EQ(req.body, "");
  5810. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5811. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5812. EXPECT_EQ("world", req.get_header_value("hello"));
  5813. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5814. res.set_content("path-headers-only", "text/plain");
  5815. })
  5816. .Post("/post-large",
  5817. [&](const Request &req, Response &res) {
  5818. EXPECT_EQ(req.body, LARGE_DATA);
  5819. res.set_content(req.body, "text/plain");
  5820. })
  5821. .Post("/post-loopback",
  5822. [&](const Request &, Response &res,
  5823. ContentReader const &content_reader) {
  5824. std::string body;
  5825. content_reader([&](const char *data, size_t data_length) {
  5826. body.append(data, data_length);
  5827. return true;
  5828. });
  5829. res.set_content(body, "text/plain");
  5830. })
  5831. .Put("/put-loopback",
  5832. [&](const Request &, Response &res,
  5833. ContentReader const &content_reader) {
  5834. std::string body;
  5835. content_reader([&](const char *data, size_t data_length) {
  5836. body.append(data, data_length);
  5837. return true;
  5838. });
  5839. res.set_content(body, "text/plain");
  5840. })
  5841. .Patch("/patch-loopback",
  5842. [&](const Request &, Response &res,
  5843. ContentReader const &content_reader) {
  5844. std::string body;
  5845. content_reader([&](const char *data, size_t data_length) {
  5846. body.append(data, data_length);
  5847. return true;
  5848. });
  5849. res.set_content(body, "text/plain");
  5850. })
  5851. .Put("/empty-no-content-type",
  5852. [&](const Request &req, Response &res) {
  5853. EXPECT_EQ(req.body, "");
  5854. EXPECT_FALSE(req.has_header("Content-Type"));
  5855. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5856. res.set_content("empty-no-content-type", "text/plain");
  5857. })
  5858. .Put("/put",
  5859. [&](const Request &req, Response &res) {
  5860. EXPECT_EQ(req.body, "PUT");
  5861. res.set_content(req.body, "text/plain");
  5862. })
  5863. .Put("/put-large",
  5864. [&](const Request &req, Response &res) {
  5865. EXPECT_EQ(req.body, LARGE_DATA);
  5866. res.set_content(req.body, "text/plain");
  5867. })
  5868. .Patch("/patch",
  5869. [&](const Request &req, Response &res) {
  5870. EXPECT_EQ(req.body, "PATCH");
  5871. res.set_content(req.body, "text/plain");
  5872. })
  5873. .Delete("/delete",
  5874. [&](const Request & /*req*/, Response &res) {
  5875. res.set_content("DELETE", "text/plain");
  5876. })
  5877. .Delete("/delete-body",
  5878. [&](const Request &req, Response &res) {
  5879. EXPECT_EQ(req.body, "content");
  5880. res.set_content(req.body, "text/plain");
  5881. })
  5882. .Options(R"(\*)",
  5883. [&](const Request & /*req*/, Response &res) {
  5884. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5885. })
  5886. .CustomRoute("PROPFIND", "/dav/:id",
  5887. [&](const Request &req, Response &res) {
  5888. res.set_header("x-body-size",
  5889. std::to_string(req.body.size()));
  5890. res.set_header("x-matched-route", req.matched_route);
  5891. res.set_header("x-dav-id", req.path_params.at("id"));
  5892. res.status = StatusCode::MultiStatus_207;
  5893. res.set_content(req.body, "application/xml");
  5894. })
  5895. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5896. [&](const Request &req, Response &res) {
  5897. res.set_header("x-dav-match", req.matches[1]);
  5898. res.status = StatusCode::MultiStatus_207;
  5899. })
  5900. .CustomRoute("MKCOL", "/dav-mkcol",
  5901. [&](const Request &req, Response &res) {
  5902. EXPECT_TRUE(req.body.empty());
  5903. res.status = StatusCode::Created_201;
  5904. })
  5905. .CustomRoute(
  5906. "REPORT", "/dav-report",
  5907. [&](const Request & /*req*/, Response &res,
  5908. const ContentReader &content_reader) {
  5909. std::string body;
  5910. content_reader([&](const char *data, size_t data_length) {
  5911. body.append(data, data_length);
  5912. return true;
  5913. });
  5914. res.set_header("x-body-size", std::to_string(body.size()));
  5915. res.status = StatusCode::MultiStatus_207;
  5916. res.set_content(body, "application/xml");
  5917. })
  5918. .Get("/request-target",
  5919. [&](const Request &req, Response & /*res*/) {
  5920. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5921. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5922. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5923. })
  5924. .Get("/long-query-value",
  5925. [&](const Request &req, Response & /*res*/) {
  5926. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5927. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5928. })
  5929. .Get("/too-long-query-value",
  5930. [&](const Request &req, Response & /*res*/) {
  5931. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5932. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5933. })
  5934. .Get("/array-param",
  5935. [&](const Request &req, Response & /*res*/) {
  5936. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5937. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5938. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5939. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5940. })
  5941. .Get("/array-param-values",
  5942. [&](const Request &req, Response & /*res*/) {
  5943. auto values = req.get_param_values("array");
  5944. EXPECT_EQ(3u, values.size());
  5945. EXPECT_EQ("value1", values[0]);
  5946. EXPECT_EQ("value2", values[1]);
  5947. EXPECT_EQ("value3", values[2]);
  5948. auto empty = req.get_param_values("nonexistent");
  5949. EXPECT_TRUE(empty.empty());
  5950. })
  5951. .Post("/validate-no-multiple-headers",
  5952. [&](const Request &req, Response & /*res*/) {
  5953. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5954. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5955. })
  5956. .Post("/content_receiver",
  5957. [&](const Request &req, Response &res,
  5958. const ContentReader &content_reader) {
  5959. if (req.is_multipart_form_data()) {
  5960. std::vector<FormData> items;
  5961. content_reader(
  5962. [&](const FormData &file) {
  5963. items.push_back(file);
  5964. return true;
  5965. },
  5966. [&](const char *data, size_t data_length) {
  5967. items.back().content.append(data, data_length);
  5968. return true;
  5969. });
  5970. EXPECT_EQ(5u, items.size());
  5971. {
  5972. const auto &file = get_file_value(items, "text1");
  5973. EXPECT_TRUE(file.filename.empty());
  5974. EXPECT_EQ("text default", file.content);
  5975. }
  5976. {
  5977. const auto &file = get_file_value(items, "text2");
  5978. EXPECT_TRUE(file.filename.empty());
  5979. EXPECT_EQ("aωb", file.content);
  5980. }
  5981. {
  5982. const auto &file = get_file_value(items, "file1");
  5983. EXPECT_EQ("hello.txt", file.filename);
  5984. EXPECT_EQ("text/plain", file.content_type);
  5985. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5986. }
  5987. {
  5988. const auto &file = get_file_value(items, "file2");
  5989. EXPECT_EQ("world.json", file.filename);
  5990. EXPECT_EQ("application/json", file.content_type);
  5991. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5992. }
  5993. {
  5994. const auto &file = get_file_value(items, "file3");
  5995. EXPECT_TRUE(file.filename.empty());
  5996. EXPECT_EQ("application/octet-stream", file.content_type);
  5997. EXPECT_EQ(0u, file.content.size());
  5998. }
  5999. } else {
  6000. std::string body;
  6001. content_reader([&](const char *data, size_t data_length) {
  6002. EXPECT_EQ(7U, data_length);
  6003. body.append(data, data_length);
  6004. return true;
  6005. });
  6006. EXPECT_EQ(body, "content");
  6007. res.set_content(body, "text/plain");
  6008. }
  6009. })
  6010. .Put("/content_receiver",
  6011. [&](const Request & /*req*/, Response &res,
  6012. const ContentReader &content_reader) {
  6013. std::string body;
  6014. content_reader([&](const char *data, size_t data_length) {
  6015. body.append(data, data_length);
  6016. return true;
  6017. });
  6018. EXPECT_EQ(body, "content");
  6019. res.set_content(body, "text/plain");
  6020. })
  6021. .Patch("/content_receiver",
  6022. [&](const Request & /*req*/, Response &res,
  6023. const ContentReader &content_reader) {
  6024. std::string body;
  6025. content_reader([&](const char *data, size_t data_length) {
  6026. body.append(data, data_length);
  6027. return true;
  6028. });
  6029. EXPECT_EQ(body, "content");
  6030. res.set_content(body, "text/plain");
  6031. })
  6032. .Post("/query-string-and-body",
  6033. [&](const Request &req, Response & /*res*/) {
  6034. ASSERT_TRUE(req.has_param("key"));
  6035. EXPECT_EQ(req.get_param_value("key"), "value");
  6036. EXPECT_EQ(req.body, "content");
  6037. })
  6038. .Get("/last-request",
  6039. [&](const Request &req, Response & /*res*/) {
  6040. EXPECT_EQ("close", req.get_header_value("Connection"));
  6041. })
  6042. .Get(R"(/redirect/(\d+))",
  6043. [&](const Request &req, Response &res) {
  6044. auto num = std::stoi(req.matches[1]) + 1;
  6045. std::string url = "/redirect/" + std::to_string(num);
  6046. res.set_redirect(url);
  6047. })
  6048. .Post("/binary",
  6049. [&](const Request &req, Response &res) {
  6050. EXPECT_EQ(4U, req.body.size());
  6051. EXPECT_EQ("application/octet-stream",
  6052. req.get_header_value("Content-Type"));
  6053. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6054. res.set_content(req.body, "application/octet-stream");
  6055. })
  6056. .Put("/binary",
  6057. [&](const Request &req, Response &res) {
  6058. EXPECT_EQ(4U, req.body.size());
  6059. EXPECT_EQ("application/octet-stream",
  6060. req.get_header_value("Content-Type"));
  6061. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6062. res.set_content(req.body, "application/octet-stream");
  6063. })
  6064. .Patch("/binary",
  6065. [&](const Request &req, Response &res) {
  6066. EXPECT_EQ(4U, req.body.size());
  6067. EXPECT_EQ("application/octet-stream",
  6068. req.get_header_value("Content-Type"));
  6069. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6070. res.set_content(req.body, "application/octet-stream");
  6071. })
  6072. .Delete("/binary",
  6073. [&](const Request &req, Response &res) {
  6074. EXPECT_EQ(4U, req.body.size());
  6075. EXPECT_EQ("application/octet-stream",
  6076. req.get_header_value("Content-Type"));
  6077. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6078. res.set_content(req.body, "application/octet-stream");
  6079. })
  6080. .Get("/issue1772",
  6081. [&](const Request & /*req*/, Response &res) {
  6082. res.status = 401;
  6083. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6084. })
  6085. .Delete("/issue609",
  6086. [](const httplib::Request &, httplib::Response &res,
  6087. const httplib::ContentReader &) {
  6088. res.set_content("ok", "text/plain");
  6089. })
  6090. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6091. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6092. .Get("/compress",
  6093. [&](const Request & /*req*/, Response &res) {
  6094. res.set_content(
  6095. "12345678901234567890123456789012345678901234567890123456789"
  6096. "01234567890123456789012345678901234567890",
  6097. "text/plain");
  6098. })
  6099. .Get("/compress-with-charset",
  6100. [&](const Request & /*req*/, Response &res) {
  6101. res.set_content(
  6102. "12345678901234567890123456789012345678901234567890123456789"
  6103. "01234567890123456789012345678901234567890",
  6104. "application/json; charset=utf-8");
  6105. })
  6106. .Get("/nocompress",
  6107. [&](const Request & /*req*/, Response &res) {
  6108. res.set_content(
  6109. "12345678901234567890123456789012345678901234567890123456789"
  6110. "01234567890123456789012345678901234567890",
  6111. "application/octet-stream");
  6112. })
  6113. .Post("/compress-multipart",
  6114. [&](const Request &req, Response & /*res*/) {
  6115. EXPECT_EQ(2u, req.form.fields.size());
  6116. ASSERT_TRUE(!req.form.has_field("???"));
  6117. {
  6118. const auto &text = req.form.get_field("key1");
  6119. EXPECT_EQ("test", text);
  6120. }
  6121. {
  6122. const auto &text = req.form.get_field("key2");
  6123. EXPECT_EQ("--abcdefg123", text);
  6124. }
  6125. })
  6126. #endif
  6127. ;
  6128. persons_["john"] = "programmer";
  6129. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6130. svr_.wait_until_ready();
  6131. }
  6132. virtual void TearDown() {
  6133. svr_.stop();
  6134. if (!request_threads_.empty()) {
  6135. std::this_thread::sleep_for(std::chrono::seconds(1));
  6136. for (auto &t : request_threads_) {
  6137. t.join();
  6138. }
  6139. }
  6140. t_.join();
  6141. }
  6142. map<string, string> persons_;
  6143. #ifdef CPPHTTPLIB_SSL_ENABLED
  6144. SSLClient cli_;
  6145. SSLServer svr_;
  6146. #else
  6147. Client cli_;
  6148. Server svr_;
  6149. #endif
  6150. thread t_;
  6151. std::vector<thread> request_threads_;
  6152. };
  6153. TEST_F(ServerTest, GetMethod200) {
  6154. auto res = cli_.Get("/hi");
  6155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6156. EXPECT_EQ("HTTP/1.1", res->version);
  6157. EXPECT_EQ(StatusCode::OK_200, res->status);
  6158. EXPECT_EQ("OK", res->reason);
  6159. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6160. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6161. EXPECT_EQ("Hello World!", res->body);
  6162. }
  6163. TEST_F(ServerTest, GetEmptyFile) {
  6164. auto res = cli_.Get("/empty_file");
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6168. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6169. EXPECT_EQ("", res->body);
  6170. }
  6171. TEST_F(ServerTest, GetFileContent) {
  6172. auto res = cli_.Get("/file_content");
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::OK_200, res->status);
  6175. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6176. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6177. EXPECT_EQ("test.html", res->body);
  6178. }
  6179. TEST_F(ServerTest, GetFileContentWithRange) {
  6180. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6182. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6183. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6184. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6185. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6186. EXPECT_EQ("est", res->body);
  6187. }
  6188. TEST_F(ServerTest, GetFileContentWithContentType) {
  6189. auto res = cli_.Get("/file_content_with_content_type");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. EXPECT_EQ(StatusCode::OK_200, res->status);
  6192. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6193. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6194. EXPECT_EQ("file\n", res->body);
  6195. }
  6196. TEST_F(ServerTest, GetInvalidFileContent) {
  6197. auto res = cli_.Get("/invalid_file_content");
  6198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6199. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6200. }
  6201. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6202. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6204. EXPECT_EQ("HTTP/1.1", res->version);
  6205. EXPECT_EQ(StatusCode::OK_200, res->status);
  6206. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6207. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6208. EXPECT_EQ("Hello World!", res->body);
  6209. }
  6210. TEST_F(ServerTest, GetMethod302) {
  6211. auto res = cli_.Get("/");
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. EXPECT_EQ(StatusCode::Found_302, res->status);
  6214. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6215. }
  6216. TEST_F(ServerTest, GetMethod302Redirect) {
  6217. cli_.set_follow_location(true);
  6218. auto res = cli_.Get("/");
  6219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6220. EXPECT_EQ(StatusCode::OK_200, res->status);
  6221. EXPECT_EQ("Hello World!", res->body);
  6222. EXPECT_EQ("/hi", res->location);
  6223. }
  6224. TEST_F(ServerTest, GetMethod404) {
  6225. auto res = cli_.Get("/invalid");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6228. }
  6229. TEST_F(ServerTest, HeadMethod200) {
  6230. auto res = cli_.Head("/hi");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::OK_200, res->status);
  6233. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6234. EXPECT_TRUE(res->body.empty());
  6235. }
  6236. TEST_F(ServerTest, HeadMethod200Static) {
  6237. auto res = cli_.Head("/mount/dir/index.html");
  6238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6239. EXPECT_EQ(StatusCode::OK_200, res->status);
  6240. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6241. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6242. EXPECT_TRUE(res->body.empty());
  6243. }
  6244. TEST_F(ServerTest, HeadMethod404) {
  6245. auto res = cli_.Head("/invalid");
  6246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6247. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6248. EXPECT_TRUE(res->body.empty());
  6249. }
  6250. TEST_F(ServerTest, GetMethodPersonJohn) {
  6251. auto res = cli_.Get("/person/john");
  6252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6253. EXPECT_EQ(StatusCode::OK_200, res->status);
  6254. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6255. EXPECT_EQ("programmer", res->body);
  6256. }
  6257. TEST_F(ServerTest, PostMethod1) {
  6258. auto res = cli_.Get("/person/john1");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6261. res = cli_.Post("/person", "name=john1&note=coder",
  6262. "application/x-www-form-urlencoded");
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. ASSERT_EQ(StatusCode::OK_200, res->status);
  6265. res = cli_.Get("/person/john1");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. ASSERT_EQ(StatusCode::OK_200, res->status);
  6268. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6269. ASSERT_EQ("coder", res->body);
  6270. }
  6271. TEST_F(ServerTest, PostMethod2) {
  6272. auto res = cli_.Get("/person/john2");
  6273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6274. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6275. Params params;
  6276. params.emplace("name", "john2");
  6277. params.emplace("note", "coder");
  6278. res = cli_.Post("/person", params);
  6279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6280. ASSERT_EQ(StatusCode::OK_200, res->status);
  6281. res = cli_.Get("/person/john2");
  6282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6283. ASSERT_EQ(StatusCode::OK_200, res->status);
  6284. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6285. ASSERT_EQ("coder", res->body);
  6286. }
  6287. TEST_F(ServerTest, PutMethod3) {
  6288. auto res = cli_.Get("/person/john3");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6291. Params params;
  6292. params.emplace("name", "john3");
  6293. params.emplace("note", "coder");
  6294. res = cli_.Put("/person", params);
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. ASSERT_EQ(StatusCode::OK_200, res->status);
  6297. res = cli_.Get("/person/john3");
  6298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6299. ASSERT_EQ(StatusCode::OK_200, res->status);
  6300. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6301. ASSERT_EQ("coder", res->body);
  6302. }
  6303. TEST_F(ServerTest, DeleteMethod1) {
  6304. auto res = cli_.Get("/person/john4");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6307. Params params;
  6308. params.emplace("name", "john4");
  6309. params.emplace("note", "coder");
  6310. res = cli_.Post("/person", params);
  6311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6312. ASSERT_EQ(StatusCode::OK_200, res->status);
  6313. res = cli_.Get("/person/john4");
  6314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6315. ASSERT_EQ(StatusCode::OK_200, res->status);
  6316. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6317. ASSERT_EQ("coder", res->body);
  6318. Params delete_params;
  6319. delete_params.emplace("name", "john4");
  6320. res = cli_.Delete("/person", delete_params);
  6321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6322. ASSERT_EQ(StatusCode::OK_200, res->status);
  6323. ASSERT_EQ("DELETED", res->body);
  6324. res = cli_.Get("/person/john4");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6327. }
  6328. TEST_F(ServerTest, DeleteMethod2) {
  6329. auto res = cli_.Get("/person/john5");
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6332. Params params;
  6333. params.emplace("name", "john5");
  6334. params.emplace("note", "developer");
  6335. res = cli_.Post("/person", params);
  6336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6337. ASSERT_EQ(StatusCode::OK_200, res->status);
  6338. res = cli_.Get("/person/john5");
  6339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6340. ASSERT_EQ(StatusCode::OK_200, res->status);
  6341. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6342. ASSERT_EQ("developer", res->body);
  6343. Params delete_params;
  6344. delete_params.emplace("name", "john5");
  6345. Headers headers;
  6346. headers.emplace("Custom-Header", "test-value");
  6347. res = cli_.Delete("/person", headers, delete_params);
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. ASSERT_EQ(StatusCode::OK_200, res->status);
  6350. ASSERT_EQ("DELETED", res->body);
  6351. res = cli_.Get("/person/john5");
  6352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6353. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6354. }
  6355. TEST_F(ServerTest, DeleteMethod3) {
  6356. auto res = cli_.Get("/person/john6");
  6357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6358. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6359. Params params;
  6360. params.emplace("name", "john6");
  6361. params.emplace("note", "tester");
  6362. res = cli_.Post("/person", params);
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. ASSERT_EQ(StatusCode::OK_200, res->status);
  6365. res = cli_.Get("/person/john6");
  6366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6367. ASSERT_EQ(StatusCode::OK_200, res->status);
  6368. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6369. ASSERT_EQ("tester", res->body);
  6370. Params delete_params;
  6371. delete_params.emplace("name", "john6");
  6372. Headers headers;
  6373. headers.emplace("Custom-Header", "test-value");
  6374. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6376. ASSERT_EQ(StatusCode::OK_200, res->status);
  6377. ASSERT_EQ("DELETED", res->body);
  6378. res = cli_.Get("/person/john6");
  6379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6380. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6381. }
  6382. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6383. Params params;
  6384. params.emplace("json", JSON_DATA);
  6385. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6387. ASSERT_EQ(StatusCode::OK_200, res->status);
  6388. ASSERT_EQ(JSON_DATA, res->body);
  6389. }
  6390. TEST_F(ServerTest, PostEmptyContent) {
  6391. auto res = cli_.Post("/empty", "", "text/plain");
  6392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6393. ASSERT_EQ(StatusCode::OK_200, res->status);
  6394. ASSERT_EQ("empty", res->body);
  6395. }
  6396. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6397. auto res = cli_.Post("/empty-no-content-type");
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. ASSERT_EQ(StatusCode::OK_200, res->status);
  6400. ASSERT_EQ("empty-no-content-type", res->body);
  6401. }
  6402. TEST_F(ServerTest, PostPathOnly) {
  6403. auto res = cli_.Post("/path-only");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. ASSERT_EQ(StatusCode::OK_200, res->status);
  6406. ASSERT_EQ("path-only", res->body);
  6407. }
  6408. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6409. auto res = cli_.Post("/path-headers-only",
  6410. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. ASSERT_EQ(StatusCode::OK_200, res->status);
  6413. ASSERT_EQ("path-headers-only", res->body);
  6414. }
  6415. TEST_F(ServerTest, PostLarge) {
  6416. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. ASSERT_EQ(StatusCode::OK_200, res->status);
  6419. EXPECT_EQ(LARGE_DATA, res->body);
  6420. }
  6421. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6422. auto res = cli_.Put("/empty-no-content-type");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. ASSERT_EQ(StatusCode::OK_200, res->status);
  6425. ASSERT_EQ("empty-no-content-type", res->body);
  6426. }
  6427. TEST_F(ServerTest, GetMethodDir) {
  6428. auto res = cli_.Get("/dir/");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::OK_200, res->status);
  6431. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6432. auto body = R"(<html>
  6433. <head>
  6434. </head>
  6435. <body>
  6436. <a href="/dir/test.html">Test</a>
  6437. <a href="/hi">hi</a>
  6438. </body>
  6439. </html>
  6440. )";
  6441. EXPECT_EQ(body, res->body);
  6442. }
  6443. TEST_F(ServerTest, GetMethodDirTest) {
  6444. auto res = cli_.Get("/dir/test.html");
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::OK_200, res->status);
  6447. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6448. EXPECT_EQ("test.html", res->body);
  6449. }
  6450. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6451. auto res = cli_.Get("/dir/../dir/test.html");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6454. }
  6455. TEST_F(ServerTest, GetMethodInvalidPath) {
  6456. auto res = cli_.Get("/dir/../test.html");
  6457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6458. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6459. }
  6460. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6461. auto res = cli_.Get("/../www/dir/test.html");
  6462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6464. }
  6465. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6466. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6469. }
  6470. TEST_F(ServerTest, GetMethodDirMountTest) {
  6471. auto res = cli_.Get("/mount/dir/test.html");
  6472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6473. EXPECT_EQ(StatusCode::OK_200, res->status);
  6474. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6475. EXPECT_EQ("test.html", res->body);
  6476. }
  6477. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6478. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6481. }
  6482. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6483. auto res = cli_.Get("/mount/dir/../test.html");
  6484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6486. }
  6487. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6488. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6491. }
  6492. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6493. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6495. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6496. }
  6497. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6498. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6500. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6501. }
  6502. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6503. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6506. }
  6507. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6508. auto res = cli_.Get("/mount/dir");
  6509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6510. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6511. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6512. }
  6513. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6514. auto res = cli_.Get("//dir");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6517. EXPECT_FALSE(res->has_header("Location"));
  6518. }
  6519. TEST_F(ServerTest, PostMethod303) {
  6520. auto res = cli_.Post("/1", "body", "text/plain");
  6521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6522. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6523. EXPECT_EQ("/2", res->get_header_value("Location"));
  6524. }
  6525. TEST_F(ServerTest, PostMethod303Redirect) {
  6526. cli_.set_follow_location(true);
  6527. auto res = cli_.Post("/1", "body", "text/plain");
  6528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6529. EXPECT_EQ(StatusCode::OK_200, res->status);
  6530. EXPECT_EQ("redirected.", res->body);
  6531. EXPECT_EQ("/2", res->location);
  6532. }
  6533. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6534. auto res = cli_.Get("/dir/test.abcde");
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::OK_200, res->status);
  6537. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6538. EXPECT_EQ("abcde", res->body);
  6539. }
  6540. TEST_F(ServerTest, StaticFileRange) {
  6541. auto res =
  6542. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6544. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6545. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6546. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6547. EXPECT_EQ(true, res->has_header("Content-Range"));
  6548. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6549. EXPECT_EQ(std::string("cd"), res->body);
  6550. }
  6551. TEST_F(ServerTest, StaticFileRanges) {
  6552. auto res = cli_.Get("/dir/test.abcde",
  6553. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6555. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6556. EXPECT_TRUE(
  6557. res->get_header_value("Content-Type")
  6558. .find(
  6559. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6560. 0);
  6561. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6562. }
  6563. TEST_F(ServerTest, StaticFileRangeHead) {
  6564. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6567. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6568. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6569. EXPECT_EQ(true, res->has_header("Content-Range"));
  6570. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6571. }
  6572. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6573. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6576. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6577. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6578. EXPECT_EQ(true, res->has_header("Content-Range"));
  6579. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6580. res->get_header_value("Content-Range"));
  6581. EXPECT_EQ("LAST\n", res->body);
  6582. }
  6583. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6584. auto res =
  6585. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6587. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6589. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6590. EXPECT_EQ(true, res->has_header("Content-Range"));
  6591. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6592. }
  6593. TEST_F(ServerTest, StaticFileBigFile) {
  6594. auto res = cli_.Get("/dir/1MB.txt");
  6595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6596. EXPECT_EQ(StatusCode::OK_200, res->status);
  6597. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6598. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6599. }
  6600. TEST_F(ServerTest, InvalidBaseDirMount) {
  6601. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6602. }
  6603. TEST_F(ServerTest, Binary) {
  6604. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6605. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6606. "application/octet-stream");
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. ASSERT_EQ(StatusCode::OK_200, res->status);
  6609. ASSERT_EQ(4U, res->body.size());
  6610. res = cli_.Put("/binary", binary.data(), binary.size(),
  6611. "application/octet-stream");
  6612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6613. ASSERT_EQ(StatusCode::OK_200, res->status);
  6614. ASSERT_EQ(4U, res->body.size());
  6615. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6616. "application/octet-stream");
  6617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6618. ASSERT_EQ(StatusCode::OK_200, res->status);
  6619. ASSERT_EQ(4U, res->body.size());
  6620. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6621. "application/octet-stream");
  6622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6623. ASSERT_EQ(StatusCode::OK_200, res->status);
  6624. ASSERT_EQ(4U, res->body.size());
  6625. }
  6626. TEST_F(ServerTest, BinaryString) {
  6627. auto binary = std::string("\x00\x01\x02\x03", 4);
  6628. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6630. ASSERT_EQ(StatusCode::OK_200, res->status);
  6631. ASSERT_EQ(4U, res->body.size());
  6632. res = cli_.Put("/binary", binary, "application/octet-stream");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. ASSERT_EQ(StatusCode::OK_200, res->status);
  6635. ASSERT_EQ(4U, res->body.size());
  6636. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. ASSERT_EQ(StatusCode::OK_200, res->status);
  6639. ASSERT_EQ(4U, res->body.size());
  6640. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6642. ASSERT_EQ(StatusCode::OK_200, res->status);
  6643. ASSERT_EQ(4U, res->body.size());
  6644. }
  6645. TEST_F(ServerTest, EmptyRequest) {
  6646. auto res = cli_.Get("");
  6647. ASSERT_TRUE(!res);
  6648. EXPECT_EQ(Error::Connection, res.error());
  6649. }
  6650. TEST_F(ServerTest, LongRequest) {
  6651. std::string request;
  6652. for (size_t i = 0; i < 545; i++) {
  6653. request += "/TooLongRequest";
  6654. }
  6655. request += "OK";
  6656. auto res = cli_.Get(request.c_str());
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6659. }
  6660. TEST_F(ServerTest, TooLongRequest) {
  6661. std::string request;
  6662. for (size_t i = 0; i < 546; i++) {
  6663. request += "/TooLongRequest";
  6664. }
  6665. request += "_NG";
  6666. auto start = std::chrono::high_resolution_clock::now();
  6667. cli_.set_keep_alive(true);
  6668. auto res = cli_.Get(request.c_str());
  6669. auto end = std::chrono::high_resolution_clock::now();
  6670. auto elapsed =
  6671. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6672. .count();
  6673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6674. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6675. EXPECT_LE(elapsed, 1000);
  6676. EXPECT_EQ("close", res->get_header_value("Connection"));
  6677. EXPECT_FALSE(cli_.is_socket_open());
  6678. }
  6679. TEST_F(ServerTest, AlmostTooLongRequest) {
  6680. // test for #2046 - URI length check shouldn't include other content on req
  6681. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6682. // leading /, space, HTTP/1.1)
  6683. std::string request =
  6684. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6685. auto res = cli_.Get(request.c_str());
  6686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6687. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6688. }
  6689. TEST_F(ServerTest, LongHeader) {
  6690. Request req;
  6691. req.method = "GET";
  6692. req.path = "/hi";
  6693. std::string host_and_port;
  6694. host_and_port += HOST;
  6695. host_and_port += ":";
  6696. host_and_port += std::to_string(PORT);
  6697. req.headers.emplace("Host", host_and_port.c_str());
  6698. req.headers.emplace("Accept", "*/*");
  6699. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6700. req.headers.emplace(
  6701. "Header-Name",
  6702. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6703. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6704. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6705. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6706. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6707. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6708. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6709. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6710. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6711. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6712. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6730. "@@@@@@@@@@@@@@@@");
  6731. auto res = std::make_shared<Response>();
  6732. auto error = Error::Success;
  6733. auto ret = cli_.send(req, *res, error);
  6734. ASSERT_TRUE(ret);
  6735. EXPECT_EQ(StatusCode::OK_200, res->status);
  6736. }
  6737. TEST_F(ServerTest, LongQueryValue) {
  6738. auto start = std::chrono::high_resolution_clock::now();
  6739. cli_.set_keep_alive(true);
  6740. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6741. auto end = std::chrono::high_resolution_clock::now();
  6742. auto elapsed =
  6743. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6744. .count();
  6745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6746. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6747. EXPECT_LE(elapsed, 1000);
  6748. EXPECT_EQ("close", res->get_header_value("Connection"));
  6749. EXPECT_FALSE(cli_.is_socket_open());
  6750. }
  6751. TEST_F(ServerTest, TooLongQueryValue) {
  6752. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6753. ASSERT_FALSE(res);
  6754. EXPECT_EQ(Error::Read, res.error());
  6755. }
  6756. TEST_F(ServerTest, TooLongHeader) {
  6757. Request req;
  6758. req.method = "GET";
  6759. req.path = "/hi";
  6760. std::string host_and_port;
  6761. host_and_port += HOST;
  6762. host_and_port += ":";
  6763. host_and_port += std::to_string(PORT);
  6764. req.headers.emplace("Host", host_and_port.c_str());
  6765. req.headers.emplace("Accept", "*/*");
  6766. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6767. req.headers.emplace(
  6768. "Header-Name",
  6769. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6770. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6771. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6772. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6773. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6774. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6775. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6776. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6777. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6778. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6779. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6797. "@@@@@@@@@@@@@@@@@");
  6798. auto res = std::make_shared<Response>();
  6799. auto error = Error::Success;
  6800. auto ret = cli_.send(req, *res, error);
  6801. ASSERT_TRUE(ret);
  6802. EXPECT_EQ(StatusCode::OK_200, res->status);
  6803. }
  6804. TEST_F(ServerTest, HeaderCountAtLimit) {
  6805. // Test with headers just under the 100 limit
  6806. httplib::Headers headers;
  6807. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6808. // This should keep us just under the 100 header limit
  6809. for (int i = 0; i < 95; i++) {
  6810. std::string name = "X-Test-Header-" + std::to_string(i);
  6811. std::string value = "value" + std::to_string(i);
  6812. headers.emplace(name, value);
  6813. }
  6814. // This should work fine as we're under the limit
  6815. auto res = cli_.Get("/hi", headers);
  6816. EXPECT_TRUE(res);
  6817. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6818. }
  6819. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6820. // Test with many headers to exceed the 100 limit
  6821. httplib::Headers headers;
  6822. // Add 150 headers to definitely exceed the 100 limit
  6823. for (int i = 0; i < 150; i++) {
  6824. std::string name = "X-Test-Header-" + std::to_string(i);
  6825. std::string value = "value" + std::to_string(i);
  6826. headers.emplace(name, value);
  6827. }
  6828. // This should fail due to exceeding header count limit
  6829. cli_.set_keep_alive(true);
  6830. auto res = cli_.Get("/hi", headers);
  6831. // The server should respond with 400 Bad Request
  6832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6833. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6834. EXPECT_EQ("close", res->get_header_value("Connection"));
  6835. EXPECT_FALSE(cli_.is_socket_open());
  6836. }
  6837. TEST_F(ServerTest, PercentEncoding) {
  6838. auto res = cli_.Get("/e%6edwith%");
  6839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6840. EXPECT_EQ(StatusCode::OK_200, res->status);
  6841. }
  6842. TEST_F(ServerTest, PercentEncodingUnicode) {
  6843. auto res = cli_.Get("/e%u006edwith%");
  6844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6845. EXPECT_EQ(StatusCode::OK_200, res->status);
  6846. }
  6847. TEST_F(ServerTest, InvalidPercentEncoding) {
  6848. auto res = cli_.Get("/%endwith%");
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6851. }
  6852. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6853. auto res = cli_.Get("/%uendwith%");
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6856. }
  6857. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6858. auto res = cli_.Get("/hello?aaa=bbb%");
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6861. }
  6862. TEST_F(ServerTest, PlusSignEncoding) {
  6863. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6865. EXPECT_EQ(StatusCode::OK_200, res->status);
  6866. EXPECT_EQ("a +b", res->body);
  6867. }
  6868. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6869. // This test simulates a potential DoS attack using many headers
  6870. // to verify our security fix prevents memory exhaustion
  6871. httplib::Headers attack_headers;
  6872. // Attempt to add many headers like an attacker would (200 headers to far
  6873. // exceed limit)
  6874. for (int i = 0; i < 200; i++) {
  6875. std::string name = "X-Attack-Header-" + std::to_string(i);
  6876. std::string value = "attack_payload_" + std::to_string(i);
  6877. attack_headers.emplace(name, value);
  6878. }
  6879. // Try to POST with excessive headers
  6880. cli_.set_keep_alive(true);
  6881. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6882. // Should either fail or return 400 Bad Request due to security limit
  6883. if (res) {
  6884. // If we get a response, it should be 400 Bad Request
  6885. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6886. EXPECT_EQ("close", res->get_header_value("Connection"));
  6887. }
  6888. EXPECT_FALSE(cli_.is_socket_open());
  6889. }
  6890. TEST_F(ServerTest, MultipartFormData) {
  6891. UploadFormDataItems items = {
  6892. {"text1", "text default", "", ""},
  6893. {"text2", "aωb", "", ""},
  6894. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6895. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6896. {"file3", "", "", "application/octet-stream"},
  6897. {"file4", "", "", " application/json tmp-string "}};
  6898. auto res = cli_.Post("/multipart", items);
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. EXPECT_EQ(StatusCode::OK_200, res->status);
  6901. }
  6902. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6903. UploadFormDataItems items = {
  6904. {"text", "default text", "", ""},
  6905. {"multi_text1", "aaaaa", "", ""},
  6906. {"multi_text1", "bbbbb", "", ""},
  6907. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6908. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6909. "application/json"},
  6910. };
  6911. auto res = cli_.Post("/multipart/multi_file_values", items);
  6912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6913. EXPECT_EQ(StatusCode::OK_200, res->status);
  6914. }
  6915. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6916. auto res = cli_.Get("/hi");
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. EXPECT_EQ(StatusCode::OK_200, res->status);
  6919. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6920. EXPECT_EQ("Hello World!", res->body);
  6921. }
  6922. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6923. Request req;
  6924. req.method = "POST";
  6925. req.path = "/chunked";
  6926. std::string host_and_port;
  6927. host_and_port += HOST;
  6928. host_and_port += ":";
  6929. host_and_port += std::to_string(PORT);
  6930. req.headers.emplace("Host", host_and_port.c_str());
  6931. req.headers.emplace("Accept", "*/*");
  6932. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6933. req.headers.emplace("Content-Type", "text/plain");
  6934. req.headers.emplace("Content-Length", "0");
  6935. req.headers.emplace(
  6936. "Transfer-Encoding",
  6937. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6938. // Client does not chunk, so make a chunked body manually.
  6939. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6940. auto res = std::make_shared<Response>();
  6941. auto error = Error::Success;
  6942. auto ret = cli_.send(req, *res, error);
  6943. ASSERT_TRUE(ret);
  6944. EXPECT_EQ(StatusCode::OK_200, res->status);
  6945. }
  6946. template <typename ClientT>
  6947. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6948. int expected_status) {
  6949. Request req;
  6950. req.method = "POST";
  6951. req.path = "/chunked";
  6952. std::string host_and_port;
  6953. host_and_port += HOST;
  6954. host_and_port += ":";
  6955. host_and_port += std::to_string(PORT);
  6956. req.headers.emplace("Host", host_and_port.c_str());
  6957. req.headers.emplace("Content-Length", "0");
  6958. req.headers.emplace("Transfer-Encoding", "chunked");
  6959. req.body = body;
  6960. auto res = std::make_shared<Response>();
  6961. auto error = Error::Success;
  6962. ASSERT_TRUE(cli.send(req, *res, error));
  6963. EXPECT_EQ(expected_status, res->status);
  6964. }
  6965. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6966. // rather than treat them as valid lengths.
  6967. template <typename ClientT>
  6968. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6969. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6970. }
  6971. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6972. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6973. }
  6974. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6975. expect_chunked_body_rejected(
  6976. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6977. }
  6978. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6979. // chunk-size line carries no CR, LF or other control character ahead of its
  6980. // terminator. Such a line must be refused rather than read as extension text.
  6981. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6982. expect_chunked_body_rejected(
  6983. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6984. }
  6985. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6986. expect_chunked_body_rejected(
  6987. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6988. }
  6989. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6990. expect_chunked_body_rejected(
  6991. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6992. }
  6993. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6994. // The literal stays split: a hex escape consumes every hex digit that
  6995. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6996. expect_chunked_body_rejected(
  6997. cli_, "4;a\x01"
  6998. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6999. }
  7000. // The bytes around chunk data are no payload, so they cannot ride on the
  7001. // payload limit
  7002. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7003. // Small enough that the whole request is sent before the server turns it
  7004. // down, yet past the limit by the last chunks
  7005. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7006. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7007. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7008. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7009. SCOPED_TRACE(size_line.substr(0, 2));
  7010. std::string body;
  7011. for (auto c : std::string("dechunked post body")) {
  7012. body += size_line + "\r\n" + c + "\r\n";
  7013. }
  7014. body += "0\r\n\r\n";
  7015. expect_chunked_body_rejected(cli_, body.c_str());
  7016. }
  7017. }
  7018. TEST_F(ServerTest, AcceptsChunkExtension) {
  7019. expect_chunked_body_status(cli_,
  7020. "4;name=value\r\ndech\r\n"
  7021. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7022. "0;last\r\n\r\n",
  7023. StatusCode::OK_200);
  7024. }
  7025. TEST_F(ServerTest, GetStreamed2) {
  7026. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7029. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7030. EXPECT_EQ(true, res->has_header("Content-Range"));
  7031. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7032. EXPECT_EQ(std::string("ab"), res->body);
  7033. }
  7034. TEST_F(ServerTest, GetStreamed) {
  7035. auto res = cli_.Get("/streamed");
  7036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7037. EXPECT_EQ(StatusCode::OK_200, res->status);
  7038. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7039. EXPECT_EQ(std::string("aaabbb"), res->body);
  7040. }
  7041. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7042. auto res = cli_.Get("/streamed-without-length",
  7043. Headers{make_range_header({{0, -1}})});
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::OK_200, res->status);
  7046. EXPECT_EQ(false, res->has_header("Content-Length"));
  7047. EXPECT_EQ(false, res->has_header("Content-Range"));
  7048. EXPECT_EQ(std::string("abcdefg"), res->body);
  7049. }
  7050. TEST_F(ServerTest, GetStreamedWithRange1) {
  7051. auto res =
  7052. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7054. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7055. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7056. EXPECT_EQ(true, res->has_header("Content-Range"));
  7057. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7058. EXPECT_EQ(std::string("def"), res->body);
  7059. }
  7060. TEST_F(ServerTest, GetStreamedWithRange2) {
  7061. auto res =
  7062. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7065. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7066. EXPECT_EQ(true, res->has_header("Content-Range"));
  7067. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7068. EXPECT_EQ(std::string("bcdefg"), res->body);
  7069. }
  7070. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7071. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7074. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7075. EXPECT_EQ(true, res->has_header("Content-Range"));
  7076. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7077. EXPECT_EQ(std::string("efg"), res->body);
  7078. }
  7079. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7080. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7081. // the entire representation.
  7082. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7083. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7086. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7087. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7088. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7089. }
  7090. }
  7091. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7092. auto res =
  7093. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7096. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7097. EXPECT_EQ(false, res->has_header("Content-Range"));
  7098. EXPECT_EQ(0U, res->body.size());
  7099. }
  7100. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7101. // Only a 206 is served as a partial representation. Under any other status
  7102. // `apply_ranges()` reported the full content length, so the body must match
  7103. // that header, and the content provider must never be asked for an offset
  7104. // outside the representation.
  7105. auto check = [&](int status, const char *range) {
  7106. auto path =
  7107. std::string("/streamed-with-range?status=") + std::to_string(status);
  7108. auto ctx = path + " Range: " + range;
  7109. auto res = cli_.Get(path, Headers{{"Range", range}});
  7110. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7111. EXPECT_EQ(status, res->status) << ctx;
  7112. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7113. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7114. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7115. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7116. };
  7117. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7118. check(403, "bytes=3-5");
  7119. // The offset is far past the representation.
  7120. check(403, "bytes=100000-100200");
  7121. // `first_pos` is still -1 here, and the bounds asserts in
  7122. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7123. check(403, "bytes=-3");
  7124. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7125. // multipart branch would have written one that is empty.
  7126. check(403, "bytes=1-2, 4-5");
  7127. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7128. // covers the whole representation.
  7129. check(200, "bytes=3-5");
  7130. check(200, "bytes=1-2, 4-5");
  7131. }
  7132. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7133. auto res =
  7134. cli_.Get("/streamed-with-range",
  7135. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7136. "92233720368547758079223372036854775807"}});
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7139. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7140. EXPECT_EQ(false, res->has_header("Content-Range"));
  7141. EXPECT_EQ(0U, res->body.size());
  7142. }
  7143. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7144. auto res = cli_.Get(
  7145. "/with-range",
  7146. Headers{{"Range",
  7147. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7148. {"Accept-Encoding", ""}});
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(true, res->has_header("Content-Range"));
  7153. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7154. EXPECT_EQ(std::string("abcdefg"), res->body);
  7155. }
  7156. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7157. auto res = cli_.Get("/with-range", Headers{
  7158. {"Range", "bytes=0-"},
  7159. {"Accept-Encoding", ""},
  7160. });
  7161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7162. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7163. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7164. EXPECT_EQ(true, res->has_header("Content-Range"));
  7165. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7166. EXPECT_EQ(std::string("abcdefg"), res->body);
  7167. }
  7168. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7169. auto res = cli_.Get("/streamed-with-range",
  7170. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7173. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7174. EXPECT_EQ(false, res->has_header("Content-Range"));
  7175. EXPECT_EQ(267U, res->body.size());
  7176. // Check that both range contents are present
  7177. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7178. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7179. // Check that Content-Range headers are present for both ranges
  7180. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7181. std::string::npos);
  7182. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7183. std::string::npos);
  7184. }
  7185. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7186. Ranges ranges;
  7187. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7188. ranges.emplace_back(0, -1);
  7189. }
  7190. auto res = cli_.Get("/streamed-with-range?error",
  7191. Headers{{make_range_header(ranges)}});
  7192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7193. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7194. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7195. EXPECT_EQ(false, res->has_header("Content-Range"));
  7196. EXPECT_EQ(0U, res->body.size());
  7197. }
  7198. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7199. auto res = cli_.Get("/streamed-with-range",
  7200. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7202. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7203. EXPECT_EQ(5U, res->body.size());
  7204. // Check that overlapping ranges are coalesced into a single range
  7205. EXPECT_EQ("bcdef", res->body);
  7206. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7207. // Should be single range, not multipart
  7208. EXPECT_TRUE(res->has_header("Content-Range"));
  7209. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7210. }
  7211. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7212. auto res = cli_.Get("/streamed-with-range",
  7213. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7215. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7216. EXPECT_EQ(268U, res->body.size());
  7217. // Check that both range contents are present
  7218. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7219. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7220. // Check that Content-Range headers are present for both ranges
  7221. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7222. std::string::npos);
  7223. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7224. std::string::npos);
  7225. }
  7226. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7227. auto res = cli_.Get("/streamed-with-range",
  7228. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7231. EXPECT_EQ(269U, res->body.size());
  7232. // Check that both duplicate range contents are present
  7233. size_t first_abc = res->body.find("abc\r\n");
  7234. EXPECT_TRUE(first_abc != std::string::npos);
  7235. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7236. EXPECT_TRUE(second_abc != std::string::npos);
  7237. // Check that Content-Range headers are present for both ranges
  7238. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7239. EXPECT_TRUE(first_range != std::string::npos);
  7240. size_t second_range =
  7241. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7242. EXPECT_TRUE(second_range != std::string::npos);
  7243. }
  7244. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7245. auto res =
  7246. cli_.Get("/streamed-with-range?error",
  7247. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7249. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7250. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7251. EXPECT_EQ(false, res->has_header("Content-Range"));
  7252. EXPECT_EQ(0U, res->body.size());
  7253. }
  7254. TEST_F(ServerTest, GetStreamedEndless) {
  7255. uint64_t offset = 0;
  7256. auto res = cli_.Get("/streamed-cancel",
  7257. [&](const char * /*data*/, uint64_t data_length) {
  7258. if (offset < 100) {
  7259. offset += data_length;
  7260. return true;
  7261. }
  7262. return false;
  7263. });
  7264. ASSERT_TRUE(!res);
  7265. EXPECT_EQ(Error::Canceled, res.error());
  7266. }
  7267. TEST_F(ServerTest, ClientStop) {
  7268. std::atomic_size_t count{4};
  7269. std::vector<std::thread> threads;
  7270. for (auto i = count.load(); i != 0; --i) {
  7271. threads.emplace_back([&]() {
  7272. auto res = cli_.Get("/streamed-cancel",
  7273. [&](const char *, uint64_t) { return true; });
  7274. --count;
  7275. ASSERT_TRUE(!res);
  7276. EXPECT_TRUE(res.error() == Error::Canceled ||
  7277. res.error() == Error::Read || res.error() == Error::Write);
  7278. });
  7279. }
  7280. std::this_thread::sleep_for(std::chrono::seconds(2));
  7281. while (count != 0) {
  7282. cli_.stop();
  7283. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7284. }
  7285. for (auto &t : threads) {
  7286. t.join();
  7287. }
  7288. }
  7289. TEST_F(ServerTest, GetWithRange1) {
  7290. auto res = cli_.Get("/with-range", Headers{
  7291. make_range_header({{3, 5}}),
  7292. {"Accept-Encoding", ""},
  7293. });
  7294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7296. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7297. EXPECT_EQ(true, res->has_header("Content-Range"));
  7298. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7299. EXPECT_EQ(std::string("def"), res->body);
  7300. }
  7301. TEST_F(ServerTest, GetWithRange2) {
  7302. auto res = cli_.Get("/with-range", Headers{
  7303. make_range_header({{1, -1}}),
  7304. {"Accept-Encoding", ""},
  7305. });
  7306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7307. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7308. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7309. EXPECT_EQ(true, res->has_header("Content-Range"));
  7310. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7311. EXPECT_EQ(std::string("bcdefg"), res->body);
  7312. }
  7313. TEST_F(ServerTest, GetWithRange3) {
  7314. auto res = cli_.Get("/with-range", Headers{
  7315. make_range_header({{0, 0}}),
  7316. {"Accept-Encoding", ""},
  7317. });
  7318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7319. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7320. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7321. EXPECT_EQ(true, res->has_header("Content-Range"));
  7322. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7323. EXPECT_EQ(std::string("a"), res->body);
  7324. }
  7325. TEST_F(ServerTest, GetWithRange4) {
  7326. auto res = cli_.Get("/with-range", Headers{
  7327. make_range_header({{-1, 2}}),
  7328. {"Accept-Encoding", ""},
  7329. });
  7330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7331. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7332. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7333. EXPECT_EQ(true, res->has_header("Content-Range"));
  7334. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7335. EXPECT_EQ(std::string("fg"), res->body);
  7336. }
  7337. TEST_F(ServerTest, GetWithRange5) {
  7338. auto res = cli_.Get("/with-range", Headers{
  7339. make_range_header({{0, 5}}),
  7340. {"Accept-Encoding", ""},
  7341. });
  7342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7343. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7344. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7345. EXPECT_EQ(true, res->has_header("Content-Range"));
  7346. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7347. EXPECT_EQ(std::string("abcdef"), res->body);
  7348. }
  7349. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7350. auto res =
  7351. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7353. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7354. }
  7355. TEST_F(ServerTest, GetWithRangeMultipart) {
  7356. auto res =
  7357. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7360. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7361. EXPECT_EQ(false, res->has_header("Content-Range"));
  7362. EXPECT_EQ(267U, res->body.size());
  7363. }
  7364. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7365. auto res = cli_.Get("/with-range",
  7366. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7369. }
  7370. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7371. auto res = cli_.Get("/with-range-customized-response",
  7372. Headers{{make_range_header({{1, 2}})}});
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7375. EXPECT_EQ(true, res->has_header("Content-Length"));
  7376. EXPECT_EQ(false, res->has_header("Content-Range"));
  7377. EXPECT_EQ(JSON_DATA, res->body);
  7378. }
  7379. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7380. auto res = cli_.Get("/with-range-customized-response",
  7381. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7383. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7384. EXPECT_EQ(true, res->has_header("Content-Length"));
  7385. EXPECT_EQ(false, res->has_header("Content-Range"));
  7386. EXPECT_EQ(JSON_DATA, res->body);
  7387. }
  7388. TEST_F(ServerTest, Issue1772) {
  7389. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7391. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7392. }
  7393. TEST_F(ServerTest, Issue609) {
  7394. auto res = cli_.Delete("/issue609");
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. EXPECT_EQ(std::string("ok"), res->body);
  7398. }
  7399. TEST_F(ServerTest, GetStreamedChunked) {
  7400. auto res = cli_.Get("/streamed-chunked");
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::OK_200, res->status);
  7403. EXPECT_EQ(std::string("123456789"), res->body);
  7404. }
  7405. TEST_F(ServerTest, GetStreamedChunked2) {
  7406. auto res = cli_.Get("/streamed-chunked2");
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::OK_200, res->status);
  7409. EXPECT_EQ(std::string("123456789"), res->body);
  7410. }
  7411. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7412. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::OK_200, res->status);
  7415. EXPECT_EQ(std::string("123456789"), res->body);
  7416. EXPECT_TRUE(res->has_header("Trailer"));
  7417. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7418. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7419. // Trailers are now stored separately from headers (security fix)
  7420. EXPECT_EQ(2U, res->trailers.size());
  7421. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7422. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7423. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7424. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7425. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7426. // Verify trailers are NOT in headers (security verification)
  7427. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7428. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7429. }
  7430. TEST_F(ServerTest, LargeChunkedPost) {
  7431. Request req;
  7432. req.method = "POST";
  7433. req.path = "/large-chunked";
  7434. std::string host_and_port;
  7435. host_and_port += HOST;
  7436. host_and_port += ":";
  7437. host_and_port += std::to_string(PORT);
  7438. req.headers.emplace("Host", host_and_port.c_str());
  7439. req.headers.emplace("Accept", "*/*");
  7440. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7441. req.headers.emplace("Content-Type", "text/plain");
  7442. req.headers.emplace("Content-Length", "0");
  7443. req.headers.emplace("Transfer-Encoding", "chunked");
  7444. std::string long_string(30 * 1024u, 'a');
  7445. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7446. // Attempt to make a large enough post to exceed OS buffers, to test that
  7447. // the server handles short reads if the full chunk data isn't available.
  7448. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7449. auto res = std::make_shared<Response>();
  7450. auto error = Error::Success;
  7451. auto ret = cli_.send(req, *res, error);
  7452. ASSERT_TRUE(ret);
  7453. EXPECT_EQ(StatusCode::OK_200, res->status);
  7454. }
  7455. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7456. auto res = cli_.Get("/remote_addr");
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7460. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7461. }
  7462. TEST_F(ServerTest, GetMethodLocalAddr) {
  7463. auto res = cli_.Get("/local_addr");
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::OK_200, res->status);
  7466. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7467. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7468. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7469. }
  7470. TEST_F(ServerTest, HTTPResponseSplitting) {
  7471. auto res = cli_.Get("/http_response_splitting");
  7472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. }
  7475. TEST_F(ServerTest, SlowRequest) {
  7476. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7477. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7478. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7479. }
  7480. #if 0
  7481. TEST_F(ServerTest, SlowPost) {
  7482. char buffer[64 * 1024];
  7483. memset(buffer, 0x42, sizeof(buffer));
  7484. auto res = cli_.Post(
  7485. "/slowpost", 64 * 1024 * 1024,
  7486. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7487. auto ret = sink.write(buffer, sizeof(buffer));
  7488. EXPECT_TRUE(ret);
  7489. return true;
  7490. },
  7491. "text/plain");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. }
  7495. TEST_F(ServerTest, SlowPostFail) {
  7496. char buffer[64 * 1024];
  7497. memset(buffer, 0x42, sizeof(buffer));
  7498. cli_.set_write_timeout(std::chrono::seconds(0));
  7499. auto res = cli_.Post(
  7500. "/slowpost", 64 * 1024 * 1024,
  7501. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7502. sink.write(buffer, sizeof(buffer));
  7503. return true;
  7504. },
  7505. "text/plain");
  7506. ASSERT_TRUE(!res);
  7507. EXPECT_EQ(Error::Write, res.error());
  7508. }
  7509. #endif
  7510. TEST_F(ServerTest, Put) {
  7511. auto res = cli_.Put("/put", "PUT", "text/plain");
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::OK_200, res->status);
  7514. EXPECT_EQ("PUT", res->body);
  7515. }
  7516. TEST_F(ServerTest, PutWithContentProvider) {
  7517. auto res = cli_.Put(
  7518. "/put", 3,
  7519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7520. sink.os << "PUT";
  7521. return true;
  7522. },
  7523. "text/plain");
  7524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7525. EXPECT_EQ(StatusCode::OK_200, res->status);
  7526. EXPECT_EQ("PUT", res->body);
  7527. }
  7528. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7529. auto res = cli_.Post(
  7530. "/post", 42,
  7531. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7532. return false;
  7533. },
  7534. "text/plain");
  7535. ASSERT_TRUE(!res);
  7536. EXPECT_EQ(Error::Canceled, res.error());
  7537. }
  7538. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7539. auto res = cli_.Put(
  7540. "/put",
  7541. [](size_t /*offset*/, DataSink &sink) {
  7542. sink.os << "PUT";
  7543. sink.done();
  7544. return true;
  7545. },
  7546. "text/plain");
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ(StatusCode::OK_200, res->status);
  7549. EXPECT_EQ("PUT", res->body);
  7550. }
  7551. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7552. auto res = cli_.Post(
  7553. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7554. "text/plain");
  7555. ASSERT_TRUE(!res);
  7556. EXPECT_EQ(Error::Canceled, res.error());
  7557. }
  7558. TEST_F(ServerTest, PostLoopBack) {
  7559. std::string body;
  7560. auto res = cli_.Post(
  7561. "/post-loopback", 9,
  7562. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7563. EXPECT_EQ(9u, length);
  7564. sink.write("123", 3);
  7565. sink.write("456", 3);
  7566. sink.write("789", 3);
  7567. return true;
  7568. },
  7569. "text/plain",
  7570. [&body](const char *data, size_t data_length) {
  7571. body.append(data, data_length);
  7572. return true;
  7573. });
  7574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. EXPECT_EQ("123456789", body);
  7577. }
  7578. TEST_F(ServerTest, PutLoopBack) {
  7579. std::string body;
  7580. auto res = cli_.Put(
  7581. "/put-loopback", 9,
  7582. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7583. EXPECT_EQ(9u, length);
  7584. sink.write("123", 3);
  7585. sink.write("456", 3);
  7586. sink.write("789", 3);
  7587. return true;
  7588. },
  7589. "text/plain",
  7590. [&body](const char *data, size_t data_length) {
  7591. body.append(data, data_length);
  7592. return true;
  7593. });
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::OK_200, res->status);
  7596. EXPECT_EQ("123456789", body);
  7597. }
  7598. TEST_F(ServerTest, PatchLoopBack) {
  7599. std::string body;
  7600. auto res = cli_.Patch(
  7601. "/patch-loopback", 9,
  7602. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7603. EXPECT_EQ(9u, length);
  7604. sink.write("123", 3);
  7605. sink.write("456", 3);
  7606. sink.write("789", 3);
  7607. return true;
  7608. },
  7609. "text/plain",
  7610. [&body](const char *data, size_t data_length) {
  7611. body.append(data, data_length);
  7612. return true;
  7613. });
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. EXPECT_EQ("123456789", body);
  7617. }
  7618. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7619. std::string body;
  7620. auto res = cli_.Post(
  7621. "/post-loopback",
  7622. [](size_t /*offset*/, DataSink &sink) {
  7623. sink.write("123", 3);
  7624. sink.write("456", 3);
  7625. sink.write("789", 3);
  7626. sink.done();
  7627. return true;
  7628. },
  7629. "text/plain",
  7630. [&body](const char *data, size_t data_length) {
  7631. body.append(data, data_length);
  7632. return true;
  7633. });
  7634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. EXPECT_EQ("123456789", body);
  7637. }
  7638. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7639. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7640. cli_.set_compress(true);
  7641. auto res = cli_.Put(
  7642. "/put", 3,
  7643. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7644. sink.os << "PUT";
  7645. return true;
  7646. },
  7647. "text/plain");
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. EXPECT_EQ("PUT", res->body);
  7651. }
  7652. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7653. cli_.set_compress(true);
  7654. auto res = cli_.Post(
  7655. "/post", 42,
  7656. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7657. return false;
  7658. },
  7659. "text/plain");
  7660. ASSERT_TRUE(!res);
  7661. EXPECT_EQ(Error::Canceled, res.error());
  7662. }
  7663. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7664. cli_.set_compress(true);
  7665. auto res = cli_.Put(
  7666. "/put",
  7667. [](size_t /*offset*/, DataSink &sink) {
  7668. sink.os << "PUT";
  7669. sink.done();
  7670. return true;
  7671. },
  7672. "text/plain");
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ("PUT", res->body);
  7676. }
  7677. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7678. cli_.set_compress(true);
  7679. auto res = cli_.Post(
  7680. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7681. "text/plain");
  7682. ASSERT_TRUE(!res);
  7683. EXPECT_EQ(Error::Canceled, res.error());
  7684. }
  7685. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7686. cli_.set_compress(true);
  7687. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7689. EXPECT_EQ(StatusCode::OK_200, res->status);
  7690. EXPECT_EQ(LARGE_DATA, res->body);
  7691. }
  7692. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7693. #ifdef CPPHTTPLIB_SSL_ENABLED
  7694. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7695. Client cli(s.c_str());
  7696. cli.enable_server_certificate_verification(false);
  7697. #else
  7698. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7699. Client cli(s.c_str());
  7700. #endif
  7701. cli.set_compress(true);
  7702. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. EXPECT_EQ(LARGE_DATA, res->body);
  7706. // The compressed size should be less than a 10th of the original. May vary
  7707. // depending on the zlib library.
  7708. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7709. static_cast<uint64_t>(10 * 1024 * 1024));
  7710. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7711. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7712. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7713. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7714. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7715. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7716. #endif
  7717. }
  7718. TEST_F(ServerTest, PutContentWithDeflate) {
  7719. cli_.set_compress(false);
  7720. Headers headers;
  7721. headers.emplace("Content-Encoding", "deflate");
  7722. // PUT in deflate format:
  7723. auto res = cli_.Put("/put", headers,
  7724. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("PUT", res->body);
  7728. }
  7729. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7730. Headers headers;
  7731. headers.emplace("Accept-Encoding", "gzip, deflate");
  7732. auto res = cli_.Get("/streamed-chunked", headers);
  7733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7734. EXPECT_EQ(StatusCode::OK_200, res->status);
  7735. EXPECT_EQ(std::string("123456789"), res->body);
  7736. }
  7737. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7738. Headers headers;
  7739. headers.emplace("Accept-Encoding", "gzip, deflate");
  7740. auto res = cli_.Get("/streamed-chunked2", headers);
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::OK_200, res->status);
  7743. EXPECT_EQ(std::string("123456789"), res->body);
  7744. }
  7745. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7746. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7748. EXPECT_EQ(StatusCode::OK_200, res->status);
  7749. }
  7750. TEST(GzipDecompressor, ChunkedDecompression) {
  7751. std::string data;
  7752. for (size_t i = 0; i < 32 * 1024; ++i) {
  7753. data.push_back(static_cast<char>('a' + i % 26));
  7754. }
  7755. std::string compressed_data;
  7756. {
  7757. httplib::detail::gzip_compressor compressor;
  7758. bool result = compressor.compress(
  7759. data.data(), data.size(),
  7760. /*last=*/true,
  7761. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7762. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7763. compressed_data_size);
  7764. return true;
  7765. });
  7766. ASSERT_TRUE(result);
  7767. }
  7768. std::string decompressed_data;
  7769. {
  7770. httplib::detail::gzip_decompressor decompressor;
  7771. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7772. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7773. size_t chunk_size = 130;
  7774. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7775. chunk_begin += chunk_size) {
  7776. size_t current_chunk_size =
  7777. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7778. bool result = decompressor.decompress(
  7779. compressed_data.data() + chunk_begin, current_chunk_size,
  7780. [&](const char *decompressed_data_chunk,
  7781. size_t decompressed_data_chunk_size) {
  7782. decompressed_data.insert(decompressed_data.size(),
  7783. decompressed_data_chunk,
  7784. decompressed_data_chunk_size);
  7785. return true;
  7786. });
  7787. ASSERT_TRUE(result);
  7788. }
  7789. }
  7790. ASSERT_EQ(data, decompressed_data);
  7791. }
  7792. TEST(GzipDecompressor, DeflateDecompression) {
  7793. std::string original_text = "Raw deflate without gzip";
  7794. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7795. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7796. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7797. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7798. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7799. std::string decompressed_data;
  7800. {
  7801. httplib::detail::gzip_decompressor decompressor;
  7802. bool result = decompressor.decompress(
  7803. compressed_data.data(), compressed_data.size(),
  7804. [&](const char *decompressed_data_chunk,
  7805. size_t decompressed_data_chunk_size) {
  7806. decompressed_data.insert(decompressed_data.size(),
  7807. decompressed_data_chunk,
  7808. decompressed_data_chunk_size);
  7809. return true;
  7810. });
  7811. ASSERT_TRUE(result);
  7812. }
  7813. ASSERT_EQ(original_text, decompressed_data);
  7814. }
  7815. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7816. std::string original_text = "Raw deflate without gzip";
  7817. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7818. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7819. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7820. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7821. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7822. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7823. std::string decompressed_data;
  7824. {
  7825. httplib::detail::gzip_decompressor decompressor;
  7826. bool result = decompressor.decompress(
  7827. compressed_data.data(), compressed_data.size(),
  7828. [&](const char *decompressed_data_chunk,
  7829. size_t decompressed_data_chunk_size) {
  7830. decompressed_data.insert(decompressed_data.size(),
  7831. decompressed_data_chunk,
  7832. decompressed_data_chunk_size);
  7833. return true;
  7834. });
  7835. ASSERT_TRUE(result);
  7836. }
  7837. ASSERT_EQ(original_text, decompressed_data);
  7838. }
  7839. #endif
  7840. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7841. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7842. Headers headers;
  7843. headers.emplace("Accept-Encoding", "br");
  7844. auto res = cli_.Get("/streamed-chunked", headers);
  7845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7846. EXPECT_EQ(StatusCode::OK_200, res->status);
  7847. EXPECT_EQ(std::string("123456789"), res->body);
  7848. }
  7849. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7850. Headers headers;
  7851. headers.emplace("Accept-Encoding", "br");
  7852. auto res = cli_.Get("/streamed-chunked2", headers);
  7853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7854. EXPECT_EQ(StatusCode::OK_200, res->status);
  7855. EXPECT_EQ(std::string("123456789"), res->body);
  7856. }
  7857. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7858. cli_.set_compress(true);
  7859. auto res = cli_.Put(
  7860. "/put", 3,
  7861. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7862. sink.os << "PUT";
  7863. return true;
  7864. },
  7865. "text/plain");
  7866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7867. EXPECT_EQ(StatusCode::OK_200, res->status);
  7868. EXPECT_EQ("PUT", res->body);
  7869. }
  7870. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7871. cli_.set_compress(true);
  7872. auto res = cli_.Put(
  7873. "/put",
  7874. [](size_t /*offset*/, DataSink &sink) {
  7875. sink.os << "PUT";
  7876. sink.done();
  7877. return true;
  7878. },
  7879. "text/plain");
  7880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7881. EXPECT_EQ(StatusCode::OK_200, res->status);
  7882. EXPECT_EQ("PUT", res->body);
  7883. }
  7884. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7885. cli_.set_compress(true);
  7886. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. EXPECT_EQ(LARGE_DATA, res->body);
  7890. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7891. }
  7892. #endif
  7893. TEST_F(ServerTest, Patch) {
  7894. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7896. EXPECT_EQ(StatusCode::OK_200, res->status);
  7897. EXPECT_EQ("PATCH", res->body);
  7898. }
  7899. TEST_F(ServerTest, Delete) {
  7900. auto res = cli_.Delete("/delete");
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ(StatusCode::OK_200, res->status);
  7903. EXPECT_EQ("DELETE", res->body);
  7904. }
  7905. TEST_F(ServerTest, DeleteContentReceiver) {
  7906. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7908. EXPECT_EQ(StatusCode::OK_200, res->status);
  7909. EXPECT_EQ("content", res->body);
  7910. }
  7911. TEST_F(ServerTest, Options) {
  7912. auto res = cli_.Options("*");
  7913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7916. EXPECT_TRUE(res->body.empty());
  7917. }
  7918. TEST_F(ServerTest, URL) {
  7919. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7921. EXPECT_EQ(StatusCode::OK_200, res->status);
  7922. }
  7923. TEST_F(ServerTest, ArrayParam) {
  7924. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7926. EXPECT_EQ(StatusCode::OK_200, res->status);
  7927. }
  7928. TEST_F(ServerTest, ArrayParamValues) {
  7929. auto res =
  7930. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7932. EXPECT_EQ(StatusCode::OK_200, res->status);
  7933. }
  7934. TEST_F(ServerTest, NoMultipleHeaders) {
  7935. Headers headers = {{"Content-Length", "5"}};
  7936. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7937. "text/plain");
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. }
  7941. TEST_F(ServerTest, PostContentReceiver) {
  7942. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7944. ASSERT_EQ(StatusCode::OK_200, res->status);
  7945. ASSERT_EQ("content", res->body);
  7946. }
  7947. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7948. UploadFormDataItems items = {
  7949. {"text1", "text default", "", ""},
  7950. {"text2", "aωb", "", ""},
  7951. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7952. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7953. {"file3", "", "", "application/octet-stream"},
  7954. };
  7955. auto res = cli_.Post("/content_receiver", items);
  7956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7957. EXPECT_EQ(StatusCode::OK_200, res->status);
  7958. }
  7959. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7960. UploadFormDataItems items = {
  7961. {"text1", "text default", "", ""},
  7962. {"text2", "aωb", "", ""},
  7963. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7964. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7965. {"file3", "", "", "application/octet-stream"},
  7966. };
  7967. auto boundary = std::string("+++++");
  7968. std::string body;
  7969. for (const auto &item : items) {
  7970. body += "--" + boundary + "\r\n";
  7971. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7972. if (!item.filename.empty()) {
  7973. body += "; filename=\"" + item.filename + "\"";
  7974. }
  7975. body += "\r\n";
  7976. if (!item.content_type.empty()) {
  7977. body += "Content-Type: " + item.content_type + "\r\n";
  7978. }
  7979. body += "\r\n";
  7980. body += item.content + "\r\n";
  7981. }
  7982. body += "--" + boundary + "--\r\n";
  7983. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7984. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. }
  7988. TEST(MultipartFormDataTest, FieldEscaping) {
  7989. Server svr;
  7990. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7991. const ContentReader &content_reader) {
  7992. ASSERT_TRUE(req.is_multipart_form_data());
  7993. std::vector<FormData> received;
  7994. content_reader(
  7995. [&](const FormData &file) {
  7996. received.push_back(file);
  7997. return true;
  7998. },
  7999. [&](const char *data, size_t data_length) {
  8000. received.back().content.append(data, data_length);
  8001. return true;
  8002. });
  8003. // '"', CR and LF in names and filenames are escaped following the
  8004. // WHATWG HTML standard, so each part still parses as a single part
  8005. // with no injected headers. Content types get CR/LF escaped too,
  8006. // while '"' (legal there, e.g. quoted charset) is preserved.
  8007. ASSERT_EQ(4U, received.size());
  8008. EXPECT_EQ("na%22me", received[0].name);
  8009. EXPECT_EQ("quoted name", received[0].content);
  8010. EXPECT_EQ("file", received[1].name);
  8011. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8012. received[1].filename);
  8013. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8014. EXPECT_EQ("injected", received[1].content);
  8015. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8016. EXPECT_EQ("my%22file.txt", received[2].filename);
  8017. EXPECT_EQ("cr lf name", received[2].content);
  8018. EXPECT_EQ("typed", received[3].name);
  8019. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8020. received[3].content_type);
  8021. EXPECT_EQ("typed content", received[3].content);
  8022. });
  8023. auto port = svr.bind_to_any_port("localhost");
  8024. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8025. auto se = detail::scope_exit([&] {
  8026. svr.stop();
  8027. t.join();
  8028. ASSERT_FALSE(svr.is_running());
  8029. });
  8030. svr.wait_until_ready();
  8031. Client cli("localhost", port);
  8032. UploadFormDataItems items = {
  8033. {"na\"me", "quoted name", "", ""},
  8034. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8035. "application/octet-stream"},
  8036. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8037. {"typed", "typed content", "",
  8038. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8039. };
  8040. auto res = cli.Post("/post", items);
  8041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8042. EXPECT_EQ(StatusCode::OK_200, res->status);
  8043. }
  8044. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8045. const UploadFormDataItems items = {
  8046. {"name1", "Content 1", "", ""},
  8047. {"name2", "Content 2", "file2.txt", "text/plain"},
  8048. };
  8049. Server svr;
  8050. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8051. const ContentReader &content_reader) {
  8052. ASSERT_TRUE(req.is_multipart_form_data());
  8053. std::vector<FormData> received;
  8054. content_reader(
  8055. [&](const FormData &file) {
  8056. received.push_back(file);
  8057. return true;
  8058. },
  8059. [&](const char *data, size_t data_length) {
  8060. received.back().content.append(data, data_length);
  8061. return true;
  8062. });
  8063. ASSERT_EQ(2U, received.size());
  8064. EXPECT_EQ("name1", received[0].name);
  8065. EXPECT_EQ("Content 1", received[0].content);
  8066. EXPECT_EQ("name2", received[1].name);
  8067. EXPECT_EQ("Content 2", received[1].content);
  8068. EXPECT_EQ("file2.txt", received[1].filename);
  8069. EXPECT_EQ("text/plain", received[1].content_type);
  8070. });
  8071. auto port = svr.bind_to_any_port("localhost");
  8072. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8073. auto se = detail::scope_exit([&] {
  8074. svr.stop();
  8075. t.join();
  8076. ASSERT_FALSE(svr.is_running());
  8077. });
  8078. svr.wait_until_ready();
  8079. Client cli("localhost", port);
  8080. // Whole-body serialization with a generated boundary
  8081. {
  8082. MultipartFormDataWriter writer;
  8083. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8084. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8085. writer.content_type());
  8086. auto body = writer.serialize(items);
  8087. EXPECT_EQ(body.size(), writer.content_length(items));
  8088. auto res = cli.Post("/post", body, writer.content_type());
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::OK_200, res->status);
  8091. }
  8092. // Per-part framing with a custom boundary via a content provider
  8093. {
  8094. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8095. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8096. MultipartFormDataWriter writer("custom-boundary_123");
  8097. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8098. std::string body;
  8099. for (const auto &item : items) {
  8100. body += writer.item_begin(item);
  8101. body += item.content;
  8102. body += MultipartFormDataWriter::item_end();
  8103. }
  8104. body += writer.finish();
  8105. EXPECT_EQ(body.size(), writer.content_length(items));
  8106. auto res = cli.Post(
  8107. "/post", body.size(),
  8108. [&](size_t offset, size_t length, DataSink &sink) {
  8109. sink.write(body.data() + offset, length);
  8110. return true;
  8111. },
  8112. writer.content_type());
  8113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8114. EXPECT_EQ(StatusCode::OK_200, res->status);
  8115. }
  8116. }
  8117. TEST_F(ServerTest, PostContentReceiverGzip) {
  8118. cli_.set_compress(true);
  8119. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. ASSERT_EQ(StatusCode::OK_200, res->status);
  8122. ASSERT_EQ("content", res->body);
  8123. }
  8124. TEST_F(ServerTest, PutContentReceiver) {
  8125. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8127. ASSERT_EQ(StatusCode::OK_200, res->status);
  8128. ASSERT_EQ("content", res->body);
  8129. }
  8130. TEST_F(ServerTest, PatchContentReceiver) {
  8131. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. ASSERT_EQ(StatusCode::OK_200, res->status);
  8134. ASSERT_EQ("content", res->body);
  8135. }
  8136. template <typename ClientType>
  8137. void TestWithHeadersAndContentReceiver(
  8138. ClientType &cli,
  8139. std::function<Result(ClientType &, const std::string &, const Headers &,
  8140. const std::string &, const std::string &,
  8141. ContentReceiver, DownloadProgress)>
  8142. request_func) {
  8143. Headers headers;
  8144. headers.emplace("X-Custom-Header", "test-value");
  8145. std::string received_body;
  8146. auto res = request_func(
  8147. cli, "/content_receiver", headers, "content", "application/json",
  8148. [&](const char *data, size_t data_length) {
  8149. received_body.append(data, data_length);
  8150. return true;
  8151. },
  8152. nullptr);
  8153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8154. EXPECT_EQ(StatusCode::OK_200, res->status);
  8155. EXPECT_EQ("content", received_body);
  8156. }
  8157. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8158. #ifdef CPPHTTPLIB_SSL_ENABLED
  8159. using ClientT = SSLClient;
  8160. #else
  8161. using ClientT = Client;
  8162. #endif
  8163. TestWithHeadersAndContentReceiver<ClientT>(
  8164. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8165. const std::string &body, const std::string &content_type,
  8166. ContentReceiver receiver, DownloadProgress progress) {
  8167. return cli.Post(path, headers, body, content_type, receiver, progress);
  8168. });
  8169. }
  8170. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8171. #ifdef CPPHTTPLIB_SSL_ENABLED
  8172. using ClientT = SSLClient;
  8173. #else
  8174. using ClientT = Client;
  8175. #endif
  8176. TestWithHeadersAndContentReceiver<ClientT>(
  8177. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8178. const std::string &body, const std::string &content_type,
  8179. ContentReceiver receiver, DownloadProgress progress) {
  8180. return cli.Put(path, headers, body, content_type, receiver, progress);
  8181. });
  8182. }
  8183. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8184. #ifdef CPPHTTPLIB_SSL_ENABLED
  8185. using ClientT = SSLClient;
  8186. #else
  8187. using ClientT = Client;
  8188. #endif
  8189. TestWithHeadersAndContentReceiver<ClientT>(
  8190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8191. const std::string &body, const std::string &content_type,
  8192. ContentReceiver receiver, DownloadProgress progress) {
  8193. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8194. });
  8195. }
  8196. template <typename ClientType>
  8197. void TestWithHeadersAndContentReceiverWithProgress(
  8198. ClientType &cli,
  8199. std::function<Result(ClientType &, const std::string &, const Headers &,
  8200. const std::string &, const std::string &,
  8201. ContentReceiver, DownloadProgress)>
  8202. request_func) {
  8203. Headers headers;
  8204. headers.emplace("X-Test-Header", "progress-test");
  8205. std::string received_body;
  8206. auto progress_called = false;
  8207. auto res = request_func(
  8208. cli, "/content_receiver", headers, "content", "text/plain",
  8209. [&](const char *data, size_t data_length) {
  8210. received_body.append(data, data_length);
  8211. return true;
  8212. },
  8213. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8214. progress_called = true;
  8215. return true;
  8216. });
  8217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8218. EXPECT_EQ(StatusCode::OK_200, res->status);
  8219. EXPECT_EQ("content", received_body);
  8220. EXPECT_TRUE(progress_called);
  8221. }
  8222. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8223. #ifdef CPPHTTPLIB_SSL_ENABLED
  8224. using ClientT = SSLClient;
  8225. #else
  8226. using ClientT = Client;
  8227. #endif
  8228. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8229. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8230. const std::string &body, const std::string &content_type,
  8231. ContentReceiver receiver, DownloadProgress progress) {
  8232. return cli.Post(path, headers, body, content_type, receiver, progress);
  8233. });
  8234. }
  8235. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8236. #ifdef CPPHTTPLIB_SSL_ENABLED
  8237. using ClientT = SSLClient;
  8238. #else
  8239. using ClientT = Client;
  8240. #endif
  8241. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8242. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8243. const std::string &body, const std::string &content_type,
  8244. ContentReceiver receiver, DownloadProgress progress) {
  8245. return cli.Put(path, headers, body, content_type, receiver, progress);
  8246. });
  8247. }
  8248. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8249. #ifdef CPPHTTPLIB_SSL_ENABLED
  8250. using ClientT = SSLClient;
  8251. #else
  8252. using ClientT = Client;
  8253. #endif
  8254. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8255. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8256. const std::string &body, const std::string &content_type,
  8257. ContentReceiver receiver, DownloadProgress progress) {
  8258. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8259. });
  8260. }
  8261. template <typename ClientType>
  8262. void TestWithHeadersAndContentReceiverError(
  8263. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8264. const Headers &, const std::string &,
  8265. const std::string &, ContentReceiver)>
  8266. request_func) {
  8267. Headers headers;
  8268. headers.emplace("X-Error-Test", "true");
  8269. std::string received_body;
  8270. auto receiver_failed = false;
  8271. auto res =
  8272. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8273. [&](const char *data, size_t data_length) {
  8274. received_body.append(data, data_length);
  8275. receiver_failed = true;
  8276. return false;
  8277. });
  8278. ASSERT_FALSE(res);
  8279. EXPECT_TRUE(receiver_failed);
  8280. }
  8281. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8282. #ifdef CPPHTTPLIB_SSL_ENABLED
  8283. using ClientT = SSLClient;
  8284. #else
  8285. using ClientT = Client;
  8286. #endif
  8287. TestWithHeadersAndContentReceiverError<ClientT>(
  8288. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8289. const std::string &body, const std::string &content_type,
  8290. ContentReceiver receiver) {
  8291. return cli.Post(path, headers, body, content_type, receiver);
  8292. });
  8293. }
  8294. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8295. #ifdef CPPHTTPLIB_SSL_ENABLED
  8296. using ClientT = SSLClient;
  8297. #else
  8298. using ClientT = Client;
  8299. #endif
  8300. TestWithHeadersAndContentReceiverError<ClientT>(
  8301. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8302. const std::string &body, const std::string &content_type,
  8303. ContentReceiver receiver) {
  8304. return cli.Put(path, headers, body, content_type, receiver);
  8305. });
  8306. }
  8307. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8308. #ifdef CPPHTTPLIB_SSL_ENABLED
  8309. using ClientT = SSLClient;
  8310. #else
  8311. using ClientT = Client;
  8312. #endif
  8313. TestWithHeadersAndContentReceiverError<ClientT>(
  8314. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8315. const std::string &body, const std::string &content_type,
  8316. ContentReceiver receiver) {
  8317. return cli.Patch(path, headers, body, content_type, receiver);
  8318. });
  8319. }
  8320. TEST_F(ServerTest, PostQueryStringAndBody) {
  8321. auto res =
  8322. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8324. ASSERT_EQ(StatusCode::OK_200, res->status);
  8325. }
  8326. TEST_F(ServerTest, HTTP2Magic) {
  8327. Request req;
  8328. req.method = "PRI";
  8329. req.path = "*";
  8330. req.body = "SM";
  8331. auto res = std::make_shared<Response>();
  8332. auto error = Error::Success;
  8333. auto ret = cli_.send(req, *res, error);
  8334. ASSERT_TRUE(ret);
  8335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8336. }
  8337. TEST_F(ServerTest, KeepAlive) {
  8338. auto res = cli_.Get("/hi");
  8339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8342. EXPECT_EQ("Hello World!", res->body);
  8343. res = cli_.Get("/hi");
  8344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8345. EXPECT_EQ(StatusCode::OK_200, res->status);
  8346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8347. EXPECT_EQ("Hello World!", res->body);
  8348. res = cli_.Get("/hi");
  8349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8350. EXPECT_EQ(StatusCode::OK_200, res->status);
  8351. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8352. EXPECT_EQ("Hello World!", res->body);
  8353. res = cli_.Get("/not-exist");
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8356. res = cli_.Post("/empty", "", "text/plain");
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ(StatusCode::OK_200, res->status);
  8359. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8360. EXPECT_EQ("empty", res->body);
  8361. EXPECT_EQ("close", res->get_header_value("Connection"));
  8362. res = cli_.Post(
  8363. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8364. "text/plain");
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ(StatusCode::OK_200, res->status);
  8367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8368. EXPECT_EQ("empty", res->body);
  8369. cli_.set_keep_alive(false);
  8370. res = cli_.Get("/last-request");
  8371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8372. EXPECT_EQ(StatusCode::OK_200, res->status);
  8373. EXPECT_EQ("close", res->get_header_value("Connection"));
  8374. }
  8375. TEST_F(ServerTest, TooManyRedirect) {
  8376. cli_.set_follow_location(true);
  8377. auto res = cli_.Get("/redirect/0");
  8378. ASSERT_TRUE(!res);
  8379. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8380. }
  8381. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8382. Request req;
  8383. req.method = "FOOBAR";
  8384. req.path = "/hi";
  8385. cli_.set_keep_alive(true);
  8386. auto res = cli_.send(req);
  8387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8388. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8389. EXPECT_EQ("close", res->get_header_value("Connection"));
  8390. EXPECT_FALSE(cli_.is_socket_open());
  8391. }
  8392. TEST_F(ServerTest, CustomRouteReadsBody) {
  8393. const std::string xml =
  8394. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8395. Request req;
  8396. req.method = "PROPFIND";
  8397. req.path = "/dav/dir";
  8398. req.set_header("Depth", "1");
  8399. req.body = xml;
  8400. auto res = cli_.send(req);
  8401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8402. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8403. EXPECT_EQ(xml, res->body);
  8404. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8405. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8406. }
  8407. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8408. Request req;
  8409. req.method = "PROPFIND";
  8410. req.path = "/dav/42";
  8411. auto res = cli_.send(req);
  8412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8413. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8414. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8415. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8416. }
  8417. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8418. Request req;
  8419. req.method = "PROPFIND";
  8420. req.path = "/dav-re/123";
  8421. auto res = cli_.send(req);
  8422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8423. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8424. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8425. }
  8426. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8427. Request req;
  8428. req.method = "MKCOL";
  8429. req.path = "/dav-mkcol";
  8430. auto res = cli_.send(req);
  8431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8432. EXPECT_EQ(StatusCode::Created_201, res->status);
  8433. }
  8434. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8435. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8436. Request req;
  8437. req.method = "REPORT";
  8438. req.path = "/dav-report";
  8439. req.body = xml;
  8440. auto res = cli_.send(req);
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8443. EXPECT_EQ(xml, res->body);
  8444. }
  8445. // A content reader route must fire even when the request carries no body,
  8446. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8447. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8448. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8449. Request req;
  8450. req.method = "REPORT";
  8451. req.path = "/dav-report";
  8452. auto res = cli_.send(req);
  8453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8454. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8455. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8456. }
  8457. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8458. Request req;
  8459. req.method = "PROPFIND";
  8460. req.path = "/not-dav";
  8461. auto res = cli_.send(req);
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8464. }
  8465. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8466. Request req;
  8467. req.method = "UNLOCK";
  8468. req.path = "/dav/dir";
  8469. cli_.set_keep_alive(true);
  8470. auto res = cli_.send(req);
  8471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8472. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8473. EXPECT_EQ("close", res->get_header_value("Connection"));
  8474. EXPECT_FALSE(cli_.is_socket_open());
  8475. }
  8476. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8477. // The mount point serves this path, but only for GET and HEAD.
  8478. auto get_res = cli_.Get("/dir/index.html");
  8479. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8480. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8481. Request req;
  8482. req.method = "PROPFIND";
  8483. req.path = "/dir/index.html";
  8484. auto res = cli_.send(req);
  8485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8487. }
  8488. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8489. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8490. cli_.set_keep_alive(true);
  8491. for (auto i = 0; i < 2; i++) {
  8492. Request req;
  8493. req.method = "PROPFIND";
  8494. req.path = "/dav/dir";
  8495. req.body = xml;
  8496. auto res = cli_.send(req);
  8497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8498. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8499. EXPECT_EQ(xml, res->body);
  8500. EXPECT_TRUE(cli_.is_socket_open());
  8501. }
  8502. // A built-in method must still be served on the same connection.
  8503. cli_.set_keep_alive(false);
  8504. auto res = cli_.Get("/hi");
  8505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8506. EXPECT_EQ(StatusCode::OK_200, res->status);
  8507. EXPECT_EQ("close", res->get_header_value("Connection"));
  8508. }
  8509. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8510. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8511. Request req;
  8512. req.method = "PROPFIND";
  8513. req.path = "/dav/dir";
  8514. req.set_header("Expect", "100-continue");
  8515. req.body = xml;
  8516. auto res = cli_.send(req);
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8519. EXPECT_EQ(xml, res->body);
  8520. }
  8521. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8522. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8523. TEST_F(ServerTest, Gzip) {
  8524. Headers headers;
  8525. headers.emplace("Accept-Encoding", "gzip, deflate");
  8526. auto res = cli_.Get("/compress", headers);
  8527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8528. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8529. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8530. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8531. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8532. "7890123456789012345678901234567890",
  8533. res->body);
  8534. EXPECT_EQ(StatusCode::OK_200, res->status);
  8535. }
  8536. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8537. Headers headers;
  8538. headers.emplace("Accept-Encoding", "gzip, deflate");
  8539. auto res = cli_.Get("/compress-with-charset", headers);
  8540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8541. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8542. EXPECT_EQ("application/json; charset=utf-8",
  8543. res->get_header_value("Content-Type"));
  8544. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8545. "7890123456789012345678901234567890",
  8546. res->body);
  8547. EXPECT_EQ(StatusCode::OK_200, res->status);
  8548. }
  8549. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8550. Headers headers;
  8551. headers.emplace("Accept-Encoding", "");
  8552. auto res = cli_.Get("/compress", headers);
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8556. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8558. "7890123456789012345678901234567890",
  8559. res->body);
  8560. EXPECT_EQ(StatusCode::OK_200, res->status);
  8561. }
  8562. TEST_F(ServerTest, GzipWithContentReceiver) {
  8563. Headers headers;
  8564. headers.emplace("Accept-Encoding", "gzip, deflate");
  8565. std::string body;
  8566. auto res =
  8567. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8568. EXPECT_EQ(100U, data_length);
  8569. body.append(data, data_length);
  8570. return true;
  8571. });
  8572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8573. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8575. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8576. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8577. "7890123456789012345678901234567890",
  8578. body);
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8582. Headers headers;
  8583. headers.emplace("Accept-Encoding", "gzip, deflate");
  8584. cli_.set_decompress(false);
  8585. auto res = cli_.Get("/compress", headers);
  8586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8587. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8589. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8590. EXPECT_EQ(33U, res->body.size());
  8591. EXPECT_EQ(StatusCode::OK_200, res->status);
  8592. }
  8593. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8594. Headers headers;
  8595. headers.emplace("Accept-Encoding", "");
  8596. std::string body;
  8597. auto res =
  8598. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8599. EXPECT_EQ(100U, data_length);
  8600. body.append(data, data_length);
  8601. return true;
  8602. });
  8603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8604. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8605. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8606. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8607. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8608. "7890123456789012345678901234567890",
  8609. body);
  8610. EXPECT_EQ(StatusCode::OK_200, res->status);
  8611. }
  8612. TEST_F(ServerTest, NoGzip) {
  8613. Headers headers;
  8614. headers.emplace("Accept-Encoding", "gzip, deflate");
  8615. auto res = cli_.Get("/nocompress", headers);
  8616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8617. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8618. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8619. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8620. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8621. "7890123456789012345678901234567890",
  8622. res->body);
  8623. EXPECT_EQ(StatusCode::OK_200, res->status);
  8624. }
  8625. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8626. Headers headers;
  8627. headers.emplace("Accept-Encoding", "gzip, deflate");
  8628. std::string body;
  8629. auto res = cli_.Get("/nocompress", headers,
  8630. [&](const char *data, size_t data_length) {
  8631. EXPECT_EQ(100U, data_length);
  8632. body.append(data, data_length);
  8633. return true;
  8634. });
  8635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8636. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8637. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8638. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8639. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8640. "7890123456789012345678901234567890",
  8641. body);
  8642. EXPECT_EQ(StatusCode::OK_200, res->status);
  8643. }
  8644. TEST_F(ServerTest, MultipartFormDataGzip) {
  8645. UploadFormDataItems items = {
  8646. {"key1", "test", "", ""},
  8647. {"key2", "--abcdefg123", "", ""},
  8648. };
  8649. cli_.set_compress(true);
  8650. auto res = cli_.Post("/compress-multipart", items);
  8651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8652. EXPECT_EQ(StatusCode::OK_200, res->status);
  8653. }
  8654. #endif
  8655. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8656. // Static file compression is opt-in, so these run their own server rather than
  8657. // flipping it on for the shared ServerTest fixture, which would silently
  8658. // rewrite what every other static file test is asserting.
  8659. class StaticFileCompressionTest : public ::testing::Test {
  8660. protected:
  8661. void TearDown() override {
  8662. if (t_.joinable()) {
  8663. svr_.stop();
  8664. t_.join();
  8665. }
  8666. }
  8667. int start(const std::function<void(Server &)> &configure = nullptr) {
  8668. // Serves the same tree as a directory of build-time compressed assets
  8669. // would be served: the mount point names the coding the files are already
  8670. // stored in. Registered before "/" so it is the one that matches.
  8671. svr_.set_mount_point("/pre-encoded", "./www",
  8672. {{"Content-Encoding", "gzip"}});
  8673. svr_.set_mount_point("/", "./www");
  8674. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8675. res.set_file_content("./www/dir/index.html", "text/html");
  8676. });
  8677. svr_.Get("/pre-encoded-file-content",
  8678. [](const Request & /*req*/, Response &res) {
  8679. res.set_header("Content-Encoding", "gzip");
  8680. res.set_file_content("./www/dir/index.html", "text/html");
  8681. });
  8682. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8683. res.set_content_provider(
  8684. 6, "text/plain",
  8685. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8686. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8687. return true;
  8688. });
  8689. });
  8690. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8691. res.set_content_provider(
  8692. 1000, "text/plain",
  8693. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8694. if (offset < 100) {
  8695. std::string data(100, 'A');
  8696. sink.write(data.data(), data.size());
  8697. return true;
  8698. }
  8699. std::this_thread::sleep_for(std::chrono::seconds(2));
  8700. std::string data(900, 'B');
  8701. sink.write(data.data(), data.size());
  8702. return true;
  8703. });
  8704. });
  8705. if (configure) { configure(svr_); }
  8706. auto port = svr_.bind_to_any_port(HOST);
  8707. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8708. svr_.wait_until_ready();
  8709. return port;
  8710. }
  8711. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8712. // Every file under ./www except 1MB.txt is smaller than the default
  8713. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8714. // it out of the way.
  8715. static void enable_without_floor(Server &svr) {
  8716. svr.set_static_file_compression(true);
  8717. svr.set_static_file_compression_min_length(0);
  8718. }
  8719. Server svr_;
  8720. std::thread t_;
  8721. };
  8722. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8723. auto port = start();
  8724. Client cli(HOST, port);
  8725. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8727. EXPECT_EQ(StatusCode::OK_200, res->status);
  8728. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8729. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8730. EXPECT_EQ(1048576U, res->body.size());
  8731. }
  8732. TEST_F(StaticFileCompressionTest, MountPoint) {
  8733. auto port = start(enable);
  8734. Client cli(HOST, port);
  8735. cli.set_decompress(false);
  8736. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8738. EXPECT_EQ(StatusCode::OK_200, res->status);
  8739. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8740. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8741. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8742. // The response stays self-delimiting: a length, not a chunked body.
  8743. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8744. EXPECT_EQ(std::to_string(res->body.size()),
  8745. res->get_header_value("Content-Length"));
  8746. EXPECT_LT(res->body.size(), 1048576U);
  8747. EXPECT_FALSE(res->body.empty());
  8748. }
  8749. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8750. auto port = start(enable);
  8751. Client cli(HOST, port);
  8752. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8754. EXPECT_EQ(StatusCode::OK_200, res->status);
  8755. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8756. EXPECT_EQ(1048576U, res->body.size());
  8757. }
  8758. TEST_F(StaticFileCompressionTest, FileContent) {
  8759. auto port = start(enable_without_floor);
  8760. Client cli(HOST, port);
  8761. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8763. EXPECT_EQ(StatusCode::OK_200, res->status);
  8764. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8765. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8766. EXPECT_EQ(104U, res->body.size());
  8767. }
  8768. // A handler that serves an already-encoded file names the coding itself. The
  8769. // file-backed path decided its coding from Accept-Encoding and the content
  8770. // type alone, so it compressed the stored bytes a second time and appended a
  8771. // second Content-Encoding field line.
  8772. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8773. auto port = start(enable_without_floor);
  8774. Client cli(HOST, port);
  8775. cli.set_decompress(false);
  8776. auto res = cli.Get("/pre-encoded-file-content",
  8777. Headers{{"Accept-Encoding", "gzip"}});
  8778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8779. EXPECT_EQ(StatusCode::OK_200, res->status);
  8780. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8782. // Vary belongs to a coding the server chose, and it chose none here.
  8783. EXPECT_FALSE(res->has_header("Vary"));
  8784. // The file travels exactly as it is stored on disk.
  8785. EXPECT_EQ(104U, res->body.size());
  8786. }
  8787. // The 1MB file clears the default floor, so this one runs the configuration a
  8788. // deployment would actually have.
  8789. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8790. auto port = start(enable);
  8791. Client cli(HOST, port);
  8792. cli.set_decompress(false);
  8793. auto res =
  8794. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8796. EXPECT_EQ(StatusCode::OK_200, res->status);
  8797. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8798. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8799. EXPECT_FALSE(res->has_header("Vary"));
  8800. EXPECT_EQ(1048576U, res->body.size());
  8801. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8802. }
  8803. TEST_F(StaticFileCompressionTest, Head) {
  8804. auto port = start(enable);
  8805. Client cli(HOST, port);
  8806. cli.set_decompress(false);
  8807. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8808. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8809. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8811. EXPECT_EQ(StatusCode::OK_200, res->status);
  8812. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8813. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8814. // HEAD still reports the size a GET would return.
  8815. EXPECT_EQ(get->get_header_value("Content-Length"),
  8816. res->get_header_value("Content-Length"));
  8817. EXPECT_TRUE(res->body.empty());
  8818. }
  8819. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8820. auto port = start(enable);
  8821. Client cli(HOST, port);
  8822. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8823. {"Accept-Encoding", "gzip"}});
  8824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8825. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8826. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8827. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8828. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8829. EXPECT_EQ("cd", res->body);
  8830. }
  8831. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8832. auto port = start(enable);
  8833. Client cli(HOST, port);
  8834. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8836. EXPECT_EQ(StatusCode::OK_200, res->status);
  8837. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8838. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8839. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8840. }
  8841. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8842. auto port = start(enable);
  8843. Client cli(HOST, port);
  8844. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8848. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8849. EXPECT_TRUE(res->body.empty());
  8850. }
  8851. TEST_F(StaticFileCompressionTest, MinLength) {
  8852. auto port = start(enable);
  8853. Client cli(HOST, port);
  8854. // 104 bytes, well under the default floor. Compressing it would add the
  8855. // gzip header and trailer to a body that already fits in one packet.
  8856. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ(StatusCode::OK_200, res->status);
  8859. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8860. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8861. }
  8862. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8863. auto port = start([](Server &svr) {
  8864. svr.set_static_file_compression(true);
  8865. svr.set_static_file_compression_min_length(1);
  8866. });
  8867. Client cli(HOST, port);
  8868. cli.set_decompress(false);
  8869. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8871. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8872. // A 9-byte file comes back larger than it went in, because gzip's header and
  8873. // trailer outweigh anything deflate can save. That is the end of the range
  8874. // the floor exists to keep out.
  8875. EXPECT_GT(res->body.size(), 9U);
  8876. }
  8877. TEST_F(StaticFileCompressionTest, MaxLength) {
  8878. auto port = start([](Server &svr) {
  8879. svr.set_static_file_compression(true);
  8880. svr.set_static_file_compression_min_length(0);
  8881. svr.set_static_file_compression_max_length(1024);
  8882. });
  8883. Client cli(HOST, port);
  8884. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8885. // defines `small` as a macro on Windows.
  8886. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8887. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8888. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8889. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8890. // Under it: compressed.
  8891. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8892. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8893. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8894. }
  8895. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8896. auto port = start(enable_without_floor);
  8897. Client cli(HOST, port);
  8898. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8899. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8900. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8901. auto identity_etag = identity->get_header_value("ETag");
  8902. ASSERT_FALSE(identity_etag.empty());
  8903. auto gzipped =
  8904. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8905. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8906. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8907. auto gzip_etag = gzipped->get_header_value("ETag");
  8908. ASSERT_FALSE(gzip_etag.empty());
  8909. // Two representations, two validators.
  8910. EXPECT_NE(identity_etag, gzip_etag);
  8911. // Each one revalidates against the request that would produce it...
  8912. auto fresh =
  8913. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8914. {"If-None-Match", gzip_etag}});
  8915. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8916. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8917. auto fresh_identity =
  8918. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8919. {"If-None-Match", identity_etag}});
  8920. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8921. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8922. // ...and not against the other representation.
  8923. auto crossed =
  8924. cli.Get("/dir/index.html",
  8925. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8926. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8927. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8928. }
  8929. // The opt-in covers responses the server reads off disk itself. A caller's own
  8930. // known-length provider keeps its Content-Length and, more importantly, keeps
  8931. // delivering incrementally: routing it through a compressor would hold every
  8932. // write back until zlib's window filled.
  8933. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8934. auto port = start(enable);
  8935. Client cli(HOST, port);
  8936. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8938. EXPECT_EQ(StatusCode::OK_200, res->status);
  8939. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8940. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8941. EXPECT_EQ("aaabbb", res->body);
  8942. }
  8943. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8944. auto port = start(enable);
  8945. Client cli(HOST, port);
  8946. cli.set_read_timeout(1, 0);
  8947. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8948. Headers{{"Accept-Encoding", "gzip"}});
  8949. ASSERT_TRUE(handle.is_valid());
  8950. // The provider writes 100 bytes and then stalls for longer than the read
  8951. // timeout. Those first bytes have to arrive anyway: run the response through
  8952. // a compressor and zlib holds them until its window fills, so the read would
  8953. // come back empty instead.
  8954. char buf[256];
  8955. auto n = handle.read(buf, sizeof(buf));
  8956. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8957. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8958. }
  8959. #endif
  8960. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8961. TEST_F(ServerTest, Brotli) {
  8962. Headers headers;
  8963. headers.emplace("Accept-Encoding", "br");
  8964. auto res = cli_.Get("/compress", headers);
  8965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8966. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8967. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8968. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8969. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8970. "7890123456789012345678901234567890",
  8971. res->body);
  8972. EXPECT_EQ(StatusCode::OK_200, res->status);
  8973. }
  8974. #endif
  8975. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8976. TEST_F(ServerTest, Zstd) {
  8977. Headers headers;
  8978. headers.emplace("Accept-Encoding", "zstd");
  8979. auto res = cli_.Get("/compress", headers);
  8980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8981. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8982. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8983. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8984. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8985. "7890123456789012345678901234567890",
  8986. res->body);
  8987. EXPECT_EQ(StatusCode::OK_200, res->status);
  8988. }
  8989. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8990. Headers headers;
  8991. headers.emplace("Accept-Encoding", "");
  8992. auto res = cli_.Get("/compress", headers);
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8996. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8997. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8998. "7890123456789012345678901234567890",
  8999. res->body);
  9000. EXPECT_EQ(StatusCode::OK_200, res->status);
  9001. }
  9002. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9003. Headers headers;
  9004. headers.emplace("Accept-Encoding", "zstd");
  9005. std::string body;
  9006. auto res =
  9007. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9008. EXPECT_EQ(100U, data_length);
  9009. body.append(data, data_length);
  9010. return true;
  9011. });
  9012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9013. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9015. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9016. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9017. "7890123456789012345678901234567890",
  9018. body);
  9019. EXPECT_EQ(StatusCode::OK_200, res->status);
  9020. }
  9021. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9022. Headers headers;
  9023. headers.emplace("Accept-Encoding", "zstd");
  9024. cli_.set_decompress(false);
  9025. auto res = cli_.Get("/compress", headers);
  9026. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9027. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9028. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9029. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9031. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9033. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9034. EXPECT_EQ(StatusCode::OK_200, res->status);
  9035. ASSERT_EQ(26U, res->body.size());
  9036. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9037. 0);
  9038. }
  9039. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9040. Headers headers;
  9041. headers.emplace("Accept-Encoding", "");
  9042. std::string body;
  9043. auto res =
  9044. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9045. EXPECT_EQ(100U, data_length);
  9046. body.append(data, data_length);
  9047. return true;
  9048. });
  9049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9050. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9052. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9053. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9054. "7890123456789012345678901234567890",
  9055. body);
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. }
  9058. TEST_F(ServerTest, NoZstd) {
  9059. Headers headers;
  9060. headers.emplace("Accept-Encoding", "zstd");
  9061. auto res = cli_.Get("/nocompress", headers);
  9062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9063. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9064. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9065. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9066. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9067. "7890123456789012345678901234567890",
  9068. res->body);
  9069. EXPECT_EQ(StatusCode::OK_200, res->status);
  9070. }
  9071. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9072. Headers headers;
  9073. headers.emplace("Accept-Encoding", "zstd");
  9074. std::string body;
  9075. auto res = cli_.Get("/nocompress", headers,
  9076. [&](const char *data, size_t data_length) {
  9077. EXPECT_EQ(100U, data_length);
  9078. body.append(data, data_length);
  9079. return true;
  9080. });
  9081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9082. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9083. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9084. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9085. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9086. "7890123456789012345678901234567890",
  9087. body);
  9088. EXPECT_EQ(StatusCode::OK_200, res->status);
  9089. }
  9090. // TODO: How to enable zstd ??
  9091. TEST_F(ServerTest, MultipartFormDataZstd) {
  9092. UploadFormDataItems items = {
  9093. {"key1", "test", "", ""},
  9094. {"key2", "--abcdefg123", "", ""},
  9095. };
  9096. Headers headers;
  9097. headers.emplace("Accept-Encoding", "zstd");
  9098. cli_.set_compress(true);
  9099. auto res = cli_.Post("/compress-multipart", headers, items);
  9100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9101. EXPECT_EQ(StatusCode::OK_200, res->status);
  9102. }
  9103. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9104. Headers headers;
  9105. headers.emplace("Accept-Encoding", "zstd");
  9106. cli_.set_compress(true);
  9107. auto res = cli_.Put(
  9108. "/put", headers, 3,
  9109. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9110. sink.os << "PUT";
  9111. return true;
  9112. },
  9113. "text/plain");
  9114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9115. EXPECT_EQ(StatusCode::OK_200, res->status);
  9116. EXPECT_EQ("PUT", res->body);
  9117. }
  9118. // Pre-compression logging tests
  9119. TEST_F(ServerTest, PreCompressionLogging) {
  9120. // Test data for compression (matches the actual /compress endpoint content)
  9121. const std::string test_content =
  9122. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9123. "3456789012345678901234567890";
  9124. // Variables to capture logging data
  9125. std::string pre_compression_body;
  9126. std::string pre_compression_content_type;
  9127. std::string pre_compression_content_encoding;
  9128. std::string post_compression_body;
  9129. std::string post_compression_content_type;
  9130. std::string post_compression_content_encoding;
  9131. // Set up pre-compression logger
  9132. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9133. const Response &res) {
  9134. pre_compression_body = res.body;
  9135. pre_compression_content_type = res.get_header_value("Content-Type");
  9136. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9137. });
  9138. // Set up post-compression logger
  9139. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9140. post_compression_body = res.body;
  9141. post_compression_content_type = res.get_header_value("Content-Type");
  9142. post_compression_content_encoding =
  9143. res.get_header_value("Content-Encoding");
  9144. });
  9145. // Test with gzip compression
  9146. Headers headers;
  9147. headers.emplace("Accept-Encoding", "gzip");
  9148. auto res = cli_.Get("/compress", headers);
  9149. // Verify response was compressed
  9150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9151. EXPECT_EQ(StatusCode::OK_200, res->status);
  9152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9153. // Verify pre-compression logger captured uncompressed content
  9154. EXPECT_EQ(test_content, pre_compression_body);
  9155. EXPECT_EQ("text/plain", pre_compression_content_type);
  9156. EXPECT_TRUE(pre_compression_content_encoding
  9157. .empty()); // No encoding header before compression
  9158. // Verify post-compression logger captured compressed content
  9159. EXPECT_NE(test_content,
  9160. post_compression_body); // Should be different after compression
  9161. EXPECT_EQ("text/plain", post_compression_content_type);
  9162. EXPECT_EQ("gzip", post_compression_content_encoding);
  9163. // Verify compressed content is smaller
  9164. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9165. }
  9166. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9167. const std::string test_content =
  9168. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9169. "3456789012345678901234567890";
  9170. std::string pre_compression_body;
  9171. std::string post_compression_body;
  9172. svr_.set_pre_compression_logger(
  9173. [&](const Request & /*req*/, const Response &res) {
  9174. pre_compression_body = res.body;
  9175. });
  9176. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9177. post_compression_body = res.body;
  9178. });
  9179. Headers headers;
  9180. headers.emplace("Accept-Encoding", "br");
  9181. auto res = cli_.Get("/compress", headers);
  9182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9183. EXPECT_EQ(StatusCode::OK_200, res->status);
  9184. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9185. // Verify pre-compression content is uncompressed
  9186. EXPECT_EQ(test_content, pre_compression_body);
  9187. // Verify post-compression content is compressed
  9188. EXPECT_NE(test_content, post_compression_body);
  9189. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9190. }
  9191. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9192. const std::string test_content =
  9193. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9194. "3456789012345678901234567890";
  9195. std::string pre_compression_body;
  9196. std::string post_compression_body;
  9197. svr_.set_pre_compression_logger(
  9198. [&](const Request & /*req*/, const Response &res) {
  9199. pre_compression_body = res.body;
  9200. });
  9201. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9202. post_compression_body = res.body;
  9203. });
  9204. // Request without compression (use /nocompress endpoint)
  9205. Headers headers;
  9206. auto res = cli_.Get("/nocompress", headers);
  9207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9208. EXPECT_EQ(StatusCode::OK_200, res->status);
  9209. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9210. // Pre-compression logger should not be called when no compression is applied
  9211. EXPECT_TRUE(
  9212. pre_compression_body.empty()); // Pre-compression logger not called
  9213. EXPECT_EQ(
  9214. test_content,
  9215. post_compression_body); // Post-compression logger captures final content
  9216. }
  9217. TEST_F(ServerTest, LoggerSeesContentLength) {
  9218. size_t logged_content_length = 0;
  9219. std::string logged_content_length_header;
  9220. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9221. logged_content_length = res.content_length_;
  9222. logged_content_length_header = res.get_header_value("Content-Length");
  9223. });
  9224. auto res = cli_.Get("/nocompress");
  9225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9226. EXPECT_EQ(StatusCode::OK_200, res->status);
  9227. EXPECT_EQ(res->body.size(), logged_content_length);
  9228. EXPECT_EQ(std::to_string(logged_content_length),
  9229. logged_content_length_header);
  9230. }
  9231. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9232. const std::string test_content =
  9233. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9234. "3456789012345678901234567890";
  9235. std::string pre_compression_body;
  9236. bool pre_logger_called = false;
  9237. // Set only pre-compression logger
  9238. svr_.set_pre_compression_logger(
  9239. [&](const Request & /*req*/, const Response &res) {
  9240. pre_compression_body = res.body;
  9241. pre_logger_called = true;
  9242. });
  9243. Headers headers;
  9244. headers.emplace("Accept-Encoding", "gzip");
  9245. auto res = cli_.Get("/compress", headers);
  9246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9247. EXPECT_EQ(StatusCode::OK_200, res->status);
  9248. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9249. // Verify pre-compression logger was called
  9250. EXPECT_TRUE(pre_logger_called);
  9251. EXPECT_EQ(test_content, pre_compression_body);
  9252. }
  9253. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9254. {
  9255. // Test with Expect: 100-continue header - success case
  9256. // Server returns 100 Continue, client sends body, server returns 200 OK
  9257. Request req;
  9258. req.method = "POST";
  9259. req.path = "/post-large";
  9260. req.set_header("Expect", "100-continue");
  9261. req.body = LARGE_DATA;
  9262. Response res;
  9263. auto error = Error::Success;
  9264. cli_.set_keep_alive(true);
  9265. auto ret = cli_.send(req, res, error);
  9266. EXPECT_TRUE(ret);
  9267. EXPECT_EQ(StatusCode::OK_200, res.status);
  9268. EXPECT_EQ(LARGE_DATA, res.body);
  9269. }
  9270. {
  9271. // Test with Expect: 100-continue header - error case
  9272. // Client should not send the body when server returns an error
  9273. Request req;
  9274. req.method = "POST";
  9275. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9276. req.set_header("Expect", "100-continue");
  9277. req.body = LARGE_DATA;
  9278. Response res;
  9279. auto error = Error::Success;
  9280. auto start = std::chrono::high_resolution_clock::now();
  9281. cli_.set_keep_alive(true);
  9282. auto ret = cli_.send(req, res, error);
  9283. auto end = std::chrono::high_resolution_clock::now();
  9284. auto elapsed =
  9285. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9286. .count();
  9287. // With Expect: 100-continue, request completes successfully but with error
  9288. EXPECT_TRUE(ret);
  9289. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9290. EXPECT_EQ("close", res.get_header_value("Connection"));
  9291. EXPECT_FALSE(cli_.is_socket_open());
  9292. EXPECT_LE(elapsed, 2000);
  9293. }
  9294. {
  9295. // Send an extra GET request to ensure error recovery without hanging
  9296. Request req;
  9297. req.method = "GET";
  9298. req.path = "/hi";
  9299. auto start = std::chrono::high_resolution_clock::now();
  9300. auto res = cli_.send(req);
  9301. auto end = std::chrono::high_resolution_clock::now();
  9302. auto elapsed =
  9303. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9304. .count();
  9305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9306. EXPECT_EQ(StatusCode::OK_200, res->status);
  9307. EXPECT_EQ("Hello World!", res->body);
  9308. EXPECT_LE(elapsed, 500);
  9309. }
  9310. }
  9311. TEST(ZstdDecompressor, ChunkedDecompression) {
  9312. std::string data;
  9313. for (size_t i = 0; i < 32 * 1024; ++i) {
  9314. data.push_back(static_cast<char>('a' + i % 26));
  9315. }
  9316. std::string compressed_data;
  9317. {
  9318. httplib::detail::zstd_compressor compressor;
  9319. bool result = compressor.compress(
  9320. data.data(), data.size(),
  9321. /*last=*/true,
  9322. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9323. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9324. compressed_data_size);
  9325. return true;
  9326. });
  9327. ASSERT_TRUE(result);
  9328. }
  9329. std::string decompressed_data;
  9330. {
  9331. httplib::detail::zstd_decompressor decompressor;
  9332. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9333. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9334. size_t chunk_size = 130;
  9335. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9336. chunk_begin += chunk_size) {
  9337. size_t current_chunk_size =
  9338. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9339. bool result = decompressor.decompress(
  9340. compressed_data.data() + chunk_begin, current_chunk_size,
  9341. [&](const char *decompressed_data_chunk,
  9342. size_t decompressed_data_chunk_size) {
  9343. decompressed_data.insert(decompressed_data.size(),
  9344. decompressed_data_chunk,
  9345. decompressed_data_chunk_size);
  9346. return true;
  9347. });
  9348. ASSERT_TRUE(result);
  9349. }
  9350. }
  9351. ASSERT_EQ(data, decompressed_data);
  9352. }
  9353. TEST(ZstdDecompressor, Decompress) {
  9354. std::string original_text = "Compressed with ZSTD";
  9355. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9356. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9357. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9358. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9359. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9360. std::string decompressed_data;
  9361. {
  9362. httplib::detail::zstd_decompressor decompressor;
  9363. bool result = decompressor.decompress(
  9364. compressed_data.data(), compressed_data.size(),
  9365. [&](const char *decompressed_data_chunk,
  9366. size_t decompressed_data_chunk_size) {
  9367. decompressed_data.insert(decompressed_data.size(),
  9368. decompressed_data_chunk,
  9369. decompressed_data_chunk_size);
  9370. return true;
  9371. });
  9372. ASSERT_TRUE(result);
  9373. }
  9374. ASSERT_EQ(original_text, decompressed_data);
  9375. }
  9376. #endif
  9377. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9378. // separate chunks so that the server sees each part in its own read(). Used to
  9379. // place a read boundary at a specific offset of a request body.
  9380. static bool send_request_in_parts(time_t read_timeout_sec,
  9381. const std::vector<std::string> &parts,
  9382. std::string *resp = nullptr,
  9383. int port = PORT) {
  9384. auto error = Error::Success;
  9385. auto client_sock = detail::create_client_socket(
  9386. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9387. /*connection_timeout_sec=*/5, 0,
  9388. /*read_timeout_sec=*/5, 0,
  9389. /*write_timeout_sec=*/5, 0, std::string(), error);
  9390. if (client_sock == INVALID_SOCKET) { return false; }
  9391. auto ret = detail::process_client_socket(
  9392. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9393. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9394. for (size_t i = 0; i < parts.size(); i++) {
  9395. const auto &part = parts[i];
  9396. if (part.size() !=
  9397. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9398. return false;
  9399. }
  9400. if (i + 1 < parts.size()) {
  9401. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9402. }
  9403. }
  9404. char buf[512];
  9405. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9406. while (line_reader.getline()) {
  9407. if (resp) { *resp += line_reader.ptr(); }
  9408. }
  9409. return true;
  9410. });
  9411. detail::close_socket(client_sock);
  9412. return ret;
  9413. }
  9414. // Sends a raw request to a server listening at HOST:PORT.
  9415. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9416. std::string *resp = nullptr, int port = PORT) {
  9417. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9418. }
  9419. #ifdef CPPHTTPLIB_SSL_ENABLED
  9420. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9422. ASSERT_TRUE(svr.is_valid());
  9423. svr.set_read_timeout(1, 0);
  9424. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9425. auto se = detail::scope_exit([&] {
  9426. svr.stop();
  9427. t.join();
  9428. ASSERT_FALSE(svr.is_running());
  9429. });
  9430. svr.wait_until_ready();
  9431. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9432. // keeps each wait well within the read timeout. The server gives up a
  9433. // second in, so the bytes sent after that fail.
  9434. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9435. parts.resize(26, std::string(1, '\0'));
  9436. EXPECT_FALSE(send_request_in_parts(5, parts));
  9437. }
  9438. #endif
  9439. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9440. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9441. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9442. const std::vector<std::string> &parts,
  9443. std::string *resp = nullptr,
  9444. int port = PORT) {
  9445. auto error = Error::Success;
  9446. auto sock = detail::create_client_socket(
  9447. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9448. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9449. /*write_timeout_sec=*/5, 0, std::string(), error);
  9450. if (sock == INVALID_SOCKET) { return false; }
  9451. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9452. auto ctx = SSL_CTX_new(TLS_client_method());
  9453. auto ssl = SSL_new(ctx);
  9454. auto ssl_se = detail::scope_exit([&] {
  9455. SSL_free(ssl);
  9456. SSL_CTX_free(ctx);
  9457. });
  9458. SSL_set_fd(ssl, static_cast<int>(sock));
  9459. if (SSL_connect(ssl) != 1) { return false; }
  9460. for (size_t i = 0; i < parts.size(); i++) {
  9461. const auto &part = parts[i];
  9462. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9463. static_cast<int>(part.size())) {
  9464. return false;
  9465. }
  9466. if (i + 1 < parts.size()) {
  9467. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9468. }
  9469. }
  9470. char buf[512];
  9471. int n;
  9472. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9473. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9474. }
  9475. return true;
  9476. }
  9477. #endif
  9478. // The request line, then a header value a byte at a time.
  9479. static std::vector<std::string> slow_request_head_parts() {
  9480. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9481. parts.resize(26, "a");
  9482. parts.emplace_back("\r\n\r\n");
  9483. return parts;
  9484. }
  9485. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9486. // within the one-second read timeout. The server gives up a second in, before
  9487. // the head is complete.
  9488. static void
  9489. expect_slow_request_head_dropped(Server &svr,
  9490. const std::function<std::string()> &send) {
  9491. std::atomic<bool> handled(false);
  9492. svr.Get("/", [&](const Request &, Response &res) {
  9493. handled = true;
  9494. res.set_content("ok", "text/plain");
  9495. });
  9496. svr.set_read_timeout(1, 0);
  9497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9498. auto se = detail::scope_exit([&] {
  9499. svr.stop();
  9500. t.join();
  9501. ASSERT_FALSE(svr.is_running());
  9502. });
  9503. svr.wait_until_ready();
  9504. auto resp = send();
  9505. EXPECT_FALSE(handled);
  9506. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9507. }
  9508. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9509. Server svr;
  9510. expect_slow_request_head_dropped(svr, [] {
  9511. std::string resp;
  9512. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9513. return resp;
  9514. });
  9515. }
  9516. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9517. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9519. ASSERT_TRUE(svr.is_valid());
  9520. expect_slow_request_head_dropped(svr, [] {
  9521. std::string resp;
  9522. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9523. return resp;
  9524. });
  9525. }
  9526. #endif
  9527. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9528. Server svr;
  9529. std::string header_value;
  9530. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9531. header_value = req.get_header_value("foo");
  9532. res.set_content("ok", "text/plain");
  9533. });
  9534. thread t = thread([&] { svr.listen(HOST, PORT); });
  9535. auto se = detail::scope_exit([&] {
  9536. svr.stop();
  9537. t.join();
  9538. ASSERT_FALSE(svr.is_running());
  9539. });
  9540. svr.wait_until_ready();
  9541. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9542. // like characters are not treated the same - use vertical tab and escape.
  9543. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9544. "foo: \t \v bar \x1B\t \r\n"
  9545. "Connection: close\r\n"
  9546. "\r\n";
  9547. std::string res;
  9548. ASSERT_TRUE(send_request(5, req, &res));
  9549. EXPECT_EQ(header_value, "");
  9550. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9551. }
  9552. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9553. Server svr;
  9554. std::string received;
  9555. svr.Get("/order", [&](const Request &req, Response &res) {
  9556. received = entries_to_string(req.headers);
  9557. res.set_content("ok", "text/plain");
  9558. });
  9559. auto port = svr.bind_to_any_port(HOST);
  9560. thread t = thread([&] { svr.listen_after_bind(); });
  9561. auto se = detail::scope_exit([&] {
  9562. svr.stop();
  9563. t.join();
  9564. ASSERT_FALSE(svr.is_running());
  9565. });
  9566. svr.wait_until_ready();
  9567. const std::string req = "GET /order HTTP/1.1\r\n"
  9568. "Host: localhost\r\n"
  9569. "X-First: 1\r\n"
  9570. "X-Dup: a\r\n"
  9571. "X-Second: 2\r\n"
  9572. "X-Dup: b\r\n"
  9573. "Connection: close\r\n"
  9574. "\r\n";
  9575. std::string res;
  9576. ASSERT_TRUE(send_request(5, req, &res, port));
  9577. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9578. EXPECT_EQ(
  9579. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9580. received);
  9581. }
  9582. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9583. Server svr;
  9584. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9585. res.set_header("Set-Cookie", "first=1");
  9586. res.set_header("X-Between", "y");
  9587. res.set_header("Set-Cookie", "second=2");
  9588. res.set_content("ok", "text/plain");
  9589. });
  9590. auto port = svr.bind_to_any_port(HOST);
  9591. thread t = thread([&] { svr.listen_after_bind(); });
  9592. auto se = detail::scope_exit([&] {
  9593. svr.stop();
  9594. t.join();
  9595. ASSERT_FALSE(svr.is_running());
  9596. });
  9597. svr.wait_until_ready();
  9598. Client cli(HOST, port);
  9599. auto res = cli.Get("/cookies");
  9600. ASSERT_TRUE(res);
  9601. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9602. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9603. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9604. }
  9605. // A stream may send a byte at a time with a small extension on each chunk,
  9606. // however long it runs
  9607. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9608. Server svr;
  9609. svr.Post("/count", [](const Request &req, Response &res) {
  9610. res.set_content(std::to_string(req.body.size()), "text/plain");
  9611. });
  9612. auto port = svr.bind_to_any_port(HOST);
  9613. ASSERT_LT(0, port);
  9614. thread t = thread([&] { svr.listen_after_bind(); });
  9615. auto se = detail::scope_exit([&] {
  9616. svr.stop();
  9617. t.join();
  9618. ASSERT_FALSE(svr.is_running());
  9619. });
  9620. svr.wait_until_ready();
  9621. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9622. "\r\nTransfer-Encoding: chunked\r\n"
  9623. "Connection: close\r\n\r\n";
  9624. for (auto i = 0; i < 4096; i++) {
  9625. req += "1;a=b\r\nx\r\n";
  9626. }
  9627. req += "0\r\n\r\n";
  9628. std::string res;
  9629. ASSERT_TRUE(send_request(5, req, &res, port));
  9630. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9631. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9632. }
  9633. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9634. Server svr;
  9635. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9636. auto i = new int(0);
  9637. res.set_header("Trailer", "X-Safe, X-Reflected");
  9638. res.set_chunked_content_provider(
  9639. "text/plain",
  9640. [i](size_t /*offset*/, DataSink &sink) {
  9641. if (*i == 0) {
  9642. sink.os << "body";
  9643. } else {
  9644. Headers trailer;
  9645. // A valid trailer that must survive.
  9646. trailer.emplace("X-Safe", "safe");
  9647. // Attacker-controlled value carrying CR/LF (response splitting).
  9648. trailer.emplace("X-Reflected",
  9649. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9650. // Attacker-controlled name carrying CR/LF.
  9651. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9652. sink.done_with_trailer(trailer);
  9653. }
  9654. (*i)++;
  9655. return true;
  9656. },
  9657. [i](bool /*success*/) { delete i; });
  9658. });
  9659. thread t = thread([&] { svr.listen(HOST, PORT); });
  9660. auto se = detail::scope_exit([&] {
  9661. svr.stop();
  9662. t.join();
  9663. ASSERT_FALSE(svr.is_running());
  9664. });
  9665. svr.wait_until_ready();
  9666. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9667. "Host: " + HOST +
  9668. "\r\n"
  9669. "Connection: close\r\n"
  9670. "\r\n";
  9671. std::string res;
  9672. ASSERT_TRUE(send_request(5, req, &res));
  9673. // The injected fields must not appear anywhere in the raw response.
  9674. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9675. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9676. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9677. // Invalid trailers are dropped entirely, matching set_header().
  9678. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9679. // The valid trailer still passes through.
  9680. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9681. }
  9682. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9683. // A custom header writer gets only the fields the default one writes
  9684. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9685. std::string s;
  9686. for (const auto &h : hdrs) {
  9687. s += h.first + ": " + h.second + "\r\n";
  9688. }
  9689. s += "\r\n";
  9690. return strm.write(s.data(), s.size());
  9691. };
  9692. for (auto custom_writer : {false, true}) {
  9693. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9694. Server svr;
  9695. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9696. svr.set_post_routing_handler([](const Request &, Response &res) {
  9697. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9698. });
  9699. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9700. // res.headers is a public field an application can populate directly,
  9701. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9702. // A valid header that must survive.
  9703. res.headers.emplace("X-Safe", "safe");
  9704. // Attacker-controlled value carrying CR/LF (response splitting).
  9705. res.headers.emplace("X-Reflected",
  9706. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9707. // Attacker-controlled name carrying CR/LF.
  9708. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9709. res.set_content("body", "text/plain");
  9710. });
  9711. thread t = thread([&] { svr.listen(HOST, PORT); });
  9712. auto se = detail::scope_exit([&] {
  9713. svr.stop();
  9714. t.join();
  9715. ASSERT_FALSE(svr.is_running());
  9716. });
  9717. svr.wait_until_ready();
  9718. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9719. "Host: " + HOST +
  9720. "\r\n"
  9721. "Connection: close\r\n"
  9722. "\r\n";
  9723. std::string res;
  9724. ASSERT_TRUE(send_request(5, req, &res));
  9725. // The injected fields must not appear anywhere in the raw response.
  9726. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9727. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9728. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9729. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9730. // Invalid headers are dropped entirely, matching set_header().
  9731. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9732. // The valid header still passes through.
  9733. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9734. }
  9735. }
  9736. // Forward declaration: in split builds split.py strips `inline` and moves the
  9737. // definition into httplib.cc, so detail::write_request_line is not visible from
  9738. // the public httplib.h. Re-declaring it here lets the tests link against the
  9739. // symbol in both header-only and split builds.
  9740. namespace httplib {
  9741. namespace detail {
  9742. ssize_t write_request_line(Stream &strm, const std::string &method,
  9743. const std::string &path);
  9744. } // namespace detail
  9745. } // namespace httplib
  9746. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9747. // A well-formed target is written verbatim.
  9748. {
  9749. detail::BufferStream strm;
  9750. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9751. EXPECT_GT(n, 0);
  9752. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9753. }
  9754. // A target carrying CR/LF, SP or other control octets must be rejected
  9755. // before anything reaches the wire, otherwise it splits the request line and
  9756. // injects a header or a whole request.
  9757. const std::string evil_targets[] = {
  9758. "/a\r\nInjected: pwned",
  9759. "/a\rInjected",
  9760. "/a\nInjected",
  9761. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9762. "/a b",
  9763. "/a\tb",
  9764. "/a\x7f",
  9765. };
  9766. for (const auto &evil : evil_targets) {
  9767. detail::BufferStream strm;
  9768. auto n = detail::write_request_line(strm, "GET", evil);
  9769. EXPECT_LT(n, 0);
  9770. EXPECT_TRUE(strm.get_buffer().empty());
  9771. }
  9772. }
  9773. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9774. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9775. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9776. // target reaches write_request. The client must fail cleanly with
  9777. // Error::Write instead of putting a request-line-less, header-injecting
  9778. // request on the wire.
  9779. Server svr;
  9780. svr.Get("/a", [](const Request &, Response &res) {
  9781. res.set_content("ok", "text/plain");
  9782. });
  9783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9784. auto se = detail::scope_exit([&] {
  9785. svr.stop();
  9786. thread.join();
  9787. ASSERT_FALSE(svr.is_running());
  9788. });
  9789. svr.wait_until_ready();
  9790. {
  9791. Client cli(HOST, PORT);
  9792. cli.set_path_encode(false);
  9793. // The request is rejected before anything is written, so the connection
  9794. // stays silent and the subsequent response read would otherwise block for
  9795. // the full default read timeout. Shorten it -- the assertion is on the
  9796. // error, not the timeout.
  9797. cli.set_read_timeout(1, 0);
  9798. auto res = cli.Get("/a\r\nInjected: pwned");
  9799. EXPECT_FALSE(res);
  9800. EXPECT_EQ(Error::Write, res.error());
  9801. }
  9802. }
  9803. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9804. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9805. // including extension methods.
  9806. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9807. for (const auto &method : good_methods) {
  9808. detail::BufferStream strm;
  9809. auto n = detail::write_request_line(strm, method, "/");
  9810. EXPECT_GT(n, 0);
  9811. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9812. }
  9813. // A method carrying CR/LF would split the request line and smuggle a whole
  9814. // request ahead of the real one. A space or an empty method corrupts the
  9815. // request line. All must be rejected before anything reaches the wire.
  9816. const std::string evil_methods[] = {
  9817. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9818. "GET\r\nInjected: pwned",
  9819. "GET\r",
  9820. "GET\n",
  9821. "GE T",
  9822. "",
  9823. };
  9824. for (const auto &evil : evil_methods) {
  9825. detail::BufferStream strm;
  9826. auto n = detail::write_request_line(strm, evil, "/");
  9827. EXPECT_LT(n, 0);
  9828. EXPECT_TRUE(strm.get_buffer().empty());
  9829. }
  9830. }
  9831. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9832. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9833. // through Client::send must fail with Error::Write and no request, neither
  9834. // the smuggled one nor the real one, may reach the server.
  9835. Server svr;
  9836. std::atomic<int> request_count(0);
  9837. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9838. request_count++;
  9839. res.status = StatusCode::OK_200;
  9840. return Server::HandlerResponse::Handled;
  9841. });
  9842. auto port = svr.bind_to_any_port(HOST);
  9843. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9844. auto se = detail::scope_exit([&] {
  9845. svr.stop();
  9846. thread.join();
  9847. ASSERT_FALSE(svr.is_running());
  9848. });
  9849. svr.wait_until_ready();
  9850. {
  9851. Client cli(HOST, port);
  9852. const std::string evil_methods[] = {
  9853. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9854. "GE T",
  9855. "",
  9856. };
  9857. for (const auto &evil : evil_methods) {
  9858. Request req;
  9859. req.method = evil;
  9860. req.path = "/";
  9861. auto res = cli.send(req);
  9862. EXPECT_FALSE(res);
  9863. EXPECT_EQ(Error::Write, res.error());
  9864. }
  9865. auto handle =
  9866. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9867. EXPECT_FALSE(handle.is_valid());
  9868. EXPECT_EQ(Error::Write, handle.error);
  9869. // A valid request on the same client still goes through.
  9870. auto res = cli.Get("/");
  9871. ASSERT_TRUE(res);
  9872. EXPECT_EQ(StatusCode::OK_200, res->status);
  9873. }
  9874. EXPECT_EQ(1, request_count.load());
  9875. }
  9876. // Sends a raw request and verifies that there isn't a crash or exception.
  9877. static void test_raw_request(const std::string &req,
  9878. std::string *out = nullptr) {
  9879. Server svr;
  9880. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9881. res.set_content("ok", "text/plain");
  9882. });
  9883. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9884. res.set_content("ok", "text/plain");
  9885. });
  9886. svr.Get("/header_field_value_check",
  9887. [&](const Request & /*req*/, Response &res) {
  9888. res.set_content("ok", "text/plain");
  9889. });
  9890. svr.CustomRoute("PROPFIND", "/dav",
  9891. [&](const Request & /*req*/, Response &res) {
  9892. res.status = StatusCode::MultiStatus_207;
  9893. });
  9894. // Server read timeout must be longer than the client read timeout for the
  9895. // bug to reproduce, probably to force the server to process a request
  9896. // without a trailing blank line.
  9897. const time_t client_read_timeout_sec = 1;
  9898. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9899. bool listen_thread_ok = false;
  9900. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9901. auto se = detail::scope_exit([&] {
  9902. svr.stop();
  9903. t.join();
  9904. ASSERT_FALSE(svr.is_running());
  9905. EXPECT_TRUE(listen_thread_ok);
  9906. });
  9907. svr.wait_until_ready();
  9908. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9909. }
  9910. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9911. // A certain header line causes an exception if the header property is parsed
  9912. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9913. test_raw_request(
  9914. "GET /hi HTTP/1.1\r\n"
  9915. " : "
  9916. " "
  9917. " ");
  9918. }
  9919. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9920. // A certain header line causes an exception if the header property *name* is
  9921. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9922. // greedy matcher and requires backtracking when there are a lot of ":"
  9923. // characters.
  9924. // This occurs with libc++ but not libstdc++.
  9925. test_raw_request(
  9926. "GET /hi HTTP/1.1\r\n"
  9927. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9928. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9929. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9930. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9931. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9932. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9933. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9934. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9935. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9936. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9937. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9938. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9939. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9940. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9941. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9942. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9943. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9944. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9945. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9946. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9947. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9948. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9949. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9950. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9951. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9952. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9953. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9954. "&&&%%%");
  9955. }
  9956. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9957. // Make sure this doesn't crash the server.
  9958. // In a previous version of the header line regex, the "\r" rendered the line
  9959. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9960. // a new position where the leading white space ended and the field value
  9961. // began.
  9962. // The crash occurs with libc++ but not libstdc++.
  9963. test_raw_request("GET /hi HTTP/1.1\r\n"
  9964. "a:" +
  9965. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9966. "\r\n"
  9967. "\r\n");
  9968. }
  9969. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9970. const char *rejected[] = {
  9971. // RFC 9112 §3: one SP between the parts, and nothing else
  9972. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9973. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9974. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9975. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9976. // A request-target has no fragment
  9977. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9978. // An HTTP/1.1 request needs a Host
  9979. "GET /hi HTTP/1.1\r\n\r\n",
  9980. };
  9981. for (auto request : rejected) {
  9982. std::string out;
  9983. test_raw_request(request, &out);
  9984. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9985. }
  9986. std::string out;
  9987. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9988. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9989. }
  9990. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9991. // RFC 9112 §6.1
  9992. const char *requests[] = {
  9993. "PUT /put_hi HTTP/1.1\r\n"
  9994. "Host: localhost\r\n"
  9995. "Content-Length: 0\r\n"
  9996. "Transfer-Encoding: chunked\r\n"
  9997. "\r\n"
  9998. "0\r\n\r\n",
  9999. "PUT /put_hi HTTP/1.0\r\n"
  10000. "Connection: keep-alive\r\n"
  10001. "Transfer-Encoding: chunked\r\n"
  10002. "\r\n"
  10003. "0\r\n\r\n",
  10004. };
  10005. for (auto request : requests) {
  10006. std::string out;
  10007. test_raw_request(request, &out);
  10008. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10009. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10010. }
  10011. }
  10012. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10013. std::string out;
  10014. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10015. "Content-Type: text/plain\r\n"
  10016. "Transfer-Encoding: chunked\r\n"
  10017. "\r\n"
  10018. "nothex\r\n",
  10019. &out);
  10020. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10021. }
  10022. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10023. std::string out;
  10024. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10025. "Content-Type: text/plain\r\n"
  10026. "Transfer-Encoding: chunked\r\n"
  10027. "\r\n"
  10028. "3\r\n"
  10029. "xyz\r\n"
  10030. "NaN\r\n",
  10031. &out);
  10032. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10033. }
  10034. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10035. std::string out;
  10036. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10037. "Content-Type: text/plain\r\n"
  10038. "Transfer-Encoding: chunked\r\n"
  10039. "\r\n"
  10040. // Length is too large for 64 bits.
  10041. "1ffffffffffffffff\r\n"
  10042. "xyz\r\n",
  10043. &out);
  10044. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10045. }
  10046. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10047. test_raw_request("GET /hi HTTP/1.1\r\n"
  10048. "Content-Type: text/plain\r\n\r");
  10049. }
  10050. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10051. std::string out;
  10052. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10053. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10054. }
  10055. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10056. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10057. std::string out;
  10058. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10059. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10060. }
  10061. }
  10062. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10063. std::string out;
  10064. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10065. "Host: localhost\r\n"
  10066. "Connection: close\r\n\r\n",
  10067. &out);
  10068. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10069. }
  10070. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10071. Server svr;
  10072. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10073. EXPECT_TRUE(!req.remote_addr.empty());
  10074. });
  10075. thread t = thread([&] { svr.listen(HOST, PORT); });
  10076. auto se = detail::scope_exit([&] {
  10077. svr.stop();
  10078. t.join();
  10079. ASSERT_FALSE(svr.is_running());
  10080. });
  10081. svr.wait_until_ready();
  10082. // Send an invalid request line to trigger Bad Request
  10083. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10084. std::string out;
  10085. ASSERT_TRUE(send_request(5, bad_req, &out));
  10086. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10087. }
  10088. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10089. // answered right away rather than blocking on a read that waits for EOF.
  10090. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10091. std::string out;
  10092. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10093. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10094. }
  10095. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10096. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10097. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10098. for (const auto *method : methods) {
  10099. Server svr;
  10100. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10101. EXPECT_FALSE(svr.is_valid()) << method;
  10102. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10103. }
  10104. }
  10105. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10106. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10107. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10108. for (const auto *method : methods) {
  10109. Server svr;
  10110. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10111. EXPECT_FALSE(svr.is_valid()) << method;
  10112. }
  10113. }
  10114. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10115. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10116. "COPY", "MOVE", "LOCK",
  10117. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10118. Server svr;
  10119. for (const auto *method : methods) {
  10120. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10121. }
  10122. EXPECT_TRUE(svr.is_valid());
  10123. }
  10124. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10125. Server svr;
  10126. svr.CustomRoute("POST", "/x",
  10127. [](const Request &, Response &, const ContentReader &) {});
  10128. EXPECT_FALSE(svr.is_valid());
  10129. }
  10130. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10131. Server svr;
  10132. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10133. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10134. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10135. EXPECT_FALSE(svr.is_valid());
  10136. }
  10137. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10138. Server svr;
  10139. auto captured = Error::Success;
  10140. svr.set_error_logger(
  10141. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10142. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10143. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10144. }
  10145. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10146. std::string out;
  10147. std::string request(
  10148. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10149. test_raw_request(request, &out);
  10150. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10151. }
  10152. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10153. std::string out;
  10154. std::string request(
  10155. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10156. test_raw_request(request, &out);
  10157. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10158. }
  10159. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10160. std::string out;
  10161. std::string request(
  10162. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10163. test_raw_request(request, &out);
  10164. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10165. }
  10166. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10167. std::string out;
  10168. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10169. "Host: localhost\r\n"
  10170. "Test: \r\n\r\n",
  10171. &out);
  10172. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10173. }
  10174. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10175. Server svr;
  10176. std::string x_custom;
  10177. std::string cookie;
  10178. std::string xff;
  10179. std::string x_unicode;
  10180. std::string x_iis;
  10181. svr.Get("/check", [&](const Request &req, Response &res) {
  10182. x_custom = req.get_header_value("X-Custom");
  10183. cookie = req.get_header_value("Cookie");
  10184. xff = req.get_header_value("X-Forwarded-For");
  10185. x_unicode = req.get_header_value("X-Unicode");
  10186. x_iis = req.get_header_value("X-IIS");
  10187. res.set_content("ok", "text/plain");
  10188. });
  10189. thread t = thread([&] { svr.listen(HOST, PORT); });
  10190. auto se = detail::scope_exit([&] {
  10191. svr.stop();
  10192. t.join();
  10193. ASSERT_FALSE(svr.is_running());
  10194. });
  10195. svr.wait_until_ready();
  10196. const std::string req = "GET /check HTTP/1.1\r\n"
  10197. "Host: localhost\r\n"
  10198. "X-Custom: a%0D%0AInjected: b\r\n"
  10199. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10200. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10201. "X-Unicode: %E3%81%82\r\n"
  10202. "X-IIS: %u00E9\r\n"
  10203. "Connection: close\r\n"
  10204. "\r\n";
  10205. std::string res;
  10206. ASSERT_TRUE(send_request(5, req, &res));
  10207. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10208. // Every value must be returned verbatim (wire form), with no decoding.
  10209. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10210. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10211. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10212. EXPECT_EQ("%E3%81%82", x_unicode);
  10213. EXPECT_EQ("%u00E9", x_iis);
  10214. }
  10215. // Applications that previously relied on automatic percent-decoding can
  10216. // reproduce the old behavior by explicitly calling decode_path_component()
  10217. // or, for RFC 3986 conformance, decode_uri_component().
  10218. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10219. Server svr;
  10220. std::string decoded;
  10221. svr.Get("/check", [&](const Request &req, Response &res) {
  10222. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10223. res.set_content("ok", "text/plain");
  10224. });
  10225. thread t = thread([&] { svr.listen(HOST, PORT); });
  10226. auto se = detail::scope_exit([&] {
  10227. svr.stop();
  10228. t.join();
  10229. ASSERT_FALSE(svr.is_running());
  10230. });
  10231. svr.wait_until_ready();
  10232. const std::string req = "GET /check HTTP/1.1\r\n"
  10233. "Host: localhost\r\n"
  10234. "X-Custom: hello%20world\r\n"
  10235. "Connection: close\r\n"
  10236. "\r\n";
  10237. std::string res;
  10238. ASSERT_TRUE(send_request(5, req, &res));
  10239. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10240. EXPECT_EQ("hello world", decoded);
  10241. }
  10242. // Regression test for #2033. Browsers send Referer values that include
  10243. // percent-encoded characters such as %0A inside the URL. Decoding the
  10244. // header value would either trip the post-decode CR/LF/NUL guard (the
  10245. // original bug, returning 400) or, after that guard was relaxed, silently
  10246. // store a literal LF — both unacceptable. The wire form must round-trip.
  10247. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10248. Server svr;
  10249. std::string referer;
  10250. svr.Get("/check", [&](const Request &req, Response &res) {
  10251. referer = req.get_header_value("Referer");
  10252. res.set_content("ok", "text/plain");
  10253. });
  10254. thread t = thread([&] { svr.listen(HOST, PORT); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. t.join();
  10258. ASSERT_FALSE(svr.is_running());
  10259. });
  10260. svr.wait_until_ready();
  10261. const std::string req = "GET /check HTTP/1.1\r\n"
  10262. "Host: localhost\r\n"
  10263. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10264. "Connection: close\r\n"
  10265. "\r\n";
  10266. std::string res;
  10267. ASSERT_TRUE(send_request(5, req, &res));
  10268. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10269. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10270. }
  10271. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10272. Server svr;
  10273. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10274. res.set_header("Cache-Control", "no-cache");
  10275. res.set_chunked_content_provider(
  10276. "text/event-stream", [](size_t offset, DataSink &sink) {
  10277. std::string s = "data:";
  10278. s += std::to_string(offset);
  10279. s += "\n\n";
  10280. auto ret = sink.write(s.data(), s.size());
  10281. EXPECT_TRUE(ret);
  10282. std::this_thread::sleep_for(std::chrono::seconds(1));
  10283. return true;
  10284. });
  10285. });
  10286. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10287. svr.wait_until_ready();
  10288. Client client(HOST, PORT);
  10289. const Headers headers = {{"Accept", "text/event-stream"}};
  10290. auto get_thread = std::thread([&client, &headers]() {
  10291. auto res = client.Get(
  10292. "/events", headers,
  10293. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10294. });
  10295. auto se = detail::scope_exit([&] {
  10296. svr.stop();
  10297. get_thread.join();
  10298. listen_thread.join();
  10299. ASSERT_FALSE(svr.is_running());
  10300. });
  10301. // Give GET time to get a few messages.
  10302. std::this_thread::sleep_for(std::chrono::seconds(2));
  10303. }
  10304. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10305. httplib::Server svr;
  10306. svr.Post("/hi",
  10307. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10308. res.status = StatusCode::OK_200;
  10309. });
  10310. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10311. svr.wait_until_ready();
  10312. Client cli(HOST, PORT);
  10313. auto res = cli.Post("/hi", "data", "text/plain");
  10314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10315. EXPECT_EQ(StatusCode::OK_200, res->status);
  10316. svr.stop();
  10317. thread.join();
  10318. ASSERT_FALSE(svr.is_running());
  10319. res = cli.Post("/hi", "data", "text/plain");
  10320. ASSERT_FALSE(res);
  10321. }
  10322. TEST(ServerStopTest, ListenFailure) {
  10323. Server svr;
  10324. auto t = thread([&]() {
  10325. auto ret = svr.listen("????", PORT);
  10326. EXPECT_FALSE(ret);
  10327. });
  10328. svr.wait_until_ready();
  10329. svr.stop();
  10330. t.join();
  10331. }
  10332. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10333. TEST(ServerStopTest, Decommision) {
  10334. Server svr;
  10335. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10336. for (int i = 0; i < 4; i++) {
  10337. auto is_even = !(i % 2);
  10338. std::thread t{[&] {
  10339. try {
  10340. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10341. if (is_even) {
  10342. throw std::runtime_error("Some thing that happens to go wrong.");
  10343. }
  10344. svr.listen(HOST, PORT);
  10345. } catch (...) { svr.decommission(); }
  10346. }};
  10347. svr.wait_until_ready();
  10348. // Server is up
  10349. {
  10350. Client cli(HOST, PORT);
  10351. auto res = cli.Get("/hi");
  10352. if (is_even) {
  10353. EXPECT_FALSE(res);
  10354. } else {
  10355. EXPECT_TRUE(res);
  10356. EXPECT_EQ("hi...", res->body);
  10357. }
  10358. }
  10359. svr.stop();
  10360. t.join();
  10361. // Server is down...
  10362. {
  10363. Client cli(HOST, PORT);
  10364. auto res = cli.Get("/hi");
  10365. EXPECT_FALSE(res);
  10366. }
  10367. }
  10368. }
  10369. #endif
  10370. // Helper function for string body upload progress tests
  10371. template <typename SetupHandler, typename ClientCall>
  10372. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10373. ClientCall &&client_call,
  10374. const string &body) {
  10375. Server svr;
  10376. setup_handler(svr);
  10377. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. t.join();
  10381. });
  10382. svr.wait_until_ready();
  10383. Client cli(HOST, PORT);
  10384. vector<uint64_t> progress_values;
  10385. bool progress_called = false;
  10386. auto res =
  10387. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10388. progress_values.push_back(current);
  10389. progress_called = true;
  10390. return true;
  10391. });
  10392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10393. EXPECT_EQ(200, res->status);
  10394. EXPECT_TRUE(progress_called);
  10395. }
  10396. TEST(UploadProgressTest, PostStringBodyBasic) {
  10397. TestStringBodyUploadProgress(
  10398. [](Server &svr) {
  10399. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10400. res.set_content("received", "text/plain");
  10401. });
  10402. },
  10403. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10404. return cli.Post("/test", body, "text/plain", progress_callback);
  10405. },
  10406. "test data for upload progress");
  10407. }
  10408. TEST(UploadProgressTest, PutStringBodyBasic) {
  10409. TestStringBodyUploadProgress(
  10410. [](Server &svr) {
  10411. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10412. res.set_content("put received", "text/plain");
  10413. });
  10414. },
  10415. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10416. return cli.Put("/test", body, "text/plain", progress_callback);
  10417. },
  10418. "put test data for upload progress");
  10419. }
  10420. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10421. TestStringBodyUploadProgress(
  10422. [](Server &svr) {
  10423. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10424. res.set_content("patch received", "text/plain");
  10425. });
  10426. },
  10427. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10428. return cli.Patch("/test", body, "text/plain", progress_callback);
  10429. },
  10430. "patch test data for upload progress");
  10431. }
  10432. // Helper function for content provider upload progress tests
  10433. template <typename SetupHandler, typename ClientCall>
  10434. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10435. ClientCall &&client_call) {
  10436. Server svr;
  10437. setup_handler(svr);
  10438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10439. auto se = detail::scope_exit([&] {
  10440. svr.stop();
  10441. t.join();
  10442. });
  10443. svr.wait_until_ready();
  10444. Client cli(HOST, PORT);
  10445. vector<uint64_t> progress_values;
  10446. auto res =
  10447. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10448. progress_values.push_back(current);
  10449. return true;
  10450. });
  10451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10452. EXPECT_EQ(200, res->status);
  10453. EXPECT_FALSE(progress_values.empty());
  10454. }
  10455. TEST(UploadProgressTest, PostContentProviderProgress) {
  10456. TestContentProviderUploadProgress(
  10457. [](Server &svr) {
  10458. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10459. res.set_content("provider received", "text/plain");
  10460. });
  10461. },
  10462. [](Client &cli, UploadProgress progress_callback) {
  10463. return cli.Post(
  10464. "/test", 9,
  10465. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10466. sink.os << "test data";
  10467. return true;
  10468. },
  10469. "text/plain", progress_callback);
  10470. });
  10471. }
  10472. // Helper function for multipart upload progress tests
  10473. template <typename SetupHandler, typename ClientCall>
  10474. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10475. ClientCall &&client_call,
  10476. const string &endpoint) {
  10477. Server svr;
  10478. setup_handler(svr);
  10479. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10480. auto se = detail::scope_exit([&] {
  10481. svr.stop();
  10482. t.join();
  10483. });
  10484. svr.wait_until_ready();
  10485. Client cli(HOST, PORT);
  10486. vector<uint64_t> progress_values;
  10487. UploadFormDataItems items = {
  10488. {"field1", "value1", "", ""},
  10489. {"field2", "longer value for progress tracking test", "", ""},
  10490. {"file1", "file content data for upload progress", "test.txt",
  10491. "text/plain"}};
  10492. auto res = client_call(cli, endpoint, items,
  10493. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10494. progress_values.push_back(current);
  10495. return true;
  10496. });
  10497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10498. EXPECT_EQ(200, res->status);
  10499. EXPECT_FALSE(progress_values.empty());
  10500. }
  10501. TEST(UploadProgressTest, PostMultipartProgress) {
  10502. TestMultipartUploadProgress(
  10503. [](Server &svr) {
  10504. svr.Post("/multipart", [](const Request &req, Response &res) {
  10505. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10506. res.set_content("multipart received", "text/plain");
  10507. });
  10508. },
  10509. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10510. UploadProgress progress_callback) {
  10511. return cli.Post(endpoint, items, progress_callback);
  10512. },
  10513. "/multipart");
  10514. }
  10515. // Helper function for basic download progress tests
  10516. template <typename SetupHandler, typename ClientCall>
  10517. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10518. ClientCall &&client_call, const string &endpoint,
  10519. size_t expected_content_size) {
  10520. Server svr;
  10521. setup_handler(svr);
  10522. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10523. auto se = detail::scope_exit([&] {
  10524. svr.stop();
  10525. t.join();
  10526. });
  10527. svr.wait_until_ready();
  10528. Client cli(HOST, PORT);
  10529. vector<uint64_t> progress_values;
  10530. auto res = client_call(cli, endpoint,
  10531. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10532. progress_values.push_back(current);
  10533. return true;
  10534. });
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(200, res->status);
  10537. EXPECT_FALSE(progress_values.empty());
  10538. EXPECT_EQ(expected_content_size, res->body.size());
  10539. }
  10540. TEST(DownloadProgressTest, GetBasic) {
  10541. TestBasicDownloadProgress(
  10542. [](Server &svr) {
  10543. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10544. string content(1000, 'D');
  10545. res.set_content(content, "text/plain");
  10546. });
  10547. },
  10548. [](Client &cli, const string &endpoint,
  10549. DownloadProgress progress_callback) {
  10550. return cli.Get(endpoint, progress_callback);
  10551. },
  10552. "/download", 1000u);
  10553. }
  10554. // Helper function for content receiver download progress tests
  10555. template <typename SetupHandler, typename ClientCall>
  10556. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10557. ClientCall &&client_call,
  10558. const string &endpoint,
  10559. size_t expected_content_size) {
  10560. Server svr;
  10561. setup_handler(svr);
  10562. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10563. auto se = detail::scope_exit([&] {
  10564. svr.stop();
  10565. t.join();
  10566. });
  10567. svr.wait_until_ready();
  10568. Client cli(HOST, PORT);
  10569. vector<uint64_t> progress_values;
  10570. string received_body;
  10571. auto res = client_call(
  10572. cli, endpoint,
  10573. [&](const char *data, size_t data_length) -> bool {
  10574. received_body.append(data, data_length);
  10575. return true;
  10576. },
  10577. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10578. progress_values.push_back(current);
  10579. return true;
  10580. });
  10581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10582. EXPECT_EQ(200, res->status);
  10583. EXPECT_FALSE(progress_values.empty());
  10584. EXPECT_EQ(expected_content_size, received_body.size());
  10585. EXPECT_TRUE(res->body.empty());
  10586. }
  10587. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10588. TestContentReceiverDownloadProgress(
  10589. [](Server &svr) {
  10590. svr.Get("/download-receiver",
  10591. [](const Request & /*req*/, Response &res) {
  10592. string content(2000, 'R');
  10593. res.set_content(content, "text/plain");
  10594. });
  10595. },
  10596. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10597. DownloadProgress progress_callback) {
  10598. return cli.Get(endpoint, content_receiver, progress_callback);
  10599. },
  10600. "/download-receiver", 2000u);
  10601. }
  10602. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10603. // A provider reaching a pass with nothing to hand over - an empty buffer
  10604. // popped off a queue, say - must not be taken to mean the body is finished.
  10605. // It used to end the loop with the terminating chunk unwritten while the
  10606. // server still considered the response complete, so the peer waited for an
  10607. // end that never arrived.
  10608. Server svr;
  10609. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10610. auto step = std::make_shared<int>(0);
  10611. res.set_chunked_content_provider("text/plain",
  10612. [step](size_t /*offset*/, DataSink &sink) {
  10613. switch ((*step)++) {
  10614. case 0: sink.write("", 0); break;
  10615. case 1: sink.write("hello", 5); break;
  10616. default: sink.done(); break;
  10617. }
  10618. return true;
  10619. });
  10620. });
  10621. auto port = svr.bind_to_any_port(HOST);
  10622. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10623. auto listen_se = detail::scope_exit([&] {
  10624. svr.stop();
  10625. listen_thread.join();
  10626. ASSERT_FALSE(svr.is_running());
  10627. });
  10628. svr.wait_until_ready();
  10629. Client cli(HOST, port);
  10630. // Without the fix the body is never terminated, so bound the wait rather
  10631. // than letting the test hang on the default read timeout.
  10632. cli.set_read_timeout(5, 0);
  10633. auto res = cli.Get("/stream");
  10634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10635. EXPECT_EQ(StatusCode::OK_200, res->status);
  10636. EXPECT_EQ("hello", res->body);
  10637. }
  10638. TEST(StreamingTest, NoContentLengthStreaming) {
  10639. Server svr;
  10640. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10641. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10642. if (offset < 6) {
  10643. sink.os << (offset < 3 ? "a" : "b");
  10644. } else {
  10645. sink.done();
  10646. }
  10647. return true;
  10648. });
  10649. });
  10650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10651. auto listen_se = detail::scope_exit([&] {
  10652. svr.stop();
  10653. listen_thread.join();
  10654. ASSERT_FALSE(svr.is_running());
  10655. });
  10656. svr.wait_until_ready();
  10657. Client client(HOST, PORT);
  10658. auto get_thread = std::thread([&client]() {
  10659. std::string s;
  10660. auto res =
  10661. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10662. s += std::string(data, len);
  10663. return true;
  10664. });
  10665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10666. EXPECT_EQ(StatusCode::OK_200, res->status);
  10667. EXPECT_EQ("aaabbb", s);
  10668. });
  10669. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10670. // Give GET time to get a few messages.
  10671. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10672. }
  10673. TEST(MountTest, Unmount) {
  10674. Server svr;
  10675. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10676. auto se = detail::scope_exit([&] {
  10677. svr.stop();
  10678. listen_thread.join();
  10679. ASSERT_FALSE(svr.is_running());
  10680. });
  10681. svr.wait_until_ready();
  10682. Client cli("localhost", PORT);
  10683. svr.set_mount_point("/mount2", "./www2");
  10684. auto res = cli.Get("/");
  10685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10686. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10687. res = cli.Get("/mount2/dir/test.html");
  10688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10689. EXPECT_EQ(StatusCode::OK_200, res->status);
  10690. svr.set_mount_point("/", "./www");
  10691. res = cli.Get("/dir/");
  10692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10693. EXPECT_EQ(StatusCode::OK_200, res->status);
  10694. svr.remove_mount_point("/");
  10695. res = cli.Get("/dir/");
  10696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10697. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10698. svr.remove_mount_point("/mount2");
  10699. res = cli.Get("/mount2/dir/test.html");
  10700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10701. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10702. }
  10703. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10704. Server svr;
  10705. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10706. svr.Get("/api/hello", [](const Request &, Response &res) {
  10707. res.set_content("api", "text/plain");
  10708. });
  10709. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10710. auto se = detail::scope_exit([&] {
  10711. svr.stop();
  10712. listen_thread.join();
  10713. ASSERT_FALSE(svr.is_running());
  10714. });
  10715. svr.wait_until_ready();
  10716. Client cli(HOST, PORT);
  10717. auto res = cli.Get("/dir/test.html");
  10718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10719. EXPECT_EQ(StatusCode::OK_200, res->status);
  10720. res = cli.Get("/api/hello");
  10721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10722. EXPECT_EQ(StatusCode::OK_200, res->status);
  10723. EXPECT_EQ("api", res->body);
  10724. }
  10725. TEST(MountTest, PathSegmentBoundary) {
  10726. Server svr;
  10727. svr.set_mount_point("/mount2", "./www2");
  10728. svr.set_mount_point("/", "./www");
  10729. auto port = svr.bind_to_any_port(HOST);
  10730. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10731. auto se = detail::scope_exit([&] {
  10732. svr.stop();
  10733. listen_thread.join();
  10734. ASSERT_FALSE(svr.is_running());
  10735. });
  10736. svr.wait_until_ready();
  10737. Client cli(HOST, port);
  10738. auto res = cli.Get("/mount2/dir/test.html");
  10739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10740. EXPECT_EQ(StatusCode::OK_200, res->status);
  10741. // "/mount2" must not match part-way through a path segment.
  10742. res = cli.Get("/mount2dir/test.html");
  10743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10745. // A mount point ending in '/' keeps matching every path below it.
  10746. res = cli.Get("/dir/test.html");
  10747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10748. EXPECT_EQ(StatusCode::OK_200, res->status);
  10749. }
  10750. TEST(MountTest, Redicect) {
  10751. Server svr;
  10752. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10753. auto se = detail::scope_exit([&] {
  10754. svr.stop();
  10755. listen_thread.join();
  10756. ASSERT_FALSE(svr.is_running());
  10757. });
  10758. svr.set_mount_point("/", "./www");
  10759. svr.wait_until_ready();
  10760. Client cli("localhost", PORT);
  10761. auto res = cli.Get("/dir/");
  10762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10763. EXPECT_EQ(StatusCode::OK_200, res->status);
  10764. res = cli.Get("/dir");
  10765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10766. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10767. res = cli.Get("/file");
  10768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10769. EXPECT_EQ(StatusCode::OK_200, res->status);
  10770. res = cli.Get("/file/");
  10771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10773. cli.set_follow_location(true);
  10774. res = cli.Get("/dir");
  10775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10776. EXPECT_EQ(StatusCode::OK_200, res->status);
  10777. }
  10778. TEST(MountTest, MultibytesPathName) {
  10779. Server svr;
  10780. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10781. auto se = detail::scope_exit([&] {
  10782. svr.stop();
  10783. listen_thread.join();
  10784. ASSERT_FALSE(svr.is_running());
  10785. });
  10786. svr.set_mount_point("/", "./www");
  10787. svr.wait_until_ready();
  10788. Client cli("localhost", PORT);
  10789. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10791. EXPECT_EQ(StatusCode::OK_200, res->status);
  10792. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10793. }
  10794. // A mount point serves no path with an empty segment or one ending in '.' or
  10795. // a space, so a guard in the pre-routing handler sees the path of every file
  10796. // that is served
  10797. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10798. Server svr;
  10799. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10800. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10801. if (req.path == "/dir/test.html") {
  10802. res.status = StatusCode::Unauthorized_401;
  10803. return Server::HandlerResponse::Handled;
  10804. }
  10805. return Server::HandlerResponse::Unhandled;
  10806. });
  10807. auto port = svr.bind_to_any_port(HOST);
  10808. ASSERT_LT(0, port);
  10809. thread t = thread([&] { svr.listen_after_bind(); });
  10810. auto se = detail::scope_exit([&] {
  10811. svr.stop();
  10812. t.join();
  10813. ASSERT_FALSE(svr.is_running());
  10814. });
  10815. svr.wait_until_ready();
  10816. Client cli(HOST, port);
  10817. for (auto path :
  10818. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10819. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10820. "/dir/test.html.", "/dir/test.html%20"}) {
  10821. SCOPED_TRACE(path);
  10822. auto res = cli.Get(path);
  10823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10824. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10825. }
  10826. }
  10827. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10828. Server svr;
  10829. svr.set_mount_point("/", "./www");
  10830. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10831. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10832. auto port = svr.bind_to_any_port(HOST);
  10833. ASSERT_GT(port, 0);
  10834. thread t = thread([&] { svr.listen_after_bind(); });
  10835. auto se = detail::scope_exit([&] {
  10836. svr.stop();
  10837. t.join();
  10838. ASSERT_FALSE(svr.is_running());
  10839. });
  10840. svr.wait_until_ready();
  10841. Client cli(HOST, port);
  10842. auto res = cli.Get("/dir/test.abcde");
  10843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10844. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10845. res = cli.Get("/dir/test.html");
  10846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10847. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10848. }
  10849. #ifdef _WIN32
  10850. // Issue #2435: mmap::open() must succeed even when another handle holds
  10851. // the file open for writing (e.g. an active log file).
  10852. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10853. const char *path = "mmap_concurrent_writer_test.txt";
  10854. const char *content = "hello";
  10855. {
  10856. std::ofstream f(path, std::ios::binary);
  10857. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10858. }
  10859. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10860. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10861. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10862. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10863. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10864. detail::mmap m(path);
  10865. ASSERT_TRUE(m.is_open());
  10866. EXPECT_EQ(strlen(content), m.size());
  10867. char buf[8];
  10868. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10869. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10870. }
  10871. #endif
  10872. #ifndef _WIN32
  10873. // A directory or a device has no size to serve.
  10874. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10875. const char *path = "./mmap_not_regular_test_dir";
  10876. ASSERT_EQ(0, ::mkdir(path, 0755));
  10877. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10878. for (auto p : {path, "/dev/null"}) {
  10879. detail::mmap m(p);
  10880. EXPECT_FALSE(m.is_open()) << p;
  10881. EXPECT_EQ(0U, m.size()) << p;
  10882. }
  10883. Server svr;
  10884. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10885. res.set_file_content("/dev/null");
  10886. });
  10887. auto port = svr.bind_to_any_port(HOST);
  10888. thread t = thread([&] { svr.listen_after_bind(); });
  10889. auto se = detail::scope_exit([&] {
  10890. svr.stop();
  10891. t.join();
  10892. });
  10893. svr.wait_until_ready();
  10894. auto res = Client(HOST, port).Get("/null");
  10895. ASSERT_TRUE(res);
  10896. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10897. }
  10898. #endif
  10899. #ifdef __linux__
  10900. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10901. TEST(MmapTest, FileIsNotMapped) {
  10902. const char *path = "mmap_not_mapped_test.txt";
  10903. {
  10904. std::ofstream f(path, std::ios::binary);
  10905. f << "hello";
  10906. }
  10907. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10908. detail::mmap m(path);
  10909. ASSERT_TRUE(m.is_open());
  10910. std::ifstream maps("/proc/self/maps");
  10911. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10912. std::istreambuf_iterator<char>());
  10913. EXPECT_EQ(std::string::npos, mappings.find(path));
  10914. }
  10915. #endif
  10916. TEST(KeepAliveTest, ReadTimeout) {
  10917. Server svr;
  10918. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10919. std::this_thread::sleep_for(std::chrono::seconds(2));
  10920. res.set_content("a", "text/plain");
  10921. });
  10922. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10923. res.set_content("b", "text/plain");
  10924. });
  10925. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10926. auto se = detail::scope_exit([&] {
  10927. svr.stop();
  10928. listen_thread.join();
  10929. ASSERT_FALSE(svr.is_running());
  10930. });
  10931. svr.wait_until_ready();
  10932. Client cli("localhost", PORT);
  10933. cli.set_keep_alive(true);
  10934. cli.set_read_timeout(std::chrono::seconds(1));
  10935. auto resa = cli.Get("/a");
  10936. ASSERT_FALSE(resa);
  10937. EXPECT_EQ(Error::Read, resa.error());
  10938. auto resb = cli.Get("/b");
  10939. ASSERT_TRUE(resb);
  10940. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10941. EXPECT_EQ("b", resb->body);
  10942. }
  10943. TEST(KeepAliveTest, MaxCount) {
  10944. size_t keep_alive_max_count = 3;
  10945. Server svr;
  10946. svr.set_keep_alive_max_count(keep_alive_max_count);
  10947. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10948. res.set_content("Hello World!", "text/plain");
  10949. });
  10950. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10951. auto se = detail::scope_exit([&] {
  10952. svr.stop();
  10953. listen_thread.join();
  10954. ASSERT_FALSE(svr.is_running());
  10955. });
  10956. svr.wait_until_ready();
  10957. Client cli(HOST, PORT);
  10958. cli.set_keep_alive(true);
  10959. for (size_t i = 0; i < 5; i++) {
  10960. auto result = cli.Get("/hi");
  10961. ASSERT_TRUE(result);
  10962. EXPECT_EQ(StatusCode::OK_200, result->status);
  10963. if (i == keep_alive_max_count - 1) {
  10964. EXPECT_EQ("close", result->get_header_value("Connection"));
  10965. } else {
  10966. EXPECT_FALSE(result->has_header("Connection"));
  10967. }
  10968. }
  10969. }
  10970. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10971. // can pull the next one into the server's buffer. The server must serve it
  10972. // without waiting for the socket to become readable again. The keep-alive
  10973. // timeout outlasts the client's read timeout, so a request left waiting for it
  10974. // shows up as a missing response.
  10975. static void serve_pipelining_routes(Server &svr,
  10976. const std::function<void(int)> &client) {
  10977. svr.set_keep_alive_timeout(5);
  10978. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10979. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10980. });
  10981. svr.Post("/echo", [](const Request &req, Response &res) {
  10982. res.set_content("echo " + req.body, "text/plain");
  10983. });
  10984. auto port = svr.bind_to_any_port(HOST);
  10985. thread t = thread([&] { svr.listen_after_bind(); });
  10986. auto se = detail::scope_exit([&] {
  10987. svr.stop();
  10988. t.join();
  10989. });
  10990. svr.wait_until_ready();
  10991. client(port);
  10992. }
  10993. static std::string
  10994. send_pipelined_requests(const std::vector<std::string> &parts) {
  10995. Server svr;
  10996. std::string res;
  10997. serve_pipelining_routes(svr, [&](int port) {
  10998. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10999. });
  11000. return res;
  11001. }
  11002. static void expect_in_order(const std::string &res,
  11003. const std::vector<std::string> &bodies) {
  11004. size_t pos = 0;
  11005. for (const auto &body : bodies) {
  11006. pos = res.find(body, pos);
  11007. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11008. pos += body.size();
  11009. }
  11010. }
  11011. TEST(KeepAliveTest, PipelinedRequests) {
  11012. auto res = send_pipelined_requests(
  11013. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11014. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11015. "Content-Length: 4\r\n\r\nbody"
  11016. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11017. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11018. }
  11019. // The second request starts in the server's buffer and ends on the socket.
  11020. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11021. auto res =
  11022. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11023. "GET /hi/2 HTTP/1.1\r\nHo",
  11024. "st: localhost\r\nConnection: close\r\n\r\n"});
  11025. expect_in_order(res, {"hi 1", "hi 2"});
  11026. }
  11027. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11028. // CRLF after a body does not turn into a 400 for the next request.
  11029. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11030. auto res = send_pipelined_requests(
  11031. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11032. "Content-Length: 4\r\n\r\nbody\r\n"
  11033. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11034. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11035. expect_in_order(res, {"echo body", "hi 2"});
  11036. }
  11037. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11038. // must not be served as the next request.
  11039. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11040. auto res = send_pipelined_requests(
  11041. {"INVALID REQUEST LINE\r\n\r\n"
  11042. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11043. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11044. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11045. }
  11046. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11047. // Over TLS, the next request is held by the TLS library as already decrypted
  11048. // data rather than on the socket.
  11049. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11051. std::string res;
  11052. serve_pipelining_routes(svr, [&](int port) {
  11053. // One part, so all three requests arrive in one TLS record
  11054. EXPECT_TRUE(send_ssl_request_in_parts(
  11055. 2,
  11056. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11057. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11058. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11059. &res, port));
  11060. });
  11061. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11062. }
  11063. #endif
  11064. TEST(KeepAliveTest, Issue1041) {
  11065. Server svr;
  11066. svr.set_keep_alive_timeout(3);
  11067. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11068. res.set_content("Hello World!", "text/plain");
  11069. });
  11070. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11071. auto se = detail::scope_exit([&] {
  11072. svr.stop();
  11073. listen_thread.join();
  11074. ASSERT_FALSE(svr.is_running());
  11075. });
  11076. svr.wait_until_ready();
  11077. Client cli(HOST, PORT);
  11078. cli.set_keep_alive(true);
  11079. auto result = cli.Get("/hi");
  11080. ASSERT_TRUE(result);
  11081. EXPECT_EQ(StatusCode::OK_200, result->status);
  11082. std::this_thread::sleep_for(std::chrono::seconds(5));
  11083. result = cli.Get("/hi");
  11084. ASSERT_TRUE(result);
  11085. EXPECT_EQ(StatusCode::OK_200, result->status);
  11086. }
  11087. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11088. Server svr;
  11089. svr.set_keep_alive_max_count(0);
  11090. std::set<int> remote_ports;
  11091. svr.Get("/hi", [&](const Request &req, Response &res) {
  11092. remote_ports.insert(req.remote_port);
  11093. res.set_content("hi", "text/plain");
  11094. });
  11095. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11096. auto se = detail::scope_exit([&] {
  11097. svr.stop();
  11098. listen_thread.join();
  11099. ASSERT_FALSE(svr.is_running());
  11100. });
  11101. svr.wait_until_ready();
  11102. Client cli(HOST, PORT);
  11103. cli.set_keep_alive(true);
  11104. for (int i = 0; i < 3; i++) {
  11105. auto res = cli.Get("/hi");
  11106. ASSERT_TRUE(res);
  11107. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11108. }
  11109. // All three over one connection
  11110. EXPECT_EQ(1u, remote_ports.size());
  11111. }
  11112. TEST(KeepAliveTest, Issue1959) {
  11113. Server svr;
  11114. svr.set_keep_alive_timeout(5);
  11115. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11116. res.set_content("a", "text/plain");
  11117. });
  11118. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11119. auto se = detail::scope_exit([&] {
  11120. if (!svr.is_running()) return;
  11121. svr.stop();
  11122. listen_thread.join();
  11123. ASSERT_FALSE(svr.is_running());
  11124. });
  11125. svr.wait_until_ready();
  11126. Client cli("localhost", PORT);
  11127. cli.set_keep_alive(true);
  11128. using namespace std::chrono;
  11129. auto start = steady_clock::now();
  11130. cli.Get("/a");
  11131. svr.stop();
  11132. listen_thread.join();
  11133. auto end = steady_clock::now();
  11134. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11135. EXPECT_LT(elapsed, 5000);
  11136. }
  11137. #ifdef CPPHTTPLIB_SSL_ENABLED
  11138. TEST(KeepAliveTest, SSLClientReconnection) {
  11139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11140. ASSERT_TRUE(svr.is_valid());
  11141. svr.set_keep_alive_timeout(1);
  11142. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11143. res.set_content("Hello World!", "text/plain");
  11144. });
  11145. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11146. auto se = detail::scope_exit([&] {
  11147. svr.stop();
  11148. listen_thread.join();
  11149. ASSERT_FALSE(svr.is_running());
  11150. });
  11151. svr.wait_until_ready();
  11152. SSLClient cli(HOST, PORT);
  11153. cli.enable_server_certificate_verification(false);
  11154. cli.set_keep_alive(true);
  11155. auto result = cli.Get("/hi");
  11156. ASSERT_TRUE(result);
  11157. EXPECT_EQ(StatusCode::OK_200, result->status);
  11158. result = cli.Get("/hi");
  11159. ASSERT_TRUE(result);
  11160. EXPECT_EQ(StatusCode::OK_200, result->status);
  11161. std::this_thread::sleep_for(std::chrono::seconds(2));
  11162. // Recoonect
  11163. result = cli.Get("/hi");
  11164. ASSERT_TRUE(result);
  11165. EXPECT_EQ(StatusCode::OK_200, result->status);
  11166. result = cli.Get("/hi");
  11167. ASSERT_TRUE(result);
  11168. EXPECT_EQ(StatusCode::OK_200, result->status);
  11169. }
  11170. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11172. ASSERT_TRUE(svr.is_valid());
  11173. svr.set_keep_alive_timeout(1);
  11174. std::string content = "reconnect";
  11175. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11176. res.set_content("Hello World!", "text/plain");
  11177. });
  11178. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. listen_thread.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.wait_until_ready();
  11185. SSLClient cli(HOST, PORT);
  11186. cli.enable_server_certificate_verification(false);
  11187. cli.set_keep_alive(true);
  11188. auto result = cli.Post(
  11189. "/hi", content.size(),
  11190. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11191. sink.write(content.c_str(), content.size());
  11192. return true;
  11193. },
  11194. "text/plain");
  11195. ASSERT_TRUE(result);
  11196. EXPECT_EQ(200, result->status);
  11197. std::this_thread::sleep_for(std::chrono::seconds(2));
  11198. // Recoonect
  11199. result = cli.Post(
  11200. "/hi", content.size(),
  11201. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11202. sink.write(content.c_str(), content.size());
  11203. return true;
  11204. },
  11205. "text/plain");
  11206. ASSERT_TRUE(result);
  11207. EXPECT_EQ(200, result->status);
  11208. result = cli.Post(
  11209. "/hi", content.size(),
  11210. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11211. sink.write(content.c_str(), content.size());
  11212. return true;
  11213. },
  11214. "text/plain");
  11215. ASSERT_TRUE(result);
  11216. EXPECT_EQ(200, result->status);
  11217. }
  11218. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11219. using namespace httplib::tls;
  11220. {
  11221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11222. ASSERT_TRUE(svr.is_valid());
  11223. svr.Get("/sni", [&](const Request &req, Response &res) {
  11224. std::string expected = req.sni();
  11225. EXPECT_EQ(expected, req.get_param_value("expected"));
  11226. res.set_content("ok", "text/plain");
  11227. });
  11228. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11229. auto se = detail::scope_exit([&] {
  11230. svr.stop();
  11231. listen_thread.join();
  11232. ASSERT_FALSE(svr.is_running());
  11233. });
  11234. svr.wait_until_ready();
  11235. {
  11236. SSLClient cli("localhost", PORT);
  11237. cli.enable_server_certificate_verification(false);
  11238. auto res = cli.Get("/sni?expected=localhost");
  11239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11240. }
  11241. {
  11242. SSLClient cli("::1", PORT);
  11243. cli.enable_server_certificate_verification(false);
  11244. auto res = cli.Get("/sni?expected=");
  11245. // NOTE: This may fail if the server is listening on IPv4 only
  11246. // (e.g., when localhost resolves to 127.0.0.1 only)
  11247. if (res) {
  11248. EXPECT_EQ(StatusCode::OK_200, res->status);
  11249. } else {
  11250. EXPECT_EQ(Error::Connection, res.error());
  11251. }
  11252. }
  11253. }
  11254. }
  11255. // The SNI of a failed handshake does not reach the next connection that the
  11256. // same worker thread serves
  11257. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11258. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11259. ASSERT_TRUE(svr.is_valid());
  11260. svr.new_task_queue = [] { return new ThreadPool(1); };
  11261. svr.Get("/sni", [](const Request &req, Response &res) {
  11262. res.set_content(req.sni(), "text/plain");
  11263. });
  11264. auto port = svr.bind_to_any_port("127.0.0.1");
  11265. ASSERT_LT(0, port);
  11266. thread t = thread([&] { svr.listen_after_bind(); });
  11267. auto se = detail::scope_exit([&] {
  11268. svr.stop();
  11269. t.join();
  11270. ASSERT_FALSE(svr.is_running());
  11271. });
  11272. svr.wait_until_ready();
  11273. {
  11274. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11275. SSLClient cli("localhost", port);
  11276. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11277. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11278. auto res = cli.Get("/sni");
  11279. ASSERT_FALSE(res);
  11280. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11281. }
  11282. // An IP host sends no SNI (RFC 6066)
  11283. SSLClient cli("127.0.0.1", port);
  11284. cli.enable_server_certificate_verification(false);
  11285. auto res = cli.Get("/sni");
  11286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11287. EXPECT_EQ("", res->body);
  11288. }
  11289. #endif
  11290. TEST(ClientProblemDetectionTest, ContentProvider) {
  11291. Server svr;
  11292. size_t content_length = 1024 * 1024;
  11293. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11294. res.set_content_provider(
  11295. content_length, "text/plain",
  11296. [&](size_t offset, size_t length, DataSink &sink) {
  11297. auto out_len = std::min(length, static_cast<size_t>(1024));
  11298. std::string out(out_len, '@');
  11299. sink.write(out.data(), out_len);
  11300. return offset < 4096;
  11301. },
  11302. [](bool success) { ASSERT_FALSE(success); });
  11303. });
  11304. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11305. res.set_content_provider(
  11306. 0, "text/plain",
  11307. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11308. EXPECT_TRUE(false);
  11309. return true;
  11310. },
  11311. [](bool success) { ASSERT_FALSE(success); });
  11312. });
  11313. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11314. auto se = detail::scope_exit([&] {
  11315. svr.stop();
  11316. listen_thread.join();
  11317. ASSERT_FALSE(svr.is_running());
  11318. });
  11319. svr.wait_until_ready();
  11320. Client cli("localhost", PORT);
  11321. {
  11322. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11323. size_t /*data_length*/) { return false; });
  11324. ASSERT_FALSE(res);
  11325. }
  11326. {
  11327. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11328. size_t /*data_length*/) { return false; });
  11329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11330. }
  11331. }
  11332. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11333. // A provider that reports success without writing anything and without
  11334. // calling done() used to be handed the same offset and length again on every
  11335. // pass, so it spun for as long as the peer stayed connected.
  11336. Server svr;
  11337. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11338. res.set_content("ok", "text/plain");
  11339. });
  11340. auto port = svr.bind_to_any_port(HOST);
  11341. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11342. auto se = detail::scope_exit([&] {
  11343. svr.stop();
  11344. listen_thread.join();
  11345. ASSERT_FALSE(svr.is_running());
  11346. });
  11347. svr.wait_until_ready();
  11348. std::atomic<int> call_count{0};
  11349. Client cli(HOST, port);
  11350. auto res = cli.Post(
  11351. "/", 1024,
  11352. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11353. // Give up after enough passes to show the spin, so that losing the
  11354. // check below fails this test instead of hanging it.
  11355. return ++call_count < 100;
  11356. },
  11357. "text/plain");
  11358. ASSERT_FALSE(res);
  11359. EXPECT_EQ(Error::Write, res.error());
  11360. EXPECT_EQ(1, call_count.load());
  11361. }
  11362. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11363. // A writer only has to assign `write`. The other three used to be left as
  11364. // empty std::functions, so a provider calling one threw
  11365. // std::bad_function_call out of the thread running it and took the whole
  11366. // process down.
  11367. DataSink sink;
  11368. std::string written;
  11369. sink.write = [&](const char *data, size_t data_len) {
  11370. written.append(data, data_len);
  11371. return true;
  11372. };
  11373. EXPECT_TRUE(sink.is_writable());
  11374. sink.done();
  11375. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11376. EXPECT_TRUE(written.empty());
  11377. }
  11378. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11379. // A sink that cannot carry trailers still has to finish.
  11380. DataSink sink;
  11381. auto done_count = 0;
  11382. sink.done = [&]() { done_count++; };
  11383. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11384. EXPECT_EQ(1, done_count);
  11385. }
  11386. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11387. Server svr;
  11388. const std::string body(4096, 'x');
  11389. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11390. res.set_content_provider(body.size(), "text/plain",
  11391. [&](size_t offset, size_t length, DataSink &sink) {
  11392. sink.write(body.data() + offset, length);
  11393. sink.done();
  11394. return true;
  11395. });
  11396. });
  11397. auto port = svr.bind_to_any_port(HOST);
  11398. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11399. auto se = detail::scope_exit([&] {
  11400. svr.stop();
  11401. listen_thread.join();
  11402. ASSERT_FALSE(svr.is_running());
  11403. });
  11404. svr.wait_until_ready();
  11405. Client cli(HOST, port);
  11406. auto res = cli.Get("/");
  11407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11408. EXPECT_EQ(StatusCode::OK_200, res->status);
  11409. EXPECT_EQ(body, res->body);
  11410. }
  11411. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11412. Server svr;
  11413. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11414. res.set_content_provider(
  11415. 1024, "text/plain",
  11416. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11417. sink.write("hello", 5);
  11418. sink.done(); // short of the 1024 bytes the response promised
  11419. return true;
  11420. });
  11421. });
  11422. auto port = svr.bind_to_any_port(HOST);
  11423. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11424. auto se = detail::scope_exit([&] {
  11425. svr.stop();
  11426. listen_thread.join();
  11427. ASSERT_FALSE(svr.is_running());
  11428. });
  11429. svr.wait_until_ready();
  11430. Client cli(HOST, port);
  11431. cli.set_read_timeout(5, 0);
  11432. // The response is short of its Content-Length, so the client cannot read a
  11433. // complete body. What matters is that this returns at all: a no-op done()
  11434. // would leave the writer looping over a provider that never makes progress.
  11435. auto res = cli.Get("/");
  11436. EXPECT_FALSE(res);
  11437. }
  11438. // Read as the next response by a peer that sees it after a framed body.
  11439. static const std::string smuggled_response =
  11440. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11441. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11442. Server svr;
  11443. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11444. res.set_content_provider(
  11445. 5, "text/plain",
  11446. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11447. auto data = "AAAAA" + smuggled_response;
  11448. sink.write(data.data(), data.size());
  11449. return true;
  11450. });
  11451. });
  11452. thread t = thread([&] { svr.listen(HOST, PORT); });
  11453. auto se = detail::scope_exit([&] {
  11454. svr.stop();
  11455. t.join();
  11456. ASSERT_FALSE(svr.is_running());
  11457. });
  11458. svr.wait_until_ready();
  11459. std::string resp;
  11460. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11461. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11462. resp.clear();
  11463. ASSERT_TRUE(send_request(
  11464. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11465. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11466. }
  11467. TEST(NoContentTest, BodyIsNotSent) {
  11468. Server svr;
  11469. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11470. res.status = StatusCode::NoContent_204;
  11471. res.set_content(smuggled_response, "text/plain");
  11472. });
  11473. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11474. res.status = StatusCode::NotModified_304;
  11475. res.set_chunked_content_provider(
  11476. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11477. sink.write(smuggled_response.data(), smuggled_response.size());
  11478. sink.done();
  11479. return true;
  11480. });
  11481. });
  11482. thread t = thread([&] { svr.listen(HOST, PORT); });
  11483. auto se = detail::scope_exit([&] {
  11484. svr.stop();
  11485. t.join();
  11486. ASSERT_FALSE(svr.is_running());
  11487. });
  11488. svr.wait_until_ready();
  11489. for (auto path : {"/204", "/304"}) {
  11490. std::string resp;
  11491. ASSERT_TRUE(send_request(
  11492. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11493. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11494. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11495. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11496. }
  11497. }
  11498. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11499. Server svr;
  11500. std::atomic<bool> smuggled(false);
  11501. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11502. res.set_content("ok", "text/plain");
  11503. });
  11504. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11505. smuggled = true;
  11506. });
  11507. auto port = svr.bind_to_any_port(HOST);
  11508. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11509. auto se = detail::scope_exit([&] {
  11510. svr.stop();
  11511. listen_thread.join();
  11512. ASSERT_FALSE(svr.is_running());
  11513. });
  11514. svr.wait_until_ready();
  11515. // What follows the body would be read as the next request.
  11516. Client cli(HOST, port);
  11517. auto res = cli.Post(
  11518. "/", 5,
  11519. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11520. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11521. sink.write(data.data(), data.size());
  11522. return true;
  11523. },
  11524. "text/plain");
  11525. ASSERT_FALSE(res);
  11526. EXPECT_EQ(Error::Write, res.error());
  11527. EXPECT_FALSE(smuggled);
  11528. }
  11529. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11530. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11531. // The compressed path builds the whole body before connecting, so this
  11532. // fails client-side and never reaches a server.
  11533. Client cli(HOST, PORT);
  11534. cli.set_compress(true);
  11535. auto res = cli.Post(
  11536. "/", 1024,
  11537. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11538. sink.write("hello", 5);
  11539. sink.done(); // short of the 1024 bytes the request announced
  11540. return true;
  11541. },
  11542. "text/plain");
  11543. ASSERT_FALSE(res);
  11544. EXPECT_EQ(Error::Write, res.error());
  11545. }
  11546. #endif
  11547. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11548. Server svr;
  11549. svr.set_error_handler([](Request const &, Response &res) -> void {
  11550. res.set_chunked_content_provider(
  11551. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11552. sink.os << "hello";
  11553. sink.os << "world";
  11554. sink.done();
  11555. return true;
  11556. });
  11557. });
  11558. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11559. auto se = detail::scope_exit([&] {
  11560. svr.stop();
  11561. listen_thread.join();
  11562. ASSERT_FALSE(svr.is_running());
  11563. });
  11564. svr.wait_until_ready();
  11565. Client cli("localhost", PORT);
  11566. auto res = cli.Get("/");
  11567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11569. EXPECT_EQ("helloworld", res->body);
  11570. }
  11571. // A body set after a content provider must replace it, not be sent through it.
  11572. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11573. Server svr;
  11574. svr.set_mount_point("/", "./www");
  11575. svr.set_file_request_handler([](const Request &req, Response &res) {
  11576. if (req.path == "/dir/test.html") {
  11577. res.status = StatusCode::Forbidden_403;
  11578. res.set_content(std::string(5000, 'D'), "text/plain");
  11579. } else if (req.path == "/file") {
  11580. res.status = StatusCode::Forbidden_403;
  11581. res.body = "Denied";
  11582. }
  11583. });
  11584. auto port = svr.bind_to_any_port(HOST);
  11585. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11586. auto se = detail::scope_exit([&] {
  11587. svr.stop();
  11588. t.join();
  11589. ASSERT_FALSE(svr.is_running());
  11590. });
  11591. svr.wait_until_ready();
  11592. Client cli(HOST, port);
  11593. {
  11594. auto res = cli.Get("/dir/test.html");
  11595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11596. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11597. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11598. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11599. }
  11600. {
  11601. auto res = cli.Get("/file");
  11602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11603. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11604. EXPECT_EQ("Denied", res->body);
  11605. }
  11606. {
  11607. auto res = cli.Get("/dir/index.html");
  11608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11609. EXPECT_EQ(StatusCode::OK_200, res->status);
  11610. EXPECT_EQ(0U, res->body.find("<html>"));
  11611. }
  11612. }
  11613. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11614. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11615. Server svr;
  11616. std::vector<bool> released;
  11617. std::mutex released_mutex;
  11618. auto releaser = [&](bool success) {
  11619. std::lock_guard<std::mutex> guard(released_mutex);
  11620. released.push_back(success);
  11621. };
  11622. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11623. return sink.write(&"hello"[offset], length);
  11624. };
  11625. svr.Get("/sized", [&](const Request &, Response &res) {
  11626. res.status = StatusCode::NotFound_404;
  11627. res.set_content_provider(5, "text/plain", provider, releaser);
  11628. });
  11629. svr.Get("/chunked", [&](const Request &, Response &res) {
  11630. res.status = StatusCode::ServiceUnavailable_503;
  11631. res.set_chunked_content_provider(
  11632. "text/plain",
  11633. [](size_t, DataSink &sink) {
  11634. sink.os << "chunk";
  11635. sink.done();
  11636. return true;
  11637. },
  11638. releaser);
  11639. });
  11640. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11641. res.set_content_provider(5, "text/plain", provider, releaser);
  11642. throw std::runtime_error("after the provider");
  11643. });
  11644. svr.set_error_handler([](const Request &req, Response &res) {
  11645. // Leave the exception handler's content to it.
  11646. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11647. res.set_content(std::string(1000, 'E'), "text/html");
  11648. return Server::HandlerResponse::Handled;
  11649. });
  11650. svr.set_exception_handler(
  11651. [](const Request &, Response &res, std::exception_ptr) {
  11652. res.status = StatusCode::InternalServerError_500;
  11653. res.set_content(std::string(1000, 'X'), "text/html");
  11654. });
  11655. auto port = svr.bind_to_any_port(HOST);
  11656. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11657. auto se = detail::scope_exit([&] {
  11658. svr.stop();
  11659. t.join();
  11660. ASSERT_FALSE(svr.is_running());
  11661. });
  11662. svr.wait_until_ready();
  11663. Client cli(HOST, port);
  11664. {
  11665. auto res = cli.Get("/sized");
  11666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11667. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11668. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11669. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11670. }
  11671. {
  11672. auto res = cli.Get("/chunked");
  11673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11674. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11675. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11676. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11677. }
  11678. {
  11679. auto res = cli.Get("/throw");
  11680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11681. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11682. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11683. }
  11684. std::lock_guard<std::mutex> guard(released_mutex);
  11685. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11686. }
  11687. #endif
  11688. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11689. Server svr;
  11690. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11691. return sink.write(&"abc"[offset], length);
  11692. };
  11693. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11694. res.set_file_content("./www/dir/test.html");
  11695. res.set_content("body", "text/plain");
  11696. });
  11697. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11698. res.set_content(std::string(100, 'B'), "text/plain");
  11699. res.set_file_content("./www/dir/test.html");
  11700. });
  11701. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11702. res.set_content(std::string(100, 'B'), "text/plain");
  11703. res.set_content_provider(3, "text/x-provider", abc);
  11704. });
  11705. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11706. res.set_content_provider(3, "text/x-provider", abc);
  11707. res.set_content(std::string(100, 'B'), "text/plain");
  11708. });
  11709. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11710. res.set_content_provider(3, "text/x-provider", abc);
  11711. res.set_file_content("./www/dir/test.html", "text/x-file");
  11712. });
  11713. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11714. res.set_file_content("./www/dir/test.html");
  11715. res.set_header("Content-Type", "text/x-handler");
  11716. });
  11717. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11718. res.set_content_provider(3, "text/plain", abc);
  11719. res.body = "direct";
  11720. });
  11721. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11722. res.set_file_content("./www/dir/test.html");
  11723. res.body = "direct";
  11724. });
  11725. auto port = svr.bind_to_any_port(HOST);
  11726. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11727. auto se = detail::scope_exit([&] {
  11728. svr.stop();
  11729. t.join();
  11730. ASSERT_FALSE(svr.is_running());
  11731. });
  11732. svr.wait_until_ready();
  11733. Client cli(HOST, port);
  11734. auto expect_body = [&](const char *path, const std::string &body,
  11735. const std::string &type) {
  11736. // Uncompressed, so Content-Length can be compared with the body.
  11737. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11738. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11739. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11740. EXPECT_EQ(body, res->body) << path;
  11741. EXPECT_EQ(std::to_string(body.size()),
  11742. res->get_header_value("Content-Length"))
  11743. << path;
  11744. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11745. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11746. };
  11747. expect_body("/file-then-body", "body", "text/plain");
  11748. expect_body("/body-then-file", "test.html", "text/html");
  11749. expect_body("/body-then-provider", "abc", "text/x-provider");
  11750. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11751. expect_body("/provider-then-file", "test.html", "text/x-file");
  11752. expect_body("/file-then-header", "test.html", "text/x-handler");
  11753. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11754. expect_body("/file-then-direct-body", "direct", "text/plain");
  11755. // Ranges are checked against the body, not the dropped provider.
  11756. {
  11757. auto res = cli.Get("/provider-then-direct-body",
  11758. Headers{{make_range_header({{1, 2}})}});
  11759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11761. EXPECT_EQ("ir", res->body);
  11762. }
  11763. {
  11764. auto res = cli.Get("/file-then-direct-body",
  11765. Headers{{make_range_header({{7, 8}})}});
  11766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11767. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11768. }
  11769. }
  11770. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11771. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11772. const char *path = "./truncated_while_served.txt";
  11773. const size_t size = 32 * 1024 * 1024;
  11774. {
  11775. std::ofstream f(path, std::ios::binary);
  11776. f << std::string(size, 'x');
  11777. }
  11778. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11779. // Over TLS, where the bytes are encrypted in this process rather than
  11780. // copied by send().
  11781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11782. svr.Get("/file", [&](const Request &, Response &res) {
  11783. res.set_file_content(path, "text/plain");
  11784. });
  11785. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11786. auto se = detail::scope_exit([&] {
  11787. svr.stop();
  11788. thread.join();
  11789. ASSERT_FALSE(svr.is_running());
  11790. });
  11791. svr.wait_until_ready();
  11792. // The file shrinks once the first bytes are in, as a rewrite in place
  11793. // would, and reading the mapping past its new end used to raise SIGBUS.
  11794. SSLClient cli(HOST, PORT);
  11795. cli.enable_server_certificate_verification(false);
  11796. size_t received = 0;
  11797. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11798. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11799. received += len;
  11800. return true;
  11801. });
  11802. EXPECT_FALSE(res);
  11803. EXPECT_LT(received, size);
  11804. }
  11805. #endif
  11806. // Forward declaration (see the base64_encode note).
  11807. namespace httplib {
  11808. namespace detail {
  11809. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11810. const std::string &content_type,
  11811. EncodingType encoding);
  11812. } // namespace detail
  11813. } // namespace httplib
  11814. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11815. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11816. ASSERT_TRUE(mm->is_open());
  11817. Response res;
  11818. detail::set_file_content_provider(res, mm, "text/html",
  11819. detail::EncodingType::None);
  11820. std::string out;
  11821. DataSink sink;
  11822. sink.write = [&](const char *d, size_t l) {
  11823. out.append(d, l);
  11824. return true;
  11825. };
  11826. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11827. EXPECT_EQ("test.html", out);
  11828. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11829. EXPECT_EQ("test.html", out);
  11830. }
  11831. TEST(LongPollingTest, ClientCloseDetection) {
  11832. Server svr;
  11833. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11834. res.set_chunked_content_provider(
  11835. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11836. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11837. sink.os << "hello";
  11838. auto count = 10;
  11839. while (count > 0 && sink.is_writable()) {
  11840. this_thread::sleep_for(chrono::milliseconds(10));
  11841. count--;
  11842. }
  11843. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11844. return true;
  11845. });
  11846. });
  11847. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11848. auto se = detail::scope_exit([&] {
  11849. svr.stop();
  11850. listen_thread.join();
  11851. ASSERT_FALSE(svr.is_running());
  11852. });
  11853. svr.wait_until_ready();
  11854. Client cli("localhost", PORT);
  11855. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11856. EXPECT_EQ("hello", string(data, data_length));
  11857. return false; // close the socket immediately.
  11858. });
  11859. ASSERT_FALSE(res);
  11860. }
  11861. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11862. Server svr;
  11863. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11864. res.set_chunked_content_provider(
  11865. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11866. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11867. sink.os << "hello";
  11868. EXPECT_TRUE(sink.os.good());
  11869. // Wait for the client to close the connection
  11870. auto count = 10;
  11871. while (count > 0 && sink.is_writable()) {
  11872. this_thread::sleep_for(chrono::milliseconds(10));
  11873. count--;
  11874. }
  11875. // After client disconnect, write repeatedly until the socket
  11876. // write actually fails (small writes may be absorbed by the
  11877. // kernel buffer)
  11878. std::string chunk(1024, 'x');
  11879. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11880. sink.os << chunk;
  11881. }
  11882. EXPECT_TRUE(sink.os.fail());
  11883. return true;
  11884. });
  11885. });
  11886. auto port = svr.bind_to_any_port("localhost");
  11887. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11888. auto se = detail::scope_exit([&] {
  11889. svr.stop();
  11890. listen_thread.join();
  11891. ASSERT_FALSE(svr.is_running());
  11892. });
  11893. svr.wait_until_ready();
  11894. Client cli("localhost", port);
  11895. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11896. EXPECT_EQ("hello", string(data, data_length));
  11897. return false; // close the socket immediately.
  11898. });
  11899. ASSERT_FALSE(res);
  11900. }
  11901. TEST(GetWithParametersTest, GetWithParameters) {
  11902. Server svr;
  11903. svr.Get("/", [&](const Request &req, Response &) {
  11904. EXPECT_EQ("world", req.get_param_value("hello"));
  11905. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11906. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11907. });
  11908. svr.Get("/params", [&](const Request &req, Response &) {
  11909. EXPECT_EQ("world", req.get_param_value("hello"));
  11910. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11911. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11912. });
  11913. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11914. EXPECT_EQ("resource-id", req.matches[1]);
  11915. EXPECT_EQ("foo", req.get_param_value("param1"));
  11916. EXPECT_EQ("bar", req.get_param_value("param2"));
  11917. });
  11918. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11919. EXPECT_EQ("user-id", req.path_params.at("id"));
  11920. EXPECT_EQ("foo", req.get_param_value("param1"));
  11921. EXPECT_EQ("bar", req.get_param_value("param2"));
  11922. });
  11923. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11924. auto se = detail::scope_exit([&] {
  11925. svr.stop();
  11926. listen_thread.join();
  11927. ASSERT_FALSE(svr.is_running());
  11928. });
  11929. svr.wait_until_ready();
  11930. {
  11931. Client cli(HOST, PORT);
  11932. Params params;
  11933. params.emplace("hello", "world");
  11934. params.emplace("hello2", "world2");
  11935. params.emplace("hello3", "world3");
  11936. auto res = cli.Get("/", params, Headers{});
  11937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11938. EXPECT_EQ(StatusCode::OK_200, res->status);
  11939. }
  11940. {
  11941. Client cli(HOST, PORT);
  11942. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11944. EXPECT_EQ(StatusCode::OK_200, res->status);
  11945. }
  11946. {
  11947. Client cli(HOST, PORT);
  11948. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. EXPECT_EQ(StatusCode::OK_200, res->status);
  11951. }
  11952. {
  11953. Client cli(HOST, PORT);
  11954. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. EXPECT_EQ(StatusCode::OK_200, res->status);
  11957. }
  11958. }
  11959. TEST(GetWithParametersTest, GetWithParameters2) {
  11960. Server svr;
  11961. svr.Get("/", [&](const Request &req, Response &res) {
  11962. auto text = req.get_param_value("hello");
  11963. res.set_content(text, "text/plain");
  11964. });
  11965. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11966. auto se = detail::scope_exit([&] {
  11967. svr.stop();
  11968. listen_thread.join();
  11969. ASSERT_FALSE(svr.is_running());
  11970. });
  11971. svr.wait_until_ready();
  11972. Client cli("localhost", PORT);
  11973. Params params;
  11974. params.emplace("hello", "world");
  11975. std::string body;
  11976. auto res = cli.Get("/", params, Headers{},
  11977. [&](const char *data, size_t data_length) {
  11978. body.append(data, data_length);
  11979. return true;
  11980. });
  11981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11982. EXPECT_EQ(StatusCode::OK_200, res->status);
  11983. EXPECT_EQ("world", body);
  11984. }
  11985. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11986. Server svr;
  11987. svr.Get("/search", [&](const Request &req, Response &res) {
  11988. auto q = req.get_param_value("q");
  11989. res.set_content(q, "text/plain");
  11990. });
  11991. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11992. auto se = detail::scope_exit([&] {
  11993. svr.stop();
  11994. listen_thread.join();
  11995. ASSERT_FALSE(svr.is_running());
  11996. });
  11997. svr.wait_until_ready();
  11998. Client cli("localhost", PORT);
  11999. // Verify that Get(path, params) works without requiring Headers argument
  12000. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12002. EXPECT_EQ(StatusCode::OK_200, res->status);
  12003. EXPECT_EQ("cpp-httplib", res->body);
  12004. }
  12005. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12006. auto host = "httpbingo.org";
  12007. auto path = std::string{"/range/32"};
  12008. #ifdef CPPHTTPLIB_SSL_ENABLED
  12009. SSLClient cli(host);
  12010. #else
  12011. Client cli(host);
  12012. #endif
  12013. cli.set_default_headers({make_range_header({{1, 10}})});
  12014. cli.set_connection_timeout(5);
  12015. {
  12016. auto res = cli.Get(path);
  12017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12018. EXPECT_EQ("bcdefghijk", res->body);
  12019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12020. }
  12021. {
  12022. auto res = cli.Get(path);
  12023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12024. EXPECT_EQ("bcdefghijk", res->body);
  12025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12026. }
  12027. }
  12028. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12029. Server svr;
  12030. svr.set_default_headers({{"Hello", "World"}});
  12031. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12032. res.set_content("ok", "text/plain");
  12033. });
  12034. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12035. auto se = detail::scope_exit([&] {
  12036. svr.stop();
  12037. listen_thread.join();
  12038. ASSERT_FALSE(svr.is_running());
  12039. });
  12040. svr.wait_until_ready();
  12041. Client cli("localhost", PORT);
  12042. auto res = cli.Get("/");
  12043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12044. EXPECT_EQ(StatusCode::OK_200, res->status);
  12045. EXPECT_EQ("ok", res->body);
  12046. EXPECT_EQ("World", res->get_header_value("Hello"));
  12047. }
  12048. #ifdef CPPHTTPLIB_SSL_ENABLED
  12049. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12050. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12051. ASSERT_TRUE(svr.is_valid());
  12052. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12053. std::this_thread::sleep_for(std::chrono::seconds(2));
  12054. res.set_content("a", "text/plain");
  12055. });
  12056. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12057. res.set_content("b", "text/plain");
  12058. });
  12059. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12060. auto se = detail::scope_exit([&] {
  12061. svr.stop();
  12062. listen_thread.join();
  12063. ASSERT_FALSE(svr.is_running());
  12064. });
  12065. svr.wait_until_ready();
  12066. SSLClient cli("localhost", PORT);
  12067. cli.enable_server_certificate_verification(false);
  12068. cli.set_keep_alive(true);
  12069. cli.set_read_timeout(std::chrono::seconds(1));
  12070. auto resa = cli.Get("/a");
  12071. ASSERT_TRUE(!resa);
  12072. EXPECT_EQ(Error::Read, resa.error());
  12073. auto resb = cli.Get("/b");
  12074. ASSERT_TRUE(resb);
  12075. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12076. EXPECT_EQ("b", resb->body);
  12077. }
  12078. // Closing an idle keep-alive connection sends close_notify and returns. The
  12079. // server must not wait for the client's close_notify: an idle client never
  12080. // sends one, so the worker would be held until the read timeout expires, and
  12081. // stop() would wait for it.
  12082. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12084. ASSERT_TRUE(svr.is_valid());
  12085. svr.set_keep_alive_timeout(1);
  12086. svr.set_read_timeout(10, 0);
  12087. svr.Get("/", [](const Request &, Response &res) {
  12088. res.set_content("ok", "text/plain");
  12089. });
  12090. auto port = svr.bind_to_any_port(HOST);
  12091. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12092. auto se = detail::scope_exit([&] {
  12093. if (listen_thread.joinable()) {
  12094. svr.stop();
  12095. listen_thread.join();
  12096. }
  12097. });
  12098. svr.wait_until_ready();
  12099. SSLClient cli(HOST, port);
  12100. cli.enable_server_certificate_verification(false);
  12101. cli.set_keep_alive(true);
  12102. auto res = cli.Get("/");
  12103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12104. EXPECT_EQ(StatusCode::OK_200, res->status);
  12105. // Stay idle past the keep-alive timeout so the server closes the connection.
  12106. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12107. auto start = std::chrono::steady_clock::now();
  12108. svr.stop();
  12109. listen_thread.join();
  12110. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12111. std::chrono::steady_clock::now() - start)
  12112. .count();
  12113. EXPECT_LT(elapsed, 3000);
  12114. }
  12115. #endif
  12116. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12117. protected:
  12118. ServerTestWithAI_PASSIVE()
  12119. : cli_(HOST, PORT)
  12120. #ifdef CPPHTTPLIB_SSL_ENABLED
  12121. ,
  12122. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12123. #endif
  12124. {
  12125. #ifdef CPPHTTPLIB_SSL_ENABLED
  12126. cli_.enable_server_certificate_verification(false);
  12127. #endif
  12128. }
  12129. virtual void SetUp() {
  12130. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12131. res.set_content("Hello World!", "text/plain");
  12132. });
  12133. t_ = thread(
  12134. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12135. svr_.wait_until_ready();
  12136. }
  12137. virtual void TearDown() {
  12138. svr_.stop();
  12139. t_.join();
  12140. }
  12141. #ifdef CPPHTTPLIB_SSL_ENABLED
  12142. SSLClient cli_;
  12143. SSLServer svr_;
  12144. #else
  12145. Client cli_;
  12146. Server svr_;
  12147. #endif
  12148. thread t_;
  12149. };
  12150. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12151. auto res = cli_.Get("/hi");
  12152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12153. EXPECT_EQ(StatusCode::OK_200, res->status);
  12154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12155. EXPECT_EQ("Hello World!", res->body);
  12156. }
  12157. class ServerUpDownTest : public ::testing::Test {
  12158. protected:
  12159. ServerUpDownTest() : cli_(HOST, PORT) {}
  12160. virtual void SetUp() {
  12161. t_ = thread([&]() {
  12162. svr_.bind_to_any_port(HOST);
  12163. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12164. ASSERT_TRUE(svr_.listen_after_bind());
  12165. });
  12166. svr_.wait_until_ready();
  12167. }
  12168. virtual void TearDown() {
  12169. svr_.stop();
  12170. t_.join();
  12171. }
  12172. Client cli_;
  12173. Server svr_;
  12174. thread t_;
  12175. };
  12176. TEST_F(ServerUpDownTest, QuickStartStop) {
  12177. // Should not crash, especially when run with
  12178. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12179. }
  12180. class PayloadMaxLengthTest : public ::testing::Test {
  12181. protected:
  12182. PayloadMaxLengthTest()
  12183. : cli_(HOST, PORT)
  12184. #ifdef CPPHTTPLIB_SSL_ENABLED
  12185. ,
  12186. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12187. #endif
  12188. {
  12189. #ifdef CPPHTTPLIB_SSL_ENABLED
  12190. cli_.enable_server_certificate_verification(false);
  12191. #endif
  12192. }
  12193. virtual void SetUp() {
  12194. svr_.set_payload_max_length(8);
  12195. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12196. res.set_content("test", "text/plain");
  12197. });
  12198. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12199. svr_.wait_until_ready();
  12200. }
  12201. virtual void TearDown() {
  12202. svr_.stop();
  12203. t_.join();
  12204. }
  12205. #ifdef CPPHTTPLIB_SSL_ENABLED
  12206. SSLClient cli_;
  12207. SSLServer svr_;
  12208. #else
  12209. Client cli_;
  12210. Server svr_;
  12211. #endif
  12212. thread t_;
  12213. };
  12214. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12215. auto res = cli_.Post("/test", "123456789", "text/plain");
  12216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12217. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12218. res = cli_.Post("/test", "12345678", "text/plain");
  12219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12220. EXPECT_EQ(StatusCode::OK_200, res->status);
  12221. }
  12222. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12223. // Test chunked encoding with payload exceeding the 8-byte limit
  12224. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12225. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12227. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12228. }
  12229. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12230. // Test chunked encoding with payload within the 8-byte limit
  12231. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12232. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12234. EXPECT_EQ(StatusCode::OK_200, res->status);
  12235. }
  12236. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12237. // Test using send_request to send chunked data exceeding payload limit
  12238. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12239. "Host: " +
  12240. std::string(HOST) + ":" + std::to_string(PORT) +
  12241. "\r\n"
  12242. "Transfer-Encoding: chunked\r\n"
  12243. "Connection: close\r\n"
  12244. "\r\n"
  12245. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12246. "0123456789\r\n"
  12247. "0\r\n" // End chunk
  12248. "\r\n";
  12249. std::string response;
  12250. bool result = send_request(1, chunked_request, &response);
  12251. if (!result) {
  12252. // If send_request fails, it might be because the server closed the
  12253. // connection due to payload limit enforcement, which is acceptable
  12254. SUCCEED()
  12255. << "Server rejected oversized chunked request (connection closed)";
  12256. } else {
  12257. // If we got a response, check if it's an error response or connection was
  12258. // closed early Short response length indicates connection was closed due to
  12259. // payload limit
  12260. if (response.length() <= 10) {
  12261. SUCCEED() << "Server closed connection for oversized chunked request";
  12262. } else {
  12263. // Check for error status codes
  12264. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12265. response.find("Payload Too Large") != std::string::npos ||
  12266. response.find("400") != std::string::npos);
  12267. }
  12268. }
  12269. }
  12270. class LargePayloadMaxLengthTest : public ::testing::Test {
  12271. protected:
  12272. LargePayloadMaxLengthTest()
  12273. : cli_(HOST, PORT)
  12274. #ifdef CPPHTTPLIB_SSL_ENABLED
  12275. ,
  12276. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12277. #endif
  12278. {
  12279. #ifdef CPPHTTPLIB_SSL_ENABLED
  12280. cli_.enable_server_certificate_verification(false);
  12281. #endif
  12282. }
  12283. virtual void SetUp() {
  12284. // Set 10MB payload limit
  12285. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12286. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12287. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12288. res.set_content("Large payload test", "text/plain");
  12289. });
  12290. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12291. svr_.wait_until_ready();
  12292. }
  12293. virtual void TearDown() {
  12294. svr_.stop();
  12295. t_.join();
  12296. }
  12297. #ifdef CPPHTTPLIB_SSL_ENABLED
  12298. SSLClient cli_;
  12299. SSLServer svr_;
  12300. #else
  12301. Client cli_;
  12302. Server svr_;
  12303. #endif
  12304. thread t_;
  12305. };
  12306. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12307. // Test chunked encoding with payload within 10MB limit
  12308. std::string medium_payload(5 * 1024 * 1024,
  12309. 'A'); // 5MB payload, within 10MB limit
  12310. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12312. EXPECT_EQ(StatusCode::OK_200, res->status);
  12313. }
  12314. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12315. // Test chunked encoding with payload exceeding 10MB limit
  12316. std::string large_payload(12 * 1024 * 1024,
  12317. 'B'); // 12MB payload, exceeds 10MB limit
  12318. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12319. // Server may either return 413 or close the connection
  12320. if (res) {
  12321. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12322. } else {
  12323. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12324. }
  12325. }
  12326. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12327. Server svr;
  12328. svr.Get("/", [](const Request &, Response &res) {
  12329. // Claims the most the client accepts, far more than it sends, then drops
  12330. // the connection.
  12331. res.set_content_provider(std::string().max_size(), "text/plain",
  12332. [](size_t, size_t, DataSink &sink) {
  12333. sink.write("abc", 3);
  12334. return false;
  12335. });
  12336. });
  12337. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12338. auto se = detail::scope_exit([&] {
  12339. svr.stop();
  12340. thread.join();
  12341. ASSERT_FALSE(svr.is_running());
  12342. });
  12343. svr.wait_until_ready();
  12344. Client cli(HOST, PORT);
  12345. cli.set_payload_max_length(0);
  12346. EXPECT_FALSE(cli.Get("/"));
  12347. }
  12348. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12349. // Stream API does, not as a plain read failure
  12350. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12351. Server svr;
  12352. svr.Get("/big", [](const Request &, Response &res) {
  12353. res.set_content(std::string(100000, 'b'), "text/plain");
  12354. });
  12355. auto port = svr.bind_to_any_port(HOST);
  12356. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12357. auto se = detail::scope_exit([&] {
  12358. svr.stop();
  12359. thread.join();
  12360. });
  12361. svr.wait_until_ready();
  12362. Client cli(HOST, port);
  12363. cli.set_payload_max_length(1000);
  12364. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12365. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12366. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12367. [](const char *, size_t) { return true; });
  12368. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12369. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12370. // Small on the wire, over the limit once decompressed
  12371. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12372. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12373. #endif
  12374. }
  12375. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12376. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12377. // path.
  12378. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12379. Server svr;
  12380. const size_t LIMIT = 64 * 1024; // 64KB
  12381. svr.set_payload_max_length(LIMIT);
  12382. size_t total = 0;
  12383. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12384. const ContentReader &content_reader) {
  12385. content_reader([&](const char * /*data*/, size_t len) {
  12386. total += len;
  12387. return true;
  12388. });
  12389. res.status = 200;
  12390. res.set_content("stream_ok", "text/plain");
  12391. });
  12392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12393. auto se = detail::scope_exit([&] {
  12394. svr.stop();
  12395. thread.join();
  12396. ASSERT_FALSE(svr.is_running());
  12397. });
  12398. svr.wait_until_ready();
  12399. // Prepare 256KB raw data and gzip-compress it
  12400. std::string raw(256 * 1024, 'A');
  12401. std::string gz;
  12402. {
  12403. z_stream zs{};
  12404. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12405. Z_DEFAULT_STRATEGY);
  12406. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12407. zs.avail_in = static_cast<uInt>(raw.size());
  12408. char outbuf[4096];
  12409. int ret;
  12410. do {
  12411. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12412. zs.avail_out = sizeof(outbuf);
  12413. ret = deflate(&zs, Z_FINISH);
  12414. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12415. } while (ret != Z_STREAM_END);
  12416. deflateEnd(&zs);
  12417. }
  12418. Client cli(HOST, PORT);
  12419. cli.set_connection_timeout(std::chrono::seconds(5));
  12420. Headers headers = {{"Content-Encoding", "gzip"}};
  12421. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12422. "application/octet-stream");
  12423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12424. // Server must reject oversized decompressed payloads with 413.
  12425. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12426. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12427. EXPECT_LE(total, LIMIT);
  12428. }
  12429. #endif
  12430. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12431. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12432. // the payload must be passed through untouched instead of being rejected.
  12433. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12434. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12435. Server svr;
  12436. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12437. res.set_content(body, "image/jpeg");
  12438. res.set_header("Content-Encoding", "UTF-8");
  12439. });
  12440. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12441. res.set_content(body, "image/jpeg");
  12442. res.set_header("Content-Encoding", "identity");
  12443. });
  12444. svr.Post("/echo", [](const Request &req, Response &res) {
  12445. res.set_content(req.body, "image/jpeg");
  12446. });
  12447. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12448. auto se = detail::scope_exit([&] {
  12449. svr.stop();
  12450. t.join();
  12451. ASSERT_FALSE(svr.is_running());
  12452. });
  12453. svr.wait_until_ready();
  12454. Client cli(HOST, PORT);
  12455. {
  12456. auto res = cli.Get("/image");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. EXPECT_EQ(StatusCode::OK_200, res->status);
  12459. EXPECT_EQ(body, res->body);
  12460. }
  12461. {
  12462. auto res = cli.Get("/identity");
  12463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12464. EXPECT_EQ(StatusCode::OK_200, res->status);
  12465. EXPECT_EQ(body, res->body);
  12466. }
  12467. {
  12468. // The same applies to a request body reaching the server.
  12469. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12470. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12472. EXPECT_EQ(StatusCode::OK_200, res->status);
  12473. EXPECT_EQ(body, res->body);
  12474. }
  12475. }
  12476. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12477. // gzip-encoded response even when the build has no zlib support.
  12478. static const char GZIPPED_HELLO_WORLD[] = {
  12479. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12480. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12481. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12482. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12483. // A content coding is a whole token, not something the field value merely
  12484. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12485. // as "fibre" look like Brotli, and turned a multi-coding value like
  12486. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12487. // it was never meant to see.
  12488. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12489. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12490. Server svr;
  12491. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12492. res.set_content(body, "image/jpeg");
  12493. res.set_header("Content-Encoding", "fibre");
  12494. });
  12495. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12496. res.set_content(body, "image/jpeg");
  12497. res.set_header("Content-Encoding", "gzip, br");
  12498. });
  12499. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12500. res.set_content(body, "image/jpeg");
  12501. res.set_header("Content-Encoding", "x-zstd-ish");
  12502. });
  12503. auto port = svr.bind_to_any_port(HOST);
  12504. thread t = thread([&]() { svr.listen_after_bind(); });
  12505. auto se = detail::scope_exit([&] {
  12506. svr.stop();
  12507. t.join();
  12508. ASSERT_FALSE(svr.is_running());
  12509. });
  12510. svr.wait_until_ready();
  12511. Client cli(HOST, port);
  12512. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12513. auto res = cli.Get(path);
  12514. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12515. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12516. // Not a coding we recognize, so the payload comes back untouched
  12517. EXPECT_EQ(body, res->body) << path;
  12518. }
  12519. }
  12520. // A content coding cpp-httplib recognizes but was not built with must be
  12521. // reported as such. Handing the still-compressed payload back to the caller
  12522. // would silently corrupt it.
  12523. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12524. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12525. Server svr;
  12526. // "image/jpeg" keeps the server from applying a content coding of its own,
  12527. // so the hand-crafted Content-Encoding below survives.
  12528. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12529. res.set_content(gzipped, "image/jpeg");
  12530. res.set_header("Content-Encoding", "gzip");
  12531. });
  12532. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12533. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12534. res.set_content(gzipped, "image/jpeg");
  12535. res.set_header("Content-Encoding", "GZIP");
  12536. });
  12537. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12538. auto se = detail::scope_exit([&] {
  12539. svr.stop();
  12540. t.join();
  12541. ASSERT_FALSE(svr.is_running());
  12542. });
  12543. svr.wait_until_ready();
  12544. Client cli(HOST, PORT);
  12545. {
  12546. auto res = cli.Get("/gzipped");
  12547. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12549. EXPECT_EQ("Hello World!", res->body);
  12550. #else
  12551. ASSERT_FALSE(res);
  12552. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12553. #endif
  12554. }
  12555. {
  12556. // open_stream() must behave the same way.
  12557. auto handle = cli.open_stream("GET", "/gzipped");
  12558. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12559. ASSERT_TRUE(handle.is_valid());
  12560. std::string received;
  12561. char buf[256];
  12562. ssize_t n;
  12563. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12564. received.append(buf, static_cast<size_t>(n));
  12565. }
  12566. EXPECT_EQ("Hello World!", received);
  12567. #else
  12568. EXPECT_FALSE(handle.is_valid());
  12569. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12570. #endif
  12571. }
  12572. {
  12573. // A differently-cased coding must not be mistaken for an unknown one, or
  12574. // the body would be handed back still compressed.
  12575. auto res = cli.Get("/gzipped-uppercase");
  12576. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12578. EXPECT_EQ("Hello World!", res->body);
  12579. #else
  12580. ASSERT_FALSE(res);
  12581. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12582. #endif
  12583. }
  12584. }
  12585. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12586. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12587. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12588. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12589. // body a second time and appending a second Content-Encoding field line, so
  12590. // clients that decode one coding per listed value handed back raw gzip bytes.
  12591. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12592. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12593. Server svr;
  12594. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12595. // keeps the server from applying a coding of its own.
  12596. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12597. res.set_content(gzipped, "text/plain");
  12598. res.set_header("Content-Encoding", "gzip");
  12599. });
  12600. auto port = svr.bind_to_any_port(HOST);
  12601. thread t = thread([&]() { svr.listen_after_bind(); });
  12602. auto se = detail::scope_exit([&] {
  12603. svr.stop();
  12604. t.join();
  12605. ASSERT_FALSE(svr.is_running());
  12606. });
  12607. svr.wait_until_ready();
  12608. Client cli(HOST, port);
  12609. Headers headers = {{"Accept-Encoding", "gzip"}};
  12610. auto res = cli.Get("/pre-gzipped", headers);
  12611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12612. EXPECT_EQ(StatusCode::OK_200, res->status);
  12613. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12614. EXPECT_EQ("Hello World!", res->body);
  12615. }
  12616. // set_compress(false) sends every handler response as it is, buffered or
  12617. // streamed
  12618. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12619. const std::string text(1000, 'a');
  12620. Server svr;
  12621. svr.set_compress(false);
  12622. svr.Get("/buffered", [&](const Request &, Response &res) {
  12623. res.set_content(text, "text/plain");
  12624. });
  12625. svr.Get("/streamed", [&](const Request &, Response &res) {
  12626. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12627. sink.write(text.data(), text.size());
  12628. sink.done();
  12629. return true;
  12630. });
  12631. });
  12632. auto port = svr.bind_to_any_port(HOST);
  12633. ASSERT_LT(0, port);
  12634. thread t = thread([&] { svr.listen_after_bind(); });
  12635. auto se = detail::scope_exit([&] {
  12636. svr.stop();
  12637. t.join();
  12638. ASSERT_FALSE(svr.is_running());
  12639. });
  12640. svr.wait_until_ready();
  12641. Client cli(HOST, port);
  12642. cli.set_decompress(false);
  12643. for (auto path : {"/buffered", "/streamed"}) {
  12644. SCOPED_TRACE(path);
  12645. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12647. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12648. EXPECT_EQ(text, res->body);
  12649. }
  12650. }
  12651. // A chunked provider settles its coding where the headers are written and
  12652. // reuses it at write time. Both ends of that have to hold: a handler's own
  12653. // Content-Encoding suppresses the coding, and a response without one is still
  12654. // compressed as it always was.
  12655. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12656. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12657. const std::string plain = "Hello World! Hello World! Hello World!";
  12658. Server svr;
  12659. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12660. res.set_header("Content-Encoding", "gzip");
  12661. res.set_chunked_content_provider(
  12662. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12663. sink.write(gzipped.data(), gzipped.size());
  12664. sink.done();
  12665. return true;
  12666. });
  12667. });
  12668. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12669. res.set_chunked_content_provider(
  12670. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12671. sink.write(plain.data(), plain.size());
  12672. sink.done();
  12673. return true;
  12674. });
  12675. });
  12676. auto port = svr.bind_to_any_port(HOST);
  12677. thread t = thread([&]() { svr.listen_after_bind(); });
  12678. auto se = detail::scope_exit([&] {
  12679. svr.stop();
  12680. t.join();
  12681. ASSERT_FALSE(svr.is_running());
  12682. });
  12683. svr.wait_until_ready();
  12684. Client cli(HOST, port);
  12685. Headers headers = {{"Accept-Encoding", "gzip"}};
  12686. {
  12687. auto res = cli.Get("/pre-gzipped", headers);
  12688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12689. EXPECT_EQ(StatusCode::OK_200, res->status);
  12690. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12691. EXPECT_EQ("Hello World!", res->body);
  12692. }
  12693. {
  12694. auto res = cli.Get("/negotiated", headers);
  12695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12696. EXPECT_EQ(StatusCode::OK_200, res->status);
  12697. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12698. EXPECT_EQ(plain, res->body);
  12699. }
  12700. }
  12701. #endif
  12702. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12703. // the same message as the comma-joined one, so both have to be read the same
  12704. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12705. // single gzip coding, and a body the sender says was encoded twice was handed
  12706. // back after one pass, still compressed but presented as decoded.
  12707. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12708. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12709. Server svr;
  12710. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12711. res.set_content(body, "image/jpeg");
  12712. res.headers.emplace("Content-Encoding", "gzip");
  12713. res.headers.emplace("Content-Encoding", "gzip");
  12714. });
  12715. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12716. res.set_content(body, "image/jpeg");
  12717. res.set_header("Content-Encoding", "gzip, gzip");
  12718. });
  12719. auto port = svr.bind_to_any_port(HOST);
  12720. thread t = thread([&]() { svr.listen_after_bind(); });
  12721. auto se = detail::scope_exit([&] {
  12722. svr.stop();
  12723. t.join();
  12724. ASSERT_FALSE(svr.is_running());
  12725. });
  12726. svr.wait_until_ready();
  12727. Client cli(HOST, port);
  12728. // Two codings is not something cpp-httplib decodes, so both representations
  12729. // take the pass-through path rather than one of them being gunzipped once.
  12730. for (const char *path : {"/split", "/joined"}) {
  12731. auto res = cli.Get(path);
  12732. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12733. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12734. EXPECT_EQ(body, res->body) << path;
  12735. }
  12736. }
  12737. // Regression test for DoS vulnerability: a malicious server sending a response
  12738. // without Content-Length header must not cause unbounded memory consumption on
  12739. // the client side. The client should stop reading after a reasonable limit,
  12740. // similar to the server-side set_payload_max_length protection.
  12741. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12742. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12743. #ifndef _WIN32
  12744. signal(SIGPIPE, SIG_IGN);
  12745. #endif
  12746. auto server_thread = std::thread([] {
  12747. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12748. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12749. default_socket_options(srv);
  12750. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12751. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12752. sockaddr_in addr{};
  12753. addr.sin_family = AF_INET;
  12754. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12755. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12756. int opt = 1;
  12757. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12758. #ifdef _WIN32
  12759. reinterpret_cast<const char *>(&opt),
  12760. #else
  12761. &opt,
  12762. #endif
  12763. sizeof(opt));
  12764. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12765. ::listen(srv, 1);
  12766. sockaddr_in cli_addr{};
  12767. socklen_t cli_len = sizeof(cli_addr);
  12768. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12769. if (cli != INVALID_SOCKET) {
  12770. char buf[4096];
  12771. ::recv(cli, buf, sizeof(buf), 0);
  12772. // Malicious response: no Content-Length, no chunked encoding
  12773. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12774. "Connection: close\r\n"
  12775. "\r\n";
  12776. ::send(cli,
  12777. #ifdef _WIN32
  12778. static_cast<const char *>(response_header.c_str()),
  12779. static_cast<int>(response_header.size()),
  12780. #else
  12781. response_header.c_str(), response_header.size(),
  12782. #endif
  12783. 0);
  12784. // Send 10MB of data
  12785. std::string chunk(64 * 1024, 'A');
  12786. size_t total_sent = 0;
  12787. while (total_sent < MALICIOUS_DATA_SIZE) {
  12788. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12789. auto sent = ::send(cli,
  12790. #ifdef _WIN32
  12791. static_cast<const char *>(chunk.c_str()),
  12792. static_cast<int>(to_send),
  12793. #else
  12794. chunk.c_str(), to_send,
  12795. #endif
  12796. 0);
  12797. if (sent <= 0) break;
  12798. total_sent += static_cast<size_t>(sent);
  12799. }
  12800. detail::close_socket(cli);
  12801. }
  12802. detail::close_socket(srv);
  12803. });
  12804. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12805. size_t total_read = 0;
  12806. {
  12807. Client cli("127.0.0.1", PORT + 2);
  12808. cli.set_read_timeout(5, 0);
  12809. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12810. auto stream = cli.open_stream("GET", "/malicious");
  12811. ASSERT_TRUE(stream.is_valid());
  12812. char buffer[64 * 1024];
  12813. ssize_t n;
  12814. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12815. total_read += static_cast<size_t>(n);
  12816. }
  12817. } // StreamHandle and Client destroyed here, closing the socket
  12818. server_thread.join();
  12819. // With set_payload_max_length, the client must stop reading before consuming
  12820. // all 10MB. The read loop should be cut off at or near the configured limit.
  12821. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12822. << "Client read " << total_read << " bytes, exceeding the configured "
  12823. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12824. }
  12825. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12826. // the entire response body without truncation.
  12827. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12828. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12829. #ifndef _WIN32
  12830. signal(SIGPIPE, SIG_IGN);
  12831. #endif
  12832. auto server_thread = std::thread([] {
  12833. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12834. default_socket_options(srv);
  12835. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12836. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12837. sockaddr_in addr{};
  12838. addr.sin_family = AF_INET;
  12839. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12840. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12841. int opt = 1;
  12842. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12843. #ifdef _WIN32
  12844. reinterpret_cast<const char *>(&opt),
  12845. #else
  12846. &opt,
  12847. #endif
  12848. sizeof(opt));
  12849. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12850. ::listen(srv, 1);
  12851. sockaddr_in cli_addr{};
  12852. socklen_t cli_len = sizeof(cli_addr);
  12853. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12854. if (cli != INVALID_SOCKET) {
  12855. char buf[4096];
  12856. ::recv(cli, buf, sizeof(buf), 0);
  12857. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12858. "Connection: close\r\n"
  12859. "\r\n";
  12860. ::send(cli,
  12861. #ifdef _WIN32
  12862. static_cast<const char *>(response_header.c_str()),
  12863. static_cast<int>(response_header.size()),
  12864. #else
  12865. response_header.c_str(), response_header.size(),
  12866. #endif
  12867. 0);
  12868. std::string chunk(64 * 1024, 'A');
  12869. size_t total_sent = 0;
  12870. while (total_sent < DATA_SIZE) {
  12871. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12872. auto sent = ::send(cli,
  12873. #ifdef _WIN32
  12874. static_cast<const char *>(chunk.c_str()),
  12875. static_cast<int>(to_send),
  12876. #else
  12877. chunk.c_str(), to_send,
  12878. #endif
  12879. 0);
  12880. if (sent <= 0) break;
  12881. total_sent += static_cast<size_t>(sent);
  12882. }
  12883. #ifdef _WIN32
  12884. ::shutdown(cli, SD_SEND);
  12885. #else
  12886. ::shutdown(cli, SHUT_WR);
  12887. #endif
  12888. // Drain until the client closes its end, ensuring all data is delivered
  12889. char drain[1024];
  12890. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12891. detail::close_socket(cli);
  12892. }
  12893. detail::close_socket(srv);
  12894. });
  12895. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12896. size_t total_read = 0;
  12897. {
  12898. Client cli("127.0.0.1", PORT + 2);
  12899. cli.set_read_timeout(5, 0);
  12900. cli.set_payload_max_length(0); // 0 means no limit
  12901. auto stream = cli.open_stream("GET", "/data");
  12902. ASSERT_TRUE(stream.is_valid());
  12903. char buffer[64 * 1024];
  12904. ssize_t n;
  12905. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12906. total_read += static_cast<size_t>(n);
  12907. }
  12908. }
  12909. server_thread.join();
  12910. EXPECT_EQ(total_read, DATA_SIZE)
  12911. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12912. << " bytes without truncation, but only read " << total_read << " bytes.";
  12913. }
  12914. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12915. // enormous Content-Length must not cause the client to pre-allocate a huge
  12916. // response body buffer. The reservation is capped at payload_max_length_, and
  12917. // the read itself fails when the body exceeds the limit.
  12918. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12919. #ifndef _WIN32
  12920. signal(SIGPIPE, SIG_IGN);
  12921. #endif
  12922. auto server_thread = std::thread([] {
  12923. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12924. default_socket_options(srv);
  12925. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12926. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12927. sockaddr_in addr{};
  12928. addr.sin_family = AF_INET;
  12929. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12930. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12931. int opt = 1;
  12932. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12933. #ifdef _WIN32
  12934. reinterpret_cast<const char *>(&opt),
  12935. #else
  12936. &opt,
  12937. #endif
  12938. sizeof(opt));
  12939. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12940. ::listen(srv, 1);
  12941. sockaddr_in cli_addr{};
  12942. socklen_t cli_len = sizeof(cli_addr);
  12943. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12944. if (cli != INVALID_SOCKET) {
  12945. char buf[4096];
  12946. ::recv(cli, buf, sizeof(buf), 0);
  12947. // Malicious response: claim a 20GB body but send only a tiny payload.
  12948. std::string response = "HTTP/1.1 200 OK\r\n"
  12949. "Content-Length: 20000000000\r\n"
  12950. "\r\n"
  12951. "abc";
  12952. ::send(cli,
  12953. #ifdef _WIN32
  12954. static_cast<const char *>(response.c_str()),
  12955. static_cast<int>(response.size()),
  12956. #else
  12957. response.c_str(), response.size(),
  12958. #endif
  12959. 0);
  12960. detail::close_socket(cli);
  12961. }
  12962. detail::close_socket(srv);
  12963. });
  12964. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12965. {
  12966. Client cli("127.0.0.1", PORT + 2);
  12967. cli.set_read_timeout(5, 0);
  12968. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12969. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12970. // (server claims more bytes than payload_max_length permits), but it must
  12971. // not exhaust memory before getting there.
  12972. auto res = cli.Get("/malicious");
  12973. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12974. }
  12975. server_thread.join();
  12976. }
  12977. // Verify that content_receiver bypasses the default payload_max_length,
  12978. // allowing streaming downloads larger than 100MB without requiring an explicit
  12979. // set_payload_max_length call.
  12980. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12981. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12982. #ifndef _WIN32
  12983. signal(SIGPIPE, SIG_IGN);
  12984. #endif
  12985. auto server_thread = std::thread([] {
  12986. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12987. default_socket_options(srv);
  12988. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12989. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12990. sockaddr_in addr{};
  12991. addr.sin_family = AF_INET;
  12992. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12993. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12994. int opt = 1;
  12995. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12996. #ifdef _WIN32
  12997. reinterpret_cast<const char *>(&opt),
  12998. #else
  12999. &opt,
  13000. #endif
  13001. sizeof(opt));
  13002. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13003. ::listen(srv, 1);
  13004. sockaddr_in cli_addr{};
  13005. socklen_t cli_len = sizeof(cli_addr);
  13006. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13007. if (cli != INVALID_SOCKET) {
  13008. char buf[4096];
  13009. ::recv(cli, buf, sizeof(buf), 0);
  13010. // Response with Content-Length larger than default 100MB limit
  13011. auto content_length = std::to_string(DATA_SIZE);
  13012. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13013. "Content-Length: " +
  13014. content_length +
  13015. "\r\n"
  13016. "Connection: close\r\n"
  13017. "\r\n";
  13018. ::send(cli,
  13019. #ifdef _WIN32
  13020. static_cast<const char *>(response_header.c_str()),
  13021. static_cast<int>(response_header.size()),
  13022. #else
  13023. response_header.c_str(), response_header.size(),
  13024. #endif
  13025. 0);
  13026. std::string chunk(64 * 1024, 'A');
  13027. size_t total_sent = 0;
  13028. while (total_sent < DATA_SIZE) {
  13029. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13030. auto sent = ::send(cli,
  13031. #ifdef _WIN32
  13032. static_cast<const char *>(chunk.c_str()),
  13033. static_cast<int>(to_send),
  13034. #else
  13035. chunk.c_str(), to_send,
  13036. #endif
  13037. 0);
  13038. if (sent <= 0) break;
  13039. total_sent += static_cast<size_t>(sent);
  13040. }
  13041. detail::close_socket(cli);
  13042. }
  13043. detail::close_socket(srv);
  13044. });
  13045. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13046. size_t total_received = 0;
  13047. {
  13048. Client cli("127.0.0.1", PORT + 2);
  13049. cli.set_read_timeout(10, 0);
  13050. // Do NOT call set_payload_max_length — use the default 100MB limit
  13051. auto res =
  13052. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13053. total_received += data_length;
  13054. return true;
  13055. });
  13056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13057. EXPECT_EQ(StatusCode::OK_200, res->status);
  13058. }
  13059. server_thread.join();
  13060. EXPECT_EQ(total_received, DATA_SIZE)
  13061. << "With content_receiver, the client should read all " << DATA_SIZE
  13062. << " bytes despite the default 100MB payload_max_length, but only read "
  13063. << total_received << " bytes.";
  13064. }
  13065. // Verify that an explicit set_payload_max_length smaller than the response is
  13066. // enforced even when a content_receiver is used.
  13067. TEST(ClientVulnerabilityTest,
  13068. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13069. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13070. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13071. #ifndef _WIN32
  13072. signal(SIGPIPE, SIG_IGN);
  13073. #endif
  13074. auto server_thread = std::thread([] {
  13075. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13076. default_socket_options(srv);
  13077. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13078. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13079. sockaddr_in addr{};
  13080. addr.sin_family = AF_INET;
  13081. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13082. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13083. int opt = 1;
  13084. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13085. #ifdef _WIN32
  13086. reinterpret_cast<const char *>(&opt),
  13087. #else
  13088. &opt,
  13089. #endif
  13090. sizeof(opt));
  13091. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13092. ::listen(srv, 1);
  13093. sockaddr_in cli_addr{};
  13094. socklen_t cli_len = sizeof(cli_addr);
  13095. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13096. if (cli != INVALID_SOCKET) {
  13097. char buf[4096];
  13098. ::recv(cli, buf, sizeof(buf), 0);
  13099. auto content_length = std::to_string(DATA_SIZE);
  13100. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13101. "Content-Length: " +
  13102. content_length +
  13103. "\r\n"
  13104. "Connection: close\r\n"
  13105. "\r\n";
  13106. ::send(cli,
  13107. #ifdef _WIN32
  13108. static_cast<const char *>(response_header.c_str()),
  13109. static_cast<int>(response_header.size()),
  13110. #else
  13111. response_header.c_str(), response_header.size(),
  13112. #endif
  13113. 0);
  13114. std::string chunk(64 * 1024, 'A');
  13115. size_t total_sent = 0;
  13116. while (total_sent < DATA_SIZE) {
  13117. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13118. auto sent = ::send(cli,
  13119. #ifdef _WIN32
  13120. static_cast<const char *>(chunk.c_str()),
  13121. static_cast<int>(to_send),
  13122. #else
  13123. chunk.c_str(), to_send,
  13124. #endif
  13125. 0);
  13126. if (sent <= 0) break;
  13127. total_sent += static_cast<size_t>(sent);
  13128. }
  13129. detail::close_socket(cli);
  13130. }
  13131. detail::close_socket(srv);
  13132. });
  13133. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13134. size_t total_received = 0;
  13135. {
  13136. Client cli("127.0.0.1", PORT + 2);
  13137. cli.set_read_timeout(10, 0);
  13138. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13139. auto res =
  13140. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13141. total_received += data_length;
  13142. return true;
  13143. });
  13144. // Should fail because 200MB exceeds the explicit 150MB limit
  13145. EXPECT_FALSE(res);
  13146. }
  13147. server_thread.join();
  13148. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13149. << "Client with content_receiver should respect the explicit "
  13150. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13151. << total_received << " bytes.";
  13152. }
  13153. // Verify that an explicit set_payload_max_length larger than the response
  13154. // allows the content_receiver to read all data successfully.
  13155. TEST(ClientVulnerabilityTest,
  13156. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13157. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13158. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13159. #ifndef _WIN32
  13160. signal(SIGPIPE, SIG_IGN);
  13161. #endif
  13162. auto server_thread = std::thread([] {
  13163. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13164. default_socket_options(srv);
  13165. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13166. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13167. sockaddr_in addr{};
  13168. addr.sin_family = AF_INET;
  13169. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13170. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13171. int opt = 1;
  13172. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13173. #ifdef _WIN32
  13174. reinterpret_cast<const char *>(&opt),
  13175. #else
  13176. &opt,
  13177. #endif
  13178. sizeof(opt));
  13179. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13180. ::listen(srv, 1);
  13181. sockaddr_in cli_addr{};
  13182. socklen_t cli_len = sizeof(cli_addr);
  13183. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13184. if (cli != INVALID_SOCKET) {
  13185. char buf[4096];
  13186. ::recv(cli, buf, sizeof(buf), 0);
  13187. auto content_length = std::to_string(DATA_SIZE);
  13188. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13189. "Content-Length: " +
  13190. content_length +
  13191. "\r\n"
  13192. "Connection: close\r\n"
  13193. "\r\n";
  13194. ::send(cli,
  13195. #ifdef _WIN32
  13196. static_cast<const char *>(response_header.c_str()),
  13197. static_cast<int>(response_header.size()),
  13198. #else
  13199. response_header.c_str(), response_header.size(),
  13200. #endif
  13201. 0);
  13202. std::string chunk(64 * 1024, 'A');
  13203. size_t total_sent = 0;
  13204. while (total_sent < DATA_SIZE) {
  13205. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13206. auto sent = ::send(cli,
  13207. #ifdef _WIN32
  13208. static_cast<const char *>(chunk.c_str()),
  13209. static_cast<int>(to_send),
  13210. #else
  13211. chunk.c_str(), to_send,
  13212. #endif
  13213. 0);
  13214. if (sent <= 0) break;
  13215. total_sent += static_cast<size_t>(sent);
  13216. }
  13217. #ifdef _WIN32
  13218. ::shutdown(cli, SD_SEND);
  13219. #else
  13220. ::shutdown(cli, SHUT_WR);
  13221. #endif
  13222. char drain[1024];
  13223. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13224. detail::close_socket(cli);
  13225. }
  13226. detail::close_socket(srv);
  13227. });
  13228. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13229. size_t total_received = 0;
  13230. {
  13231. Client cli("127.0.0.1", PORT + 2);
  13232. cli.set_read_timeout(10, 0);
  13233. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13234. auto res =
  13235. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13236. total_received += data_length;
  13237. return true;
  13238. });
  13239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13240. EXPECT_EQ(StatusCode::OK_200, res->status);
  13241. }
  13242. server_thread.join();
  13243. EXPECT_EQ(total_received, DATA_SIZE)
  13244. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13245. << " bytes (larger than " << DATA_SIZE
  13246. << " bytes response), content_receiver should read all data, but only "
  13247. "read "
  13248. << total_received << " bytes.";
  13249. }
  13250. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13251. // Regression test for "zip bomb" attack on the client side: a malicious server
  13252. // sends a small gzip-compressed response that decompresses to a huge payload.
  13253. // The client must enforce payload_max_length on the decompressed size.
  13254. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13255. constexpr size_t DECOMPRESSED_SIZE =
  13256. 10 * 1024 * 1024; // 10MB after decompression
  13257. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13258. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13259. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13260. std::string compressed;
  13261. {
  13262. httplib::detail::gzip_compressor compressor;
  13263. bool ok =
  13264. compressor.compress(uncompressed.data(), uncompressed.size(),
  13265. /*last=*/true, [&](const char *buf, size_t len) {
  13266. compressed.append(buf, len);
  13267. return true;
  13268. });
  13269. ASSERT_TRUE(ok);
  13270. }
  13271. // Sanity: compressed data should be much smaller than the decompressed size
  13272. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13273. #ifndef _WIN32
  13274. signal(SIGPIPE, SIG_IGN);
  13275. #endif
  13276. // Set up the listening socket in the main thread so the server is guaranteed
  13277. // to be ready before the client connects (eliminates race condition).
  13278. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13279. default_socket_options(srv);
  13280. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13281. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13282. sockaddr_in addr{};
  13283. addr.sin_family = AF_INET;
  13284. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13285. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13286. int opt = 1;
  13287. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13288. #ifdef _WIN32
  13289. reinterpret_cast<const char *>(&opt),
  13290. #else
  13291. &opt,
  13292. #endif
  13293. sizeof(opt));
  13294. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13295. ASSERT_EQ(0, ::listen(srv, 1));
  13296. auto server_thread = std::thread([&compressed, srv] {
  13297. sockaddr_in cli_addr{};
  13298. socklen_t cli_len = sizeof(cli_addr);
  13299. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13300. if (cli != INVALID_SOCKET) {
  13301. // Read the full HTTP request (until \r\n\r\n)
  13302. char buf[4096];
  13303. size_t total = 0;
  13304. while (total < sizeof(buf)) {
  13305. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13306. if (n <= 0) break;
  13307. total += static_cast<size_t>(n);
  13308. // Check for end of headers
  13309. if (total >= 4) {
  13310. std::string req(buf, total);
  13311. if (req.find("\r\n\r\n") != std::string::npos) break;
  13312. }
  13313. }
  13314. // Malicious response: gzip-compressed body, no Content-Length
  13315. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13316. "Content-Encoding: gzip\r\n"
  13317. "Connection: close\r\n"
  13318. "\r\n";
  13319. ::send(cli,
  13320. #ifdef _WIN32
  13321. static_cast<const char *>(response_header.c_str()),
  13322. static_cast<int>(response_header.size()),
  13323. #else
  13324. response_header.c_str(), response_header.size(),
  13325. #endif
  13326. 0);
  13327. // Send the compressed payload (small on the wire, huge when decompressed)
  13328. size_t total_sent = 0;
  13329. while (total_sent < compressed.size()) {
  13330. auto to_send = std::min(compressed.size() - total_sent,
  13331. static_cast<size_t>(64 * 1024));
  13332. auto sent =
  13333. ::send(cli,
  13334. #ifdef _WIN32
  13335. static_cast<const char *>(compressed.c_str() + total_sent),
  13336. static_cast<int>(to_send),
  13337. #else
  13338. compressed.c_str() + total_sent, to_send,
  13339. #endif
  13340. 0);
  13341. if (sent <= 0) break;
  13342. total_sent += static_cast<size_t>(sent);
  13343. }
  13344. detail::close_socket(cli);
  13345. }
  13346. });
  13347. auto se = detail::scope_exit([&] {
  13348. detail::close_socket(srv);
  13349. server_thread.join();
  13350. });
  13351. size_t total_decompressed = 0;
  13352. {
  13353. Client cli("127.0.0.1", PORT + 3);
  13354. cli.set_read_timeout(5, 0);
  13355. cli.set_decompress(true);
  13356. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13357. auto stream = cli.open_stream("GET", "/zipbomb");
  13358. ASSERT_TRUE(stream.is_valid());
  13359. char buffer[64 * 1024];
  13360. ssize_t n;
  13361. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13362. total_decompressed += static_cast<size_t>(n);
  13363. }
  13364. }
  13365. // The decompressed size must be capped by payload_max_length. Without
  13366. // protection, the client would decompress the full 10MB from a tiny
  13367. // compressed payload, enabling a zip bomb DoS attack.
  13368. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13369. << "Client decompressed " << total_decompressed
  13370. << " bytes from a gzip response. The decompressed size should be "
  13371. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13372. }
  13373. #endif
  13374. TEST(HostAndPortPropertiesTest, NoSSL) {
  13375. httplib::Client cli("www.google.com", 1234);
  13376. ASSERT_EQ("www.google.com", cli.host());
  13377. ASSERT_EQ(1234, cli.port());
  13378. }
  13379. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13380. httplib::Client cli("www.google.com:1234");
  13381. ASSERT_EQ("www.google.com", cli.host());
  13382. ASSERT_EQ(1234, cli.port());
  13383. }
  13384. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13385. // Port number that overflows int — should not crash, client becomes invalid
  13386. httplib::Client cli("http://www.google.com:99999999999999999999");
  13387. ASSERT_FALSE(cli.is_valid());
  13388. }
  13389. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13390. // Port 99999 exceeds valid range (1-65535) — should not crash
  13391. httplib::Client cli("http://www.google.com:99999");
  13392. ASSERT_FALSE(cli.is_valid());
  13393. auto res = cli.Get("/");
  13394. EXPECT_FALSE(res);
  13395. EXPECT_EQ(Error::Connection, res.error());
  13396. }
  13397. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13398. httplib::Client cli("http://user:pass@localhost:1234");
  13399. ASSERT_FALSE(cli.is_valid());
  13400. EXPECT_FALSE(cli.Get("/"));
  13401. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13402. }
  13403. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13404. httplib::Client cli("http://www.google.com:80abc");
  13405. ASSERT_FALSE(cli.is_valid());
  13406. }
  13407. #ifdef CPPHTTPLIB_SSL_ENABLED
  13408. TEST(HostAndPortPropertiesTest, SSL) {
  13409. httplib::SSLClient cli("www.google.com");
  13410. ASSERT_EQ("www.google.com", cli.host());
  13411. ASSERT_EQ(443, cli.port());
  13412. }
  13413. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13414. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13415. std::string cert;
  13416. read_file(CA_CERT_FILE, cert);
  13417. httplib::SSLClient httplib_client("www.google.com");
  13418. // Load CA store first time
  13419. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13420. // Load CA store second time (update)
  13421. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13422. // Verify client is still valid and can make connections
  13423. httplib_client.enable_server_certificate_verification(true);
  13424. auto res = httplib_client.Get("/");
  13425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13426. // Google may return 200 or 301 depending on various factors
  13427. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13428. res->status == StatusCode::MovedPermanently_301);
  13429. }
  13430. TEST(SSLClientTest, ServerNameIndication_Online) {
  13431. auto host = "httpbingo.org";
  13432. auto path = std::string{"/get"};
  13433. SSLClient cli(host, 443);
  13434. auto res = cli.Get(path);
  13435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13436. ASSERT_EQ(StatusCode::OK_200, res->status);
  13437. }
  13438. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13439. // Use a site that will cause SSL verification failure due to self-signed cert
  13440. SSLClient cli("self-signed.badssl.com", 443);
  13441. cli.enable_server_certificate_verification(true);
  13442. auto res = cli.Get("/");
  13443. ASSERT_TRUE(!res);
  13444. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13445. // Verify backend error is captured for SSLServerVerification
  13446. // This occurs when certificate verification fails
  13447. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13448. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13449. EXPECT_NE(0UL, res.ssl_backend_error());
  13450. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13451. res.ssl_error());
  13452. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13453. #if !defined(_WIN32) || \
  13454. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13455. // On non-Windows or when Windows Schannel is disabled, the error comes
  13456. // from OpenSSL's verification
  13457. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13458. res.ssl_backend_error());
  13459. #endif
  13460. #endif
  13461. }
  13462. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13463. // Use a site where hostname doesn't match the certificate
  13464. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13465. SSLClient cli("wrong.host.badssl.com", 443);
  13466. cli.enable_server_certificate_verification(true);
  13467. cli.enable_server_hostname_verification(true);
  13468. auto res = cli.Get("/");
  13469. ASSERT_TRUE(!res);
  13470. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13471. // Verify backend error is captured for hostname verification failure
  13472. EXPECT_NE(0UL, res.ssl_backend_error());
  13473. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13474. res.ssl_error());
  13475. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13476. #if !defined(_WIN32) || \
  13477. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13478. // On non-Windows or when Windows Schannel is disabled, the error comes
  13479. // from OpenSSL's hostname verification
  13480. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13481. res.ssl_backend_error());
  13482. #endif
  13483. #endif
  13484. }
  13485. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13486. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13487. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13488. SSLClient cli("www.google.com", 443);
  13489. cli.enable_server_certificate_verification(true);
  13490. auto res = cli.Get("/");
  13491. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13492. }
  13493. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13494. SSLClient cli("www.google.com", 443);
  13495. cli.enable_server_certificate_verification(true);
  13496. cli.enable_windows_certificate_verification(false);
  13497. auto res = cli.Get("/");
  13498. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13499. }
  13500. // The server sends an intermediate cross-signed by a root Windows trusts,
  13501. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13502. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13503. SSLClient cli("accounts.spotify.com", 443);
  13504. auto res = cli.Get("/");
  13505. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13506. << " ssl_backend_error=" << res.ssl_backend_error();
  13507. }
  13508. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13509. // policy status, which no backend reports for a self-signed certificate.
  13510. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13511. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13512. ASSERT_TRUE(svr.is_valid());
  13513. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13514. auto se = detail::scope_exit([&] {
  13515. svr.stop();
  13516. t.join();
  13517. ASSERT_FALSE(svr.is_running());
  13518. });
  13519. svr.wait_until_ready();
  13520. SSLClient cli("127.0.0.1", PORT);
  13521. cli.set_connection_timeout(30);
  13522. auto res = cli.Get("/");
  13523. ASSERT_FALSE(res);
  13524. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13525. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13526. }
  13527. #endif
  13528. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13529. Client cli("https://google.com");
  13530. auto res = cli.Get("/");
  13531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13532. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13533. }
  13534. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13535. SSLClient cli("google.com");
  13536. cli.set_ca_cert_path(CA_CERT_FILE);
  13537. auto res = cli.Get("/");
  13538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13539. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13540. }
  13541. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13542. SSLClient cli("google.com");
  13543. cli.enable_server_certificate_verification(true);
  13544. cli.set_ca_cert_path("hello");
  13545. auto res = cli.Get("/");
  13546. ASSERT_TRUE(!res);
  13547. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13548. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13549. // should be set
  13550. EXPECT_EQ(0, res.ssl_error());
  13551. // Verify backend error is captured for SSLLoadingCerts
  13552. // This error occurs when loading CA certificates fails
  13553. EXPECT_NE(0UL, res.ssl_backend_error());
  13554. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13555. // OpenSSL specific error codes:
  13556. // > openssl errstr 0x80000002
  13557. // error:80000002:system library::No such file or directory
  13558. // > openssl errstr 0xA000126
  13559. // error:0A000126:SSL routines::unexpected eof while reading
  13560. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13561. res.ssl_backend_error() == 0xA000126);
  13562. #endif
  13563. }
  13564. TEST(SSLClientTest, ServerCertificateVerification4) {
  13565. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13566. ASSERT_TRUE(svr.is_valid());
  13567. svr.Get("/test", [&](const Request &, Response &res) {
  13568. res.set_content("test", "text/plain");
  13569. svr.stop();
  13570. ASSERT_TRUE(true);
  13571. });
  13572. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13573. auto se = detail::scope_exit([&] {
  13574. t.join();
  13575. ASSERT_FALSE(svr.is_running());
  13576. });
  13577. svr.wait_until_ready();
  13578. SSLClient cli("127.0.0.1", PORT);
  13579. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13580. cli.enable_server_certificate_verification(true);
  13581. cli.set_connection_timeout(30);
  13582. auto res = cli.Get("/test");
  13583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13584. ASSERT_EQ(StatusCode::OK_200, res->status);
  13585. }
  13586. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13587. std::string cert;
  13588. read_file(CA_CERT_FILE, cert);
  13589. SSLClient cli("google.com");
  13590. cli.load_ca_cert_store(cert.data(), cert.size());
  13591. const auto res = cli.Get("/");
  13592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13593. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13594. }
  13595. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13596. // clang-format off
  13597. static constexpr char cert[] =
  13598. "GlobalSign Root CA\n"
  13599. "==================\n"
  13600. "-----BEGIN CERTIFICATE-----\n"
  13601. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13602. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13603. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13604. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13605. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13606. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13607. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13608. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13609. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13610. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13611. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13612. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13613. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13614. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13615. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13616. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13617. "-----END CERTIFICATE-----\n";
  13618. // clang-format on
  13619. SSLClient cli("google.com");
  13620. cli.load_ca_cert_store(cert, sizeof(cert));
  13621. const auto res = cli.Get("/");
  13622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13623. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13624. }
  13625. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13626. SSLClient cli("www.youtube.com");
  13627. cli.set_ca_cert_path(CA_CERT_FILE);
  13628. cli.enable_server_certificate_verification(true);
  13629. cli.set_follow_location(true);
  13630. auto res = cli.Get("/");
  13631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13632. ASSERT_EQ(StatusCode::OK_200, res->status);
  13633. }
  13634. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13635. SSLClient cli("wWw.YouTube.Com");
  13636. cli.set_ca_cert_path(CA_CERT_FILE);
  13637. cli.enable_server_certificate_verification(true);
  13638. cli.enable_server_hostname_verification(true);
  13639. cli.set_follow_location(true);
  13640. auto res = cli.Get("/");
  13641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13642. ASSERT_EQ(StatusCode::OK_200, res->status);
  13643. }
  13644. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13645. SSLClient cli("gOoGlE.COm");
  13646. cli.enable_server_certificate_verification(true);
  13647. cli.enable_server_hostname_verification(true);
  13648. cli.set_follow_location(true);
  13649. auto res = cli.Get("/");
  13650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13651. ASSERT_EQ(StatusCode::OK_200, res->status);
  13652. }
  13653. TEST(SSLClientTest, Issue2004_Online) {
  13654. Client client("https://google.com");
  13655. client.set_follow_location(true);
  13656. auto res = client.Get("/");
  13657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13658. ASSERT_EQ(StatusCode::OK_200, res->status);
  13659. auto body = res->body;
  13660. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13661. }
  13662. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13663. // Create SSLClient with invalid cert/key to make is_valid() return false
  13664. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13665. "nonexistent_key.pem");
  13666. // is_valid() should be false due to cert loading failure
  13667. ASSERT_FALSE(cli.is_valid());
  13668. auto res = cli.Get("/");
  13669. ASSERT_FALSE(res);
  13670. EXPECT_EQ(Error::SSLConnection, res.error());
  13671. }
  13672. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13673. // Test for Issue #2251: SSL error not properly reported when client cert
  13674. // and key paths are swapped or mismatched
  13675. // This simulates the scenario where user accidentally swaps the cert and key
  13676. // files
  13677. // Using client cert file as private key and vice versa (completely wrong)
  13678. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13679. // Should fail validation due to cert/key mismatch
  13680. ASSERT_FALSE(cli.is_valid());
  13681. // Attempt to make a request should fail with proper error
  13682. auto res = cli.Get("/");
  13683. ASSERT_FALSE(res);
  13684. EXPECT_EQ(Error::SSLConnection, res.error());
  13685. // SSL error should be recorded in the Result object (this is the key fix for
  13686. // Issue #2251)
  13687. auto backend_error = res.ssl_backend_error();
  13688. EXPECT_NE(0u, backend_error);
  13689. }
  13690. // Tests cert/key mismatch detection at the TLS context level
  13691. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13692. // Test that using mismatched cert/key causes connection failure.
  13693. // We verify this at the SSLClient level rather than through internal
  13694. // TLS API functions.
  13695. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13696. cli.enable_server_certificate_verification(false);
  13697. cli.set_connection_timeout(2);
  13698. // The mismatch should cause a connection or handshake error
  13699. auto res = cli.Get("/test");
  13700. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13701. // Either way, the request should fail
  13702. EXPECT_FALSE(res);
  13703. }
  13704. #endif
  13705. #if 0
  13706. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13707. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13708. ASSERT_TRUE(cli != nullptr);
  13709. cli->set_address_family(AF_INET6);
  13710. cli->set_interface("en0");
  13711. auto res = cli->Get("/get");
  13712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13713. ASSERT_EQ(StatusCode::OK_200, res->status);
  13714. }
  13715. #endif
  13716. // Client certificate tests - work with all TLS backends
  13717. #ifdef CPPHTTPLIB_SSL_ENABLED
  13718. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13719. void ClientCertPresent(
  13720. const std::string &client_cert_file,
  13721. const std::string &client_private_key_file,
  13722. const std::string &client_encrypted_private_key_pass = std::string(),
  13723. const ClientCertServerSetup &setup = nullptr) {
  13724. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13725. ASSERT_TRUE(svr.is_valid());
  13726. if (setup) { setup(svr); }
  13727. svr.Get("/test", [&](const Request &req, Response &res) {
  13728. res.set_content("test", "text/plain");
  13729. auto cert = req.peer_cert();
  13730. ASSERT_TRUE(static_cast<bool>(cert));
  13731. std::string common_name = cert.subject_cn();
  13732. EXPECT_EQ("Common Name", common_name);
  13733. });
  13734. auto port = svr.bind_to_any_port(HOST);
  13735. ASSERT_LT(0, port);
  13736. thread t = thread([&]() { svr.listen_after_bind(); });
  13737. auto se = detail::scope_exit([&] {
  13738. svr.stop();
  13739. t.join();
  13740. ASSERT_FALSE(svr.is_running());
  13741. });
  13742. svr.wait_until_ready();
  13743. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13744. client_encrypted_private_key_pass);
  13745. cli.enable_server_certificate_verification(false);
  13746. cli.set_connection_timeout(30);
  13747. auto res = cli.Get("/test");
  13748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13749. ASSERT_EQ(StatusCode::OK_200, res->status);
  13750. }
  13751. TEST(SSLClientServerTest, ClientCertPresent) {
  13752. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13753. }
  13754. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13755. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13756. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13757. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13758. }
  13759. // Expects svr, which must require client certificates, to reject a client
  13760. // that has none
  13761. void RejectsClientWithoutCert(SSLServer &svr) {
  13762. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13763. auto port = svr.bind_to_any_port(HOST);
  13764. ASSERT_LT(0, port);
  13765. thread t = thread([&]() { svr.listen_after_bind(); });
  13766. auto se = detail::scope_exit([&] {
  13767. svr.stop();
  13768. t.join();
  13769. ASSERT_FALSE(svr.is_running());
  13770. });
  13771. svr.wait_until_ready();
  13772. SSLClient cli(HOST, port);
  13773. cli.set_connection_timeout(30);
  13774. // Skip the server certificate check, so that the request fails because the
  13775. // client certificate is missing rather than because cert.pem is not trusted
  13776. cli.enable_server_certificate_verification(false);
  13777. auto res = cli.Get("/test");
  13778. ASSERT_FALSE(res);
  13779. // The server rejects the client during the handshake, or on TLS 1.3 right
  13780. // after it, which the client notices on its first write or read
  13781. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13782. res.error() == Error::Write || res.error() == Error::Read)
  13783. << to_string(res.error());
  13784. if (res.error() == Error::SSLConnection) {
  13785. EXPECT_NE(0UL, res.ssl_backend_error());
  13786. }
  13787. // A rejection noticed on the write keeps the TLS error the write hit
  13788. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13789. }
  13790. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13791. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13792. ASSERT_TRUE(svr.is_valid());
  13793. if (setup) { setup(svr); }
  13794. RejectsClientWithoutCert(svr);
  13795. }
  13796. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13797. // A server that requires client certificates must keep requiring them after
  13798. // setup changes it, and keep accepting a client that has one
  13799. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13800. ClientCertMissing(setup);
  13801. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13802. setup);
  13803. }
  13804. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13805. ClientCertStillRequired([](SSLServer &svr) {
  13806. ASSERT_TRUE(tls::set_verify_callback(
  13807. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13808. });
  13809. }
  13810. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13811. ClientCertStillRequired([](SSLServer &svr) {
  13812. ASSERT_TRUE(tls::set_verify_callback(
  13813. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13814. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13815. });
  13816. }
  13817. // The client verifies the server certificate during the handshake, so a
  13818. // server that fails the check never gets the client certificate, even when a
  13819. // verifier of the client's own accepts it
  13820. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13821. struct Case {
  13822. const char *trusted_ca;
  13823. const char *host;
  13824. Error error;
  13825. };
  13826. // cert2.pem names localhost: the first client does not trust it, and the
  13827. // second trusts it but asks for another name
  13828. for (const auto &c :
  13829. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13830. Case{SERVER_CERT2_FILE, "example.com",
  13831. Error::SSLServerHostnameVerification}}) {
  13832. for (auto with_verifier : {false, true}) {
  13833. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13834. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13835. CLIENT_CA_CERT_FILE);
  13836. ASSERT_TRUE(svr.is_valid());
  13837. std::atomic<bool> got_client_cert{false};
  13838. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13839. [&](const tls::VerifyContext &) {
  13840. got_client_cert = true;
  13841. return true;
  13842. }));
  13843. auto port = svr.bind_to_any_port("127.0.0.1");
  13844. ASSERT_LT(0, port);
  13845. thread t = thread([&] { svr.listen_after_bind(); });
  13846. svr.wait_until_ready();
  13847. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13848. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13849. cli.set_ca_cert_path(c.trusted_ca);
  13850. if (with_verifier) {
  13851. cli.set_server_certificate_verifier(
  13852. [](const tls::VerifyContext &) { return true; });
  13853. }
  13854. auto res = cli.Get("/");
  13855. EXPECT_FALSE(res);
  13856. EXPECT_EQ(c.error, res.error());
  13857. svr.stop();
  13858. t.join();
  13859. EXPECT_FALSE(got_client_cert);
  13860. }
  13861. }
  13862. }
  13863. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13864. std::string cert_pem, key_pem, ca_pem;
  13865. read_file(SERVER_CERT_FILE, cert_pem);
  13866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13867. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13868. ASSERT_TRUE(
  13869. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13870. }
  13871. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13872. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13873. ASSERT_TRUE(svr.is_valid());
  13874. UpdateCertsPemWithClientCA(svr);
  13875. RejectsClientWithoutCert(svr);
  13876. }
  13877. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13878. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13879. }
  13880. // A TLS error from one request must not show up in a later request's Result
  13881. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13883. ASSERT_TRUE(svr.is_valid());
  13884. svr.Get("/test", [](const Request &, Response &res) {
  13885. res.set_content("test", "text/plain");
  13886. });
  13887. auto port = svr.bind_to_any_port(HOST);
  13888. ASSERT_LT(0, port);
  13889. thread t = thread([&]() { svr.listen_after_bind(); });
  13890. auto se = detail::scope_exit([&] {
  13891. svr.stop();
  13892. t.join();
  13893. ASSERT_FALSE(svr.is_running());
  13894. });
  13895. svr.wait_until_ready();
  13896. SSLClient cli(HOST, port);
  13897. cli.set_connection_timeout(30);
  13898. cli.enable_server_hostname_verification(false);
  13899. // cert.pem is not trusted, so the handshake fails
  13900. ASSERT_FALSE(cli.Get("/test"));
  13901. cli.enable_server_certificate_verification(false);
  13902. auto res = cli.Get("/test");
  13903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13904. EXPECT_EQ(0, res.ssl_error());
  13905. EXPECT_EQ(0UL, res.ssl_backend_error());
  13906. }
  13907. // PEM memory-based constructor tests (works with all TLS backends).
  13908. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13909. // terminator after it.
  13910. void PemMemoryClientCertPresent(
  13911. const std::string &client_cert_file,
  13912. const std::string &client_private_key_file,
  13913. const std::string &client_encrypted_private_key_pass = std::string(),
  13914. bool exact_size = false) {
  13915. // Read PEM files into memory
  13916. std::string server_cert_pem, server_key_pem;
  13917. std::string client_ca_pem;
  13918. std::string client_cert_pem, client_key_pem;
  13919. read_file(SERVER_CERT_FILE, server_cert_pem);
  13920. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13921. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13922. read_file(client_cert_file, client_cert_pem);
  13923. read_file(client_private_key_file, client_key_pem);
  13924. std::list<std::vector<char>> exact_copies;
  13925. auto data = [&](const std::string &pem) -> const char * {
  13926. if (!exact_size) { return pem.c_str(); }
  13927. exact_copies.emplace_back(pem.begin(), pem.end());
  13928. return exact_copies.back().data();
  13929. };
  13930. // Create server with PEM memory
  13931. SSLServer::PemMemory server_pem = {
  13932. data(server_cert_pem),
  13933. server_cert_pem.size(),
  13934. data(server_key_pem),
  13935. server_key_pem.size(),
  13936. data(client_ca_pem),
  13937. client_ca_pem.size(),
  13938. nullptr // no password for server key
  13939. };
  13940. SSLServer svr(server_pem);
  13941. ASSERT_TRUE(svr.is_valid());
  13942. svr.Get("/test", [&](const Request &req, Response &res) {
  13943. res.set_content("test", "text/plain");
  13944. auto cert = req.peer_cert();
  13945. ASSERT_TRUE(static_cast<bool>(cert));
  13946. EXPECT_EQ("Common Name", cert.subject_cn());
  13947. });
  13948. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13949. auto se = detail::scope_exit([&] {
  13950. svr.stop();
  13951. t.join();
  13952. ASSERT_FALSE(svr.is_running());
  13953. });
  13954. svr.wait_until_ready();
  13955. // Create client with PEM memory
  13956. const char *password = client_encrypted_private_key_pass.empty()
  13957. ? nullptr
  13958. : client_encrypted_private_key_pass.c_str();
  13959. SSLClient::PemMemory client_pem = {
  13960. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13961. client_key_pem.size(), password};
  13962. SSLClient cli(HOST, PORT, client_pem);
  13963. cli.enable_server_certificate_verification(false);
  13964. cli.set_connection_timeout(30);
  13965. auto res = cli.Get("/test");
  13966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13967. ASSERT_EQ(StatusCode::OK_200, res->status);
  13968. }
  13969. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13970. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13971. }
  13972. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13973. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13974. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13975. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13976. }
  13977. // A server built from PEM memory with a client CA requires client certificates,
  13978. // also when the CA is a NUL-terminated string passed with a length of 0
  13979. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13980. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13981. read_file(SERVER_CERT_FILE, server_cert_pem);
  13982. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13983. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13984. SSLServer::PemMemory server_pem = {
  13985. server_cert_pem.c_str(),
  13986. server_cert_pem.size(),
  13987. server_key_pem.c_str(),
  13988. server_key_pem.size(),
  13989. client_ca_pem.c_str(),
  13990. client_ca_pem.size(),
  13991. nullptr // no password for server key
  13992. };
  13993. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13994. SCOPED_TRACE(client_ca_pem_len);
  13995. server_pem.client_ca_pem_len = client_ca_pem_len;
  13996. SSLServer svr(server_pem);
  13997. ASSERT_TRUE(svr.is_valid());
  13998. RejectsClientWithoutCert(svr);
  13999. }
  14000. // An empty CA fails to load instead of turning the check off
  14001. server_pem.client_ca_pem = "";
  14002. server_pem.client_ca_pem_len = 0;
  14003. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14004. }
  14005. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14006. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14007. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14008. true);
  14009. }
  14010. // A length shorter than the PEM cuts it short, so it no longer loads
  14011. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14012. std::string cert, key;
  14013. read_file(SERVER_CERT_FILE, cert);
  14014. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14015. for (auto cut_cert : {true, false}) {
  14016. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14017. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14018. SSLServer::PemMemory server_pem = {
  14019. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14020. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14021. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14022. key_len, nullptr};
  14023. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14024. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14025. key.c_str(), key_len, nullptr};
  14026. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14027. }
  14028. }
  14029. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14030. class NoListenSSLServer : public SSLServer {
  14031. public:
  14032. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14033. const char *client_ca_cert_file_path,
  14034. const char *client_ca_cert_dir_path = nullptr)
  14035. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14036. client_ca_cert_dir_path),
  14037. stop_(false) {}
  14038. std::atomic_bool stop_;
  14039. private:
  14040. bool process_and_close_socket(socket_t /*sock*/) override {
  14041. // Don't create SSL context
  14042. while (!stop_.load()) {
  14043. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14044. }
  14045. return true;
  14046. }
  14047. };
  14048. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14049. CLIENT_CA_CERT_FILE);
  14050. ASSERT_TRUE(svr.is_valid());
  14051. svr.Get("/test", [&](const Request &, Response &res) {
  14052. res.set_content("test", "text/plain");
  14053. });
  14054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14055. auto se = detail::scope_exit([&] {
  14056. svr.stop_ = true;
  14057. svr.stop();
  14058. t.join();
  14059. ASSERT_FALSE(svr.is_running());
  14060. });
  14061. svr.wait_until_ready();
  14062. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14063. cli.enable_server_certificate_verification(false);
  14064. cli.set_connection_timeout(1);
  14065. auto res = cli.Get("/test");
  14066. ASSERT_TRUE(!res);
  14067. EXPECT_EQ(Error::SSLConnection, res.error());
  14068. // Timeout results in WantRead error code (maps to backend-specific value)
  14069. EXPECT_NE(0, res.ssl_error());
  14070. }
  14071. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14072. // Test SSLServer with client certificate verification using the standard
  14073. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14075. CLIENT_CA_CERT_DIR);
  14076. ASSERT_TRUE(svr.is_valid());
  14077. svr.Get("/test", [&](const Request &req, Response &res) {
  14078. res.set_content("test", "text/plain");
  14079. auto cert = req.peer_cert();
  14080. ASSERT_TRUE(static_cast<bool>(cert));
  14081. auto common_name = cert.subject_cn();
  14082. EXPECT_EQ("Common Name", common_name);
  14083. });
  14084. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14085. auto se = detail::scope_exit([&] {
  14086. svr.stop();
  14087. t.join();
  14088. ASSERT_FALSE(svr.is_running());
  14089. });
  14090. svr.wait_until_ready();
  14091. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14092. cli.enable_server_certificate_verification(false);
  14093. cli.set_connection_timeout(30);
  14094. auto res = cli.Get("/test");
  14095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14096. ASSERT_EQ(StatusCode::OK_200, res->status);
  14097. }
  14098. // Test verify_hostname on every backend: a host is named by a SAN only
  14099. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14100. using namespace httplib::tls;
  14101. // We need a running server to test against
  14102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14103. ASSERT_TRUE(svr.is_valid());
  14104. svr.Get("/test", [](const Request &, Response &res) {
  14105. res.set_content("ok", "text/plain");
  14106. });
  14107. thread t([&]() { svr.listen(HOST, PORT); });
  14108. auto se = detail::scope_exit([&] {
  14109. svr.stop();
  14110. t.join();
  14111. });
  14112. svr.wait_until_ready();
  14113. bool verify_callback_called = false;
  14114. bool verify_result_wrong = false;
  14115. SSLClient cli(HOST, PORT);
  14116. cli.enable_server_certificate_verification(true);
  14117. cli.set_ca_cert_path(CA_CERT_FILE);
  14118. cli.set_connection_timeout(5);
  14119. // Note: Test certificate has CN="Common Name", not "localhost"
  14120. bool verify_result_cn = false;
  14121. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14122. verify_callback_called = true;
  14123. if (!ctx.cert) return false;
  14124. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14125. verify_result_cn = ctx.check_hostname("Common Name");
  14126. // Test 2: wrong hostname should not match
  14127. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14128. return true; // Accept for the purpose of this test
  14129. });
  14130. auto res = cli.Get("/test");
  14131. // The request may succeed or fail depending on cert configuration
  14132. // but the callback should have been called
  14133. ASSERT_TRUE(verify_callback_called)
  14134. << "Verify callback should have been called";
  14135. EXPECT_FALSE(verify_result_cn)
  14136. << "verify_hostname must not match the certificate CN (no SAN)";
  14137. // Wrong hostname should not match
  14138. EXPECT_FALSE(verify_result_wrong)
  14139. << "verify_hostname should not match 'wronghost.example.com'";
  14140. }
  14141. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14142. // backend verifies it.
  14143. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14144. // Certificate CN is "localhost" and it carries no SAN.
  14145. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14146. ASSERT_TRUE(svr.is_valid());
  14147. svr.Get("/test", [](const Request &, Response &res) {
  14148. res.set_content("ok", "text/plain");
  14149. });
  14150. auto port = svr.bind_to_any_port(HOST);
  14151. thread t([&]() { svr.listen_after_bind(); });
  14152. auto se = detail::scope_exit([&] {
  14153. svr.stop();
  14154. t.join();
  14155. });
  14156. svr.wait_until_ready();
  14157. SSLClient cli("localhost", port);
  14158. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14159. cli.enable_server_certificate_verification(true);
  14160. cli.set_connection_timeout(5);
  14161. auto res = cli.Get("/test");
  14162. ASSERT_FALSE(res);
  14163. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14164. // The same certificate is accepted once host name verification is off, so the
  14165. // failure above is the host name and not the chain.
  14166. cli.enable_server_hostname_verification(false);
  14167. res = cli.Get("/test");
  14168. ASSERT_TRUE(res) << to_string(res.error());
  14169. EXPECT_EQ(StatusCode::OK_200, res->status);
  14170. }
  14171. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14172. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14173. // X509_check_ip behavior and must hold for every backend.
  14174. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14175. using namespace httplib::tls;
  14176. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14177. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14178. ASSERT_TRUE(svr.is_valid());
  14179. svr.Get("/test", [](const Request &, Response &res) {
  14180. res.set_content("ok", "text/plain");
  14181. });
  14182. thread t([&]() { svr.listen(HOST, PORT); });
  14183. auto se = detail::scope_exit([&] {
  14184. svr.stop();
  14185. t.join();
  14186. });
  14187. svr.wait_until_ready();
  14188. bool verify_callback_called = false;
  14189. bool ip_matched_via_cn = true;
  14190. SSLClient cli(HOST, PORT);
  14191. cli.enable_server_certificate_verification(true);
  14192. cli.set_ca_cert_path(CA_CERT_FILE);
  14193. cli.set_connection_timeout(5);
  14194. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14195. verify_callback_called = true;
  14196. if (!ctx.cert) return false;
  14197. // The IP appears only in the CN, so it must NOT be accepted.
  14198. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14199. return true; // Accept for the purpose of this test
  14200. });
  14201. cli.Get("/test");
  14202. ASSERT_TRUE(verify_callback_called)
  14203. << "Verify callback should have been called";
  14204. EXPECT_FALSE(ip_matched_via_cn)
  14205. << "An IP host must not be authenticated via the certificate CN";
  14206. }
  14207. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14208. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14209. using namespace httplib::tls;
  14210. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14211. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14212. ASSERT_TRUE(svr.is_valid());
  14213. svr.Get("/test", [](const Request &, Response &res) {
  14214. res.set_content("ok", "text/plain");
  14215. });
  14216. thread t([&]() { svr.listen(HOST, PORT); });
  14217. auto se = detail::scope_exit([&] {
  14218. svr.stop();
  14219. t.join();
  14220. });
  14221. svr.wait_until_ready();
  14222. bool verify_callback_called = false;
  14223. bool san_matched = false;
  14224. bool wrong_ipv6_matched = true;
  14225. bool cn_ipv6_matched = true;
  14226. SSLClient cli(HOST, PORT);
  14227. cli.enable_server_certificate_verification(true);
  14228. cli.set_ca_cert_path(CA_CERT_FILE);
  14229. cli.set_connection_timeout(5);
  14230. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14231. verify_callback_called = true;
  14232. if (!ctx.cert) return false;
  14233. // Matches the IPv6 iPAddress SAN.
  14234. san_matched = ctx.check_hostname("2001:db8::1");
  14235. // A different IPv6 address must not match.
  14236. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14237. // "::1" lives only in the CN, so it must not be accepted.
  14238. cn_ipv6_matched = ctx.check_hostname("::1");
  14239. return true; // Accept for the purpose of this test
  14240. });
  14241. cli.Get("/test");
  14242. ASSERT_TRUE(verify_callback_called)
  14243. << "Verify callback should have been called";
  14244. EXPECT_TRUE(san_matched)
  14245. << "verify_hostname should match an IPv6 iPAddress SAN";
  14246. EXPECT_FALSE(wrong_ipv6_matched)
  14247. << "verify_hostname should not match a non-matching IPv6 address";
  14248. EXPECT_FALSE(cn_ipv6_matched)
  14249. << "An IPv6 host must not be authenticated via the certificate CN";
  14250. }
  14251. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14252. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14253. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14254. using namespace httplib::tls;
  14255. // SANs: DNS:a.zz, IP:42.46.122.122
  14256. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14257. ASSERT_TRUE(svr.is_valid());
  14258. svr.Get("/test", [](const Request &, Response &res) {
  14259. res.set_content("ok", "text/plain");
  14260. });
  14261. auto port = svr.bind_to_any_port(HOST);
  14262. thread t([&]() { svr.listen_after_bind(); });
  14263. auto se = detail::scope_exit([&] {
  14264. svr.stop();
  14265. t.join();
  14266. });
  14267. svr.wait_until_ready();
  14268. bool verify_callback_called = false;
  14269. bool dns_san_matched = false;
  14270. bool ip_san_matched = false;
  14271. bool ip_matched_via_dns_san = true;
  14272. bool dns_matched_via_ip_san = true;
  14273. bool cn_matched_next_to_dns_san = true;
  14274. SSLClient cli(HOST, port);
  14275. cli.enable_server_certificate_verification(true);
  14276. cli.set_ca_cert_path(CA_CERT_FILE);
  14277. cli.set_connection_timeout(5);
  14278. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14279. verify_callback_called = true;
  14280. if (!ctx.cert) return false;
  14281. dns_san_matched = ctx.check_hostname("a.zz");
  14282. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14283. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14284. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14285. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14286. return true; // Accept for the purpose of this test
  14287. });
  14288. cli.Get("/test");
  14289. ASSERT_TRUE(verify_callback_called)
  14290. << "Verify callback should have been called";
  14291. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14292. EXPECT_TRUE(ip_san_matched)
  14293. << "verify_hostname should match an iPAddress SAN";
  14294. EXPECT_FALSE(ip_matched_via_dns_san)
  14295. << "An IP host must not be authenticated via a dNSName SAN";
  14296. EXPECT_FALSE(dns_matched_via_ip_san)
  14297. << "A DNS host must not be authenticated via an iPAddress SAN";
  14298. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14299. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14300. }
  14301. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14302. // "www.*.example.test" names one host and not every host under example.test.
  14303. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14304. using namespace httplib::tls;
  14305. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14306. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14307. ASSERT_TRUE(svr.is_valid());
  14308. svr.Get("/test", [](const Request &, Response &res) {
  14309. res.set_content("ok", "text/plain");
  14310. });
  14311. auto port = svr.bind_to_any_port(HOST);
  14312. thread t([&]() { svr.listen_after_bind(); });
  14313. auto se = detail::scope_exit([&] {
  14314. svr.stop();
  14315. t.join();
  14316. });
  14317. svr.wait_until_ready();
  14318. bool verify_callback_called = false;
  14319. bool leftmost_wildcard_matched = false;
  14320. bool wildcard_spanned_labels = true;
  14321. bool inner_wildcard_matched = true;
  14322. SSLClient cli(HOST, port);
  14323. cli.enable_server_certificate_verification(true);
  14324. cli.set_ca_cert_path(CA_CERT_FILE);
  14325. cli.set_connection_timeout(5);
  14326. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14327. verify_callback_called = true;
  14328. if (!ctx.cert) return false;
  14329. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14330. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14331. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14332. return true; // Accept for the purpose of this test
  14333. });
  14334. cli.Get("/test");
  14335. ASSERT_TRUE(verify_callback_called)
  14336. << "Verify callback should have been called";
  14337. EXPECT_TRUE(leftmost_wildcard_matched)
  14338. << "A leftmost wildcard should match a single label";
  14339. EXPECT_FALSE(wildcard_spanned_labels)
  14340. << "A wildcard label must not match more than one label";
  14341. EXPECT_FALSE(inner_wildcard_matched)
  14342. << "A wildcard outside the leftmost label must not be honoured";
  14343. }
  14344. // sans() must report each SAN entry under its own type.
  14345. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14346. using namespace httplib::tls;
  14347. // SANs: DNS:a.zz, IP:42.46.122.122
  14348. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14349. ASSERT_TRUE(svr.is_valid());
  14350. svr.Get("/test", [](const Request &, Response &res) {
  14351. res.set_content("ok", "text/plain");
  14352. });
  14353. auto port = svr.bind_to_any_port(HOST);
  14354. thread t([&]() { svr.listen_after_bind(); });
  14355. auto se = detail::scope_exit([&] {
  14356. svr.stop();
  14357. t.join();
  14358. });
  14359. svr.wait_until_ready();
  14360. bool verify_callback_called = false;
  14361. std::vector<SanEntry> sans;
  14362. SSLClient cli(HOST, port);
  14363. cli.enable_server_certificate_verification(true);
  14364. cli.set_ca_cert_path(CA_CERT_FILE);
  14365. cli.set_connection_timeout(5);
  14366. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14367. verify_callback_called = true;
  14368. if (!ctx.cert) return false;
  14369. sans = ctx.sans();
  14370. return true; // Accept for the purpose of this test
  14371. });
  14372. cli.Get("/test");
  14373. ASSERT_TRUE(verify_callback_called)
  14374. << "Verify callback should have been called";
  14375. auto has_san = [&](SanType type, const std::string &value) {
  14376. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14377. return san.type == type && san.value == value;
  14378. });
  14379. };
  14380. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14381. << "sans() should report the dNSName SAN";
  14382. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14383. << "sans() should report the iPAddress SAN";
  14384. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14385. << "sans() must not report the dNSName SAN as an address";
  14386. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14387. << "sans() must not report the iPAddress SAN as a DNS name";
  14388. }
  14389. #endif
  14390. // mbedTLS-specific callback constructor test
  14391. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14392. #ifdef CPPHTTPLIB_SSL_ENABLED
  14393. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14394. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14395. ASSERT_TRUE(svr.is_valid());
  14396. // Set up a handler to verify client certificate is present
  14397. bool client_cert_verified = false;
  14398. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14399. // Verify that client certificate was provided
  14400. client_cert_verified = true;
  14401. res.set_content("success", "text/plain");
  14402. });
  14403. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14404. auto se = detail::scope_exit([&] {
  14405. svr.stop();
  14406. t.join();
  14407. ASSERT_FALSE(svr.is_running());
  14408. });
  14409. svr.wait_until_ready();
  14410. // Client with certificate
  14411. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14412. cli.enable_server_certificate_verification(false);
  14413. cli.set_connection_timeout(30);
  14414. auto res = cli.Get("/test");
  14415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14416. ASSERT_EQ(StatusCode::OK_200, res->status);
  14417. ASSERT_TRUE(client_cert_verified);
  14418. EXPECT_EQ("success", res->body);
  14419. }
  14420. #endif
  14421. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14422. // backends
  14423. #ifdef CPPHTTPLIB_SSL_ENABLED
  14424. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14425. using namespace httplib::tls;
  14426. // Test that when client CA cert file is provided,
  14427. // the server properly requests and validates client certificates
  14428. // Create a server with client authentication
  14429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14430. ASSERT_TRUE(svr.is_valid());
  14431. bool handler_called = false;
  14432. svr.Get("/test", [&](const Request &req, Response &res) {
  14433. handler_called = true;
  14434. // Verify that a client certificate was provided
  14435. auto cert = req.peer_cert();
  14436. ASSERT_TRUE(static_cast<bool>(cert));
  14437. // Get the issuer name
  14438. std::string issuer_str = cert.issuer_name();
  14439. ASSERT_FALSE(issuer_str.empty());
  14440. // The client certificate should be issued by our test CA
  14441. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14442. res.set_content("authenticated", "text/plain");
  14443. });
  14444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14445. auto se = detail::scope_exit([&] {
  14446. svr.stop();
  14447. t.join();
  14448. ASSERT_FALSE(svr.is_running());
  14449. });
  14450. svr.wait_until_ready();
  14451. // Connect with a client certificate issued by the CA
  14452. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14453. cli.enable_server_certificate_verification(false);
  14454. cli.set_connection_timeout(30);
  14455. auto res = cli.Get("/test");
  14456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14457. ASSERT_EQ(StatusCode::OK_200, res->status);
  14458. ASSERT_TRUE(handler_called);
  14459. EXPECT_EQ("authenticated", res->body);
  14460. }
  14461. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14462. using namespace httplib::tls;
  14463. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14464. ASSERT_TRUE(svr.is_valid());
  14465. svr.Get("/test", [](const Request &, Response &res) {
  14466. res.set_content("ok", "text/plain");
  14467. });
  14468. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14469. auto se = detail::scope_exit([&] {
  14470. svr.stop();
  14471. t.join();
  14472. });
  14473. svr.wait_until_ready();
  14474. SSLClient cli(HOST, PORT);
  14475. cli.enable_server_certificate_verification(false);
  14476. cli.set_connection_timeout(30);
  14477. bool cert_checked = false;
  14478. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14479. if (ctx.cert) {
  14480. auto sans = ctx.sans();
  14481. // Test certificate may or may not have SANs - just verify the API
  14482. // works If SANs exist, verify the types are valid
  14483. for (const auto &san : sans) {
  14484. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14485. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14486. san.type == SanType::OTHER);
  14487. EXPECT_FALSE(san.value.empty());
  14488. }
  14489. cert_checked = true;
  14490. }
  14491. return true;
  14492. });
  14493. auto res = cli.Get("/test");
  14494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14495. EXPECT_TRUE(cert_checked);
  14496. }
  14497. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14498. using namespace httplib::tls;
  14499. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14500. ASSERT_TRUE(svr.is_valid());
  14501. svr.Get("/test", [](const Request &, Response &res) {
  14502. res.set_content("ok", "text/plain");
  14503. });
  14504. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14505. auto se = detail::scope_exit([&] {
  14506. svr.stop();
  14507. t.join();
  14508. });
  14509. svr.wait_until_ready();
  14510. SSLClient cli(HOST, PORT);
  14511. cli.enable_server_certificate_verification(false);
  14512. cli.set_connection_timeout(30);
  14513. bool validity_checked = false;
  14514. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14515. if (ctx.cert) {
  14516. time_t not_before = 0, not_after = 0;
  14517. bool result = ctx.validity(not_before, not_after);
  14518. EXPECT_TRUE(result);
  14519. // Verify that not_before < now < not_after for a valid cert
  14520. time_t now = time(nullptr);
  14521. EXPECT_LT(not_before, now);
  14522. EXPECT_GT(not_after, now);
  14523. validity_checked = true;
  14524. }
  14525. return true;
  14526. });
  14527. auto res = cli.Get("/test");
  14528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14529. EXPECT_TRUE(validity_checked);
  14530. }
  14531. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14532. using namespace httplib::tls;
  14533. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14534. ASSERT_TRUE(svr.is_valid());
  14535. svr.Get("/test", [](const Request &, Response &res) {
  14536. res.set_content("ok", "text/plain");
  14537. });
  14538. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14539. auto se = detail::scope_exit([&] {
  14540. svr.stop();
  14541. t.join();
  14542. });
  14543. svr.wait_until_ready();
  14544. SSLClient cli(HOST, PORT);
  14545. cli.enable_server_certificate_verification(false);
  14546. cli.set_connection_timeout(30);
  14547. bool serial_checked = false;
  14548. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14549. if (ctx.cert) {
  14550. std::string serial = ctx.serial();
  14551. EXPECT_FALSE(serial.empty());
  14552. // Serial should be a hex string
  14553. for (char c : serial) {
  14554. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14555. (c >= 'a' && c <= 'f'));
  14556. }
  14557. serial_checked = true;
  14558. }
  14559. return true;
  14560. });
  14561. auto res = cli.Get("/test");
  14562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14563. EXPECT_TRUE(serial_checked);
  14564. }
  14565. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14566. // Test 1: Valid CA file - no error should be recorded
  14567. {
  14568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14569. CLIENT_CA_CERT_FILE);
  14570. ASSERT_TRUE(svr.is_valid());
  14571. // With valid setup, last_ssl_error should be 0
  14572. EXPECT_EQ(0, svr.ssl_last_error());
  14573. }
  14574. // Test 2: Invalid CA file content
  14575. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14576. {
  14577. // Create a temporary file with completely invalid content
  14578. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14579. {
  14580. std::ofstream ofs(temp_invalid_ca);
  14581. ofs << "This is not a certificate file at all\n";
  14582. ofs << "Just plain text content\n";
  14583. }
  14584. // Create server with invalid CA file
  14585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14586. // Clean up temporary file
  14587. std::remove(temp_invalid_ca);
  14588. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14589. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14590. // Note: SSL_CTX_load_verify_locations typically fails first,
  14591. // but our error handling code path is still exercised
  14592. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14593. }
  14594. }
  14595. TEST(VerifyCallbackTest, VerifyContextFields) {
  14596. using namespace httplib::tls;
  14597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14598. ASSERT_TRUE(svr.is_valid());
  14599. svr.Get("/test", [](const Request &, Response &res) {
  14600. res.set_content("ok", "text/plain");
  14601. });
  14602. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14603. auto se = detail::scope_exit([&] {
  14604. svr.stop();
  14605. t.join();
  14606. });
  14607. svr.wait_until_ready();
  14608. SSLClient cli(HOST, PORT);
  14609. cli.enable_server_certificate_verification(false);
  14610. cli.set_connection_timeout(30);
  14611. int callback_count = 0;
  14612. bool saw_leaf_cert = false;
  14613. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14614. if (ctx.cert) {
  14615. callback_count++;
  14616. // We should see at least one certificate (the leaf)
  14617. std::string cn = ctx.subject_cn();
  14618. if (!cn.empty()) { saw_leaf_cert = true; }
  14619. // Verify context fields are populated
  14620. EXPECT_NE(ctx.session, nullptr);
  14621. EXPECT_GE(ctx.depth, 0);
  14622. }
  14623. return true;
  14624. });
  14625. auto res = cli.Get("/test");
  14626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14627. EXPECT_GT(callback_count, 0);
  14628. EXPECT_TRUE(saw_leaf_cert);
  14629. }
  14630. // A verifier that accepts runs alongside the built-in verification, and is the
  14631. // only check once that is turned off.
  14632. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14633. using namespace httplib::tls;
  14634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14635. ASSERT_TRUE(svr.is_valid());
  14636. svr.Get("/test", [](const Request &, Response &res) {
  14637. res.set_content("ok", "text/plain");
  14638. });
  14639. auto port = svr.bind_to_any_port(HOST);
  14640. thread t([&]() { svr.listen_after_bind(); });
  14641. auto se = detail::scope_exit([&] {
  14642. svr.stop();
  14643. t.join();
  14644. });
  14645. svr.wait_until_ready();
  14646. SSLClient cli(HOST, port);
  14647. cli.enable_server_hostname_verification(false);
  14648. auto calls = 0;
  14649. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14650. calls++;
  14651. return true;
  14652. });
  14653. // cert.pem is not trusted
  14654. auto res = cli.Get("/test");
  14655. ASSERT_FALSE(res);
  14656. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14657. EXPECT_GT(calls, 0);
  14658. cli.enable_server_certificate_verification(false);
  14659. res = cli.Get("/test");
  14660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14661. EXPECT_EQ("ok", res->body);
  14662. }
  14663. // A verifier belongs to the client that set it, not to the thread that set it.
  14664. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14665. using namespace httplib::tls;
  14666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14667. ASSERT_TRUE(svr.is_valid());
  14668. svr.Get("/test", [](const Request &, Response &res) {
  14669. res.set_content("ok", "text/plain");
  14670. });
  14671. auto port = svr.bind_to_any_port(HOST);
  14672. thread t([&]() { svr.listen_after_bind(); });
  14673. auto se = detail::scope_exit([&] {
  14674. svr.stop();
  14675. t.join();
  14676. });
  14677. svr.wait_until_ready();
  14678. auto rejecting_calls = 0;
  14679. SSLClient rejecting(HOST, port);
  14680. rejecting.enable_server_certificate_verification(false);
  14681. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14682. rejecting_calls++;
  14683. return false;
  14684. });
  14685. auto accepting_calls = 0;
  14686. SSLClient accepting(HOST, port);
  14687. accepting.enable_server_certificate_verification(false);
  14688. // Set on another thread than the requests below.
  14689. thread([&]() {
  14690. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14691. accepting_calls++;
  14692. return true;
  14693. });
  14694. }).join();
  14695. // Requested on another thread than the verifier was set on.
  14696. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14697. EXPECT_GT(rejecting_calls, 0);
  14698. auto res = accepting.Get("/test");
  14699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14700. EXPECT_GT(accepting_calls, 0);
  14701. }
  14702. // A verifier replaced while a handshake runs it lives until it returns.
  14703. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14704. using namespace httplib::tls;
  14705. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14706. ASSERT_TRUE(svr.is_valid());
  14707. svr.Get("/test", [](const Request &, Response &res) {
  14708. res.set_content("ok", "text/plain");
  14709. });
  14710. auto port = svr.bind_to_any_port(HOST);
  14711. thread t([&]() { svr.listen_after_bind(); });
  14712. auto se = detail::scope_exit([&] {
  14713. svr.stop();
  14714. t.join();
  14715. });
  14716. svr.wait_until_ready();
  14717. SSLClient cli(HOST, port);
  14718. cli.enable_server_certificate_verification(false);
  14719. std::promise<void> entered;
  14720. std::promise<void> replaced;
  14721. auto replaced_future = replaced.get_future();
  14722. auto first_call = true;
  14723. // Long enough to live on the heap
  14724. std::string expected(64, 'v');
  14725. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14726. if (first_call) {
  14727. first_call = false;
  14728. entered.set_value();
  14729. replaced_future.wait();
  14730. }
  14731. return expected == std::string(64, 'v');
  14732. });
  14733. thread request([&]() {
  14734. auto res = cli.Get("/test");
  14735. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14736. });
  14737. entered.get_future().wait();
  14738. cli.set_server_certificate_verifier(
  14739. [](const VerifyContext &) { return true; });
  14740. replaced.set_value();
  14741. request.join();
  14742. }
  14743. // VerifyContext::session is the same handle the other tls:: functions take.
  14744. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14745. using namespace httplib::tls;
  14746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14747. ASSERT_TRUE(svr.is_valid());
  14748. svr.Get("/test", [](const Request &, Response &res) {
  14749. res.set_content("ok", "text/plain");
  14750. });
  14751. auto port = svr.bind_to_any_port(HOST);
  14752. thread t([&]() { svr.listen_after_bind(); });
  14753. auto se = detail::scope_exit([&] {
  14754. svr.stop();
  14755. t.join();
  14756. });
  14757. svr.wait_until_ready();
  14758. SSLClient cli(HOST, port);
  14759. cli.enable_server_certificate_verification(false);
  14760. session_t verifier_session = nullptr;
  14761. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14762. verifier_session = ctx.session;
  14763. return true;
  14764. });
  14765. session_t session_verifier_session = nullptr;
  14766. cli.set_session_verifier([&](session_t session) {
  14767. session_verifier_session = session;
  14768. return SSLVerifierResponse::NoDecisionMade;
  14769. });
  14770. auto res = cli.Get("/test");
  14771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14772. EXPECT_NE(nullptr, verifier_session);
  14773. EXPECT_EQ(session_verifier_session, verifier_session);
  14774. }
  14775. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14776. using httplib::tls::TlsError;
  14777. // Test that verify_error_to_string returns empty for success
  14778. std::string success_str = TlsError::verify_error_to_string(0);
  14779. EXPECT_TRUE(success_str.empty());
  14780. // Test that verify_error_to_string returns non-empty for error codes
  14781. // Using a common error code (certificate expired)
  14782. std::string error_str =
  14783. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14784. EXPECT_FALSE(error_str.empty());
  14785. }
  14786. TEST(SessionVerifierTest, CertificateAccepted) {
  14787. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14788. ASSERT_TRUE(svr.is_valid());
  14789. svr.Get("/test", [](const Request &, Response &res) {
  14790. res.set_content("ok", "text/plain");
  14791. });
  14792. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14793. auto se = detail::scope_exit([&] {
  14794. svr.stop();
  14795. t.join();
  14796. });
  14797. svr.wait_until_ready();
  14798. SSLClient cli(HOST, PORT);
  14799. cli.enable_server_certificate_verification(false);
  14800. cli.set_connection_timeout(30);
  14801. bool callback_called = false;
  14802. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14803. EXPECT_NE(session, nullptr);
  14804. callback_called = true;
  14805. return SSLVerifierResponse::CertificateAccepted;
  14806. });
  14807. auto res = cli.Get("/test");
  14808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14809. EXPECT_EQ(200, res->status);
  14810. EXPECT_TRUE(callback_called);
  14811. }
  14812. TEST(SessionVerifierTest, CertificateRejected) {
  14813. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14814. ASSERT_TRUE(svr.is_valid());
  14815. svr.Get("/test", [](const Request &, Response &res) {
  14816. res.set_content("ok", "text/plain");
  14817. });
  14818. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14819. auto se = detail::scope_exit([&] {
  14820. svr.stop();
  14821. t.join();
  14822. });
  14823. svr.wait_until_ready();
  14824. SSLClient cli(HOST, PORT);
  14825. cli.enable_server_certificate_verification(false);
  14826. cli.set_connection_timeout(30);
  14827. bool callback_called = false;
  14828. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14829. EXPECT_NE(session, nullptr);
  14830. callback_called = true;
  14831. return SSLVerifierResponse::CertificateRejected;
  14832. });
  14833. auto res = cli.Get("/test");
  14834. EXPECT_FALSE(res);
  14835. EXPECT_TRUE(callback_called);
  14836. }
  14837. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14838. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14839. ASSERT_TRUE(svr.is_valid());
  14840. svr.Get("/test", [](const Request &, Response &res) {
  14841. res.set_content("ok", "text/plain");
  14842. });
  14843. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14844. auto se = detail::scope_exit([&] {
  14845. svr.stop();
  14846. t.join();
  14847. });
  14848. svr.wait_until_ready();
  14849. // NoDecisionMade with verification disabled should succeed (no default check)
  14850. SSLClient cli(HOST, PORT);
  14851. cli.enable_server_certificate_verification(false);
  14852. cli.set_connection_timeout(30);
  14853. bool callback_called = false;
  14854. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14855. EXPECT_NE(session, nullptr);
  14856. callback_called = true;
  14857. return SSLVerifierResponse::NoDecisionMade;
  14858. });
  14859. auto res = cli.Get("/test");
  14860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14861. EXPECT_EQ(200, res->status);
  14862. EXPECT_TRUE(callback_called);
  14863. }
  14864. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14865. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14866. ASSERT_TRUE(svr.is_valid());
  14867. svr.Get("/test", [](const Request &, Response &res) {
  14868. res.set_content("ok", "text/plain");
  14869. });
  14870. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14871. auto se = detail::scope_exit([&] {
  14872. svr.stop();
  14873. t.join();
  14874. });
  14875. svr.wait_until_ready();
  14876. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14877. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14878. // so we only check that the request fails, not whether the callback was
  14879. // called.
  14880. SSLClient cli(HOST, PORT);
  14881. cli.enable_server_certificate_verification(true);
  14882. cli.set_connection_timeout(30);
  14883. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14884. EXPECT_NE(session, nullptr);
  14885. return SSLVerifierResponse::NoDecisionMade;
  14886. });
  14887. auto res = cli.Get("/test");
  14888. EXPECT_FALSE(res);
  14889. }
  14890. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14891. // Test SSL server using PemMemory constructor with client CA certificates
  14892. // Read PEM files
  14893. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14894. read_file(SERVER_CERT_FILE, server_cert_pem);
  14895. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14896. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14897. // Create SSLServer with PemMemory constructor including client CA
  14898. SSLServer::PemMemory server_pem = {
  14899. server_cert_pem.c_str(),
  14900. server_cert_pem.size(),
  14901. server_key_pem.c_str(),
  14902. server_key_pem.size(),
  14903. client_ca_pem.c_str(),
  14904. client_ca_pem.size(),
  14905. nullptr // no password for server key
  14906. };
  14907. SSLServer svr(server_pem);
  14908. ASSERT_TRUE(svr.is_valid());
  14909. // No SSL error should be recorded for valid setup
  14910. EXPECT_EQ(0, svr.ssl_last_error());
  14911. // Set up server endpoints
  14912. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14913. res.set_content("ok", "text/plain");
  14914. });
  14915. // Start server in a thread
  14916. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14917. svr.wait_until_ready();
  14918. // Connect with client certificate (using constructor with paths)
  14919. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14920. cli.enable_server_certificate_verification(false);
  14921. auto res = cli.Get("/test-pem-ca");
  14922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14923. EXPECT_EQ(200, res->status);
  14924. EXPECT_EQ("ok", res->body);
  14925. svr.stop();
  14926. server_thread.join();
  14927. }
  14928. #endif
  14929. #ifdef _WIN32
  14930. TEST(CleanupTest, WSACleanup) {
  14931. int ret = WSACleanup();
  14932. ASSERT_EQ(0, ret);
  14933. }
  14934. #endif
  14935. #ifndef CPPHTTPLIB_SSL_ENABLED
  14936. TEST(NoSSLSupport, SimpleInterface) {
  14937. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14938. }
  14939. #endif
  14940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14941. TEST(InvalidScheme, SimpleInterface) {
  14942. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14943. }
  14944. #endif
  14945. TEST(NoScheme, SimpleInterface) {
  14946. Client cli("yahoo.com:80");
  14947. ASSERT_TRUE(cli.is_valid());
  14948. }
  14949. TEST(SendAPI, SimpleInterface_Online) {
  14950. Client cli("http://yahoo.com");
  14951. Request req;
  14952. req.method = "GET";
  14953. req.path = "/";
  14954. auto res = cli.send(req);
  14955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14956. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14957. }
  14958. TEST(SendAPI, WithParamsInRequest) {
  14959. Server svr;
  14960. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14961. EXPECT_TRUE(req.has_param("test"));
  14962. EXPECT_EQ("test_value", req.get_param_value("test"));
  14963. });
  14964. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14965. auto se = detail::scope_exit([&] {
  14966. svr.stop();
  14967. t.join();
  14968. ASSERT_FALSE(svr.is_running());
  14969. });
  14970. svr.wait_until_ready();
  14971. Client cli(HOST, PORT);
  14972. {
  14973. Request req;
  14974. req.method = "GET";
  14975. req.path = "/";
  14976. req.params.emplace("test", "test_value");
  14977. auto res = cli.send(req);
  14978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14979. }
  14980. {
  14981. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14983. }
  14984. }
  14985. TEST(ClientImplMethods, GetSocketTest) {
  14986. httplib::Server svr;
  14987. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14988. res.status = StatusCode::OK_200;
  14989. });
  14990. auto port = svr.bind_to_any_port("127.0.0.1");
  14991. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14992. auto se = detail::scope_exit([&] {
  14993. svr.stop();
  14994. thread.join();
  14995. ASSERT_FALSE(svr.is_running());
  14996. });
  14997. svr.wait_until_ready();
  14998. {
  14999. httplib::Client cli("127.0.0.1", port);
  15000. cli.set_keep_alive(true);
  15001. // Use the behavior of cpp-httplib of opening the connection
  15002. // only when the first request happens. If that changes,
  15003. // this test would be obsolete.
  15004. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15005. // This also implicitly tests the server. But other tests would fail much
  15006. // earlier than this one to be considered.
  15007. auto res = cli.Get("/");
  15008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15009. EXPECT_EQ(StatusCode::OK_200, res->status);
  15010. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15011. }
  15012. }
  15013. #ifdef CPPHTTPLIB_SSL_ENABLED
  15014. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15015. Client cli("http://yahoo.com");
  15016. auto res = cli.Get("/");
  15017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15018. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15019. cli.set_follow_location(true);
  15020. res = cli.Get("/");
  15021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15022. EXPECT_EQ(StatusCode::OK_200, res->status);
  15023. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15024. }
  15025. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15026. Client cli("https://yahoo.com");
  15027. auto res = cli.Get("/");
  15028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15029. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15030. cli.set_follow_location(true);
  15031. res = cli.Get("/");
  15032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15033. EXPECT_EQ(StatusCode::OK_200, res->status);
  15034. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15035. }
  15036. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15037. Client cli("https://yahoo.com");
  15038. auto res = cli.Get("/");
  15039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15040. ASSERT_FALSE(!res);
  15041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15042. ASSERT_FALSE(res == nullptr);
  15043. ASSERT_TRUE(res != nullptr);
  15044. EXPECT_EQ(Error::Success, res.error());
  15045. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15046. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15047. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15048. cli.set_follow_location(true);
  15049. res = cli.Get("/");
  15050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15051. EXPECT_EQ(Error::Success, res.error());
  15052. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15053. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15054. EXPECT_EQ(StatusCode::OK_200, res->status);
  15055. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15056. }
  15057. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15058. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15059. Client cli("https://cdnjs.cloudflare.com");
  15060. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15061. Headers{{"Accept-Encoding", "br"}});
  15062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15063. EXPECT_EQ(StatusCode::OK_200, res->status);
  15064. EXPECT_EQ(287630U, res->body.size());
  15065. EXPECT_EQ("application/javascript; charset=utf-8",
  15066. res->get_header_value("Content-Type"));
  15067. }
  15068. #endif
  15069. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15070. #undef REDIR_HOST // Silence compiler warning
  15071. #define REDIR_HOST "https://httpbingo.org"
  15072. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15073. Client cli(REDIR_HOST);
  15074. cli.set_follow_location(true);
  15075. auto res =
  15076. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15078. EXPECT_EQ(StatusCode::OK_200, res->status);
  15079. }
  15080. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15081. Client cli(REDIR_HOST);
  15082. cli.set_follow_location(true);
  15083. Params params;
  15084. params.emplace("url", "http://example.com");
  15085. params.emplace("status_code", "302");
  15086. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15088. EXPECT_EQ(StatusCode::OK_200, res->status);
  15089. }
  15090. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15091. Client cli(REDIR_HOST);
  15092. cli.set_follow_location(true);
  15093. Params params;
  15094. params.emplace("url", "http://example.com");
  15095. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15097. EXPECT_EQ(StatusCode::OK_200, res->status);
  15098. }
  15099. TEST(HttpToHttpsRedirectTest, CertFile) {
  15100. auto ssl_port = PORT + 1;
  15101. Server svr;
  15102. ASSERT_TRUE(svr.is_valid());
  15103. svr.Get("/index", [&](const Request &, Response &res) {
  15104. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15105. "/index");
  15106. svr.stop();
  15107. });
  15108. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15109. ASSERT_TRUE(ssl_svr.is_valid());
  15110. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15111. res.set_content("test", "text/plain");
  15112. ssl_svr.stop();
  15113. });
  15114. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15115. thread t2 =
  15116. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15117. auto se = detail::scope_exit([&] {
  15118. t2.join();
  15119. t.join();
  15120. ASSERT_FALSE(svr.is_running());
  15121. });
  15122. svr.wait_until_ready();
  15123. ssl_svr.wait_until_ready();
  15124. Client cli("127.0.0.1", PORT);
  15125. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15126. cli.enable_server_certificate_verification(true);
  15127. cli.set_follow_location(true);
  15128. cli.set_connection_timeout(30);
  15129. auto res = cli.Get("/index");
  15130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15131. ASSERT_EQ(StatusCode::OK_200, res->status);
  15132. }
  15133. TEST(SSLClientRedirectTest, CertFile) {
  15134. auto ssl_port = PORT + 1;
  15135. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15136. ASSERT_TRUE(ssl_svr1.is_valid());
  15137. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15138. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15139. "/index");
  15140. ssl_svr1.stop();
  15141. });
  15142. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15143. ASSERT_TRUE(ssl_svr2.is_valid());
  15144. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15145. res.set_content("test", "text/plain");
  15146. ssl_svr2.stop();
  15147. });
  15148. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15149. thread t2 =
  15150. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15151. auto se = detail::scope_exit([&] {
  15152. t2.join();
  15153. t.join();
  15154. ASSERT_FALSE(ssl_svr1.is_running());
  15155. });
  15156. ssl_svr1.wait_until_ready();
  15157. ssl_svr2.wait_until_ready();
  15158. SSLClient cli("127.0.0.1", PORT);
  15159. std::string cert;
  15160. read_file(SERVER_CERT2_FILE, cert);
  15161. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15162. cli.enable_server_certificate_verification(true);
  15163. cli.set_follow_location(true);
  15164. cli.set_connection_timeout(30);
  15165. auto res = cli.Get("/index");
  15166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15167. ASSERT_EQ(StatusCode::OK_200, res->status);
  15168. }
  15169. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15170. // another port, so the client follows it with a new client.
  15171. static Result GetThroughTlsRedirectToDifferentPort(
  15172. const std::function<void(SSLClient &)> &setup,
  15173. const char *target_cert = SERVER_CERT2_FILE,
  15174. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15175. auto ssl_port = PORT + 1;
  15176. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15177. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15178. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15179. "/index");
  15180. });
  15181. SSLServer ssl_svr2(target_cert, target_key);
  15182. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15183. res.set_content("test", "text/plain");
  15184. });
  15185. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15186. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15187. auto se = detail::scope_exit([&] {
  15188. ssl_svr2.stop();
  15189. ssl_svr1.stop();
  15190. t2.join();
  15191. t.join();
  15192. });
  15193. ssl_svr1.wait_until_ready();
  15194. ssl_svr2.wait_until_ready();
  15195. SSLClient cli("127.0.0.1", PORT);
  15196. cli.set_follow_location(true);
  15197. cli.set_connection_timeout(30);
  15198. setup(cli);
  15199. return cli.Get("/index");
  15200. }
  15201. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15202. auto calls = 0;
  15203. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15204. cli.enable_server_certificate_verification(false);
  15205. // Accept the first server only.
  15206. cli.set_session_verifier([&](tls::session_t) {
  15207. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15208. : SSLVerifierResponse::CertificateRejected;
  15209. });
  15210. });
  15211. ASSERT_FALSE(res);
  15212. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15213. EXPECT_EQ(2, calls);
  15214. }
  15215. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15216. std::string pinned;
  15217. auto res = GetThroughTlsRedirectToDifferentPort(
  15218. [&](SSLClient &cli) {
  15219. cli.enable_server_certificate_verification(false);
  15220. // Pin the first certificate seen.
  15221. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15222. if (pinned.empty()) { pinned = ctx.serial(); }
  15223. return ctx.serial() == pinned;
  15224. });
  15225. },
  15226. // A certificate other than the first server's.
  15227. SERVER_CERT_FILE);
  15228. EXPECT_FALSE(res);
  15229. EXPECT_FALSE(pinned.empty());
  15230. }
  15231. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15232. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15233. std::string cert;
  15234. read_file(SERVER_CERT2_FILE, cert);
  15235. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15236. });
  15237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15238. EXPECT_EQ(StatusCode::OK_200, res->status);
  15239. }
  15240. // The target's certificate is signed by the root CA, which the first server's
  15241. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15242. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15243. auto res = GetThroughTlsRedirectToDifferentPort(
  15244. [](SSLClient &cli) {
  15245. std::string root_ca, cert;
  15246. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15247. read_file(SERVER_CERT2_FILE, cert);
  15248. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15249. cli.load_ca_cert_store(cert.data(), cert.size());
  15250. cli.enable_server_hostname_verification(false);
  15251. },
  15252. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15254. EXPECT_EQ(StatusCode::OK_200, res->status);
  15255. }
  15256. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15257. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15258. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15259. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15260. auto res = GetThroughTlsRedirectToDifferentPort(
  15261. [](SSLClient &cli) {
  15262. std::string root_ca, cert;
  15263. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15264. read_file(SERVER_CERT2_FILE, cert);
  15265. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15266. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15267. cli.enable_server_hostname_verification(false);
  15268. },
  15269. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15270. ASSERT_FALSE(res);
  15271. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15272. }
  15273. #endif
  15274. #endif
  15275. #ifdef CPPHTTPLIB_SSL_ENABLED
  15276. // Test that set_ca_cert_store() skips system certs (consistent with
  15277. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15278. // should be trusted - system certs should NOT be loaded.
  15279. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15280. // Load a specific cert that is NOT a system CA cert
  15281. std::string cert;
  15282. read_file(SERVER_CERT2_FILE, cert);
  15283. SSLClient cli("google.com");
  15284. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15285. cli.enable_server_certificate_verification(true);
  15286. // This should FAIL because:
  15287. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15288. // 2. System certs should NOT be loaded when custom store is set
  15289. // If system certs WERE loaded, this would succeed
  15290. auto res = cli.Get("/");
  15291. ASSERT_FALSE(res);
  15292. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15293. }
  15294. // Same as above, but through the native store handle path. Regression test:
  15295. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15296. // merged system certs into the user-provided store.
  15297. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15298. std::string cert;
  15299. read_file(SERVER_CERT2_FILE, cert);
  15300. SSLClient cli("google.com");
  15301. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15302. cli.enable_server_certificate_verification(true);
  15303. auto res = cli.Get("/");
  15304. ASSERT_FALSE(res);
  15305. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15306. }
  15307. // A custom store set via the native handle must still verify a server whose
  15308. // cert it does contain.
  15309. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15310. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15311. ASSERT_TRUE(svr.is_valid());
  15312. svr.Get("/test", [&](const Request &, Response &res) {
  15313. res.set_content("test", "text/plain");
  15314. });
  15315. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15316. auto se = detail::scope_exit([&] {
  15317. svr.stop();
  15318. t.join();
  15319. ASSERT_FALSE(svr.is_running());
  15320. });
  15321. svr.wait_until_ready();
  15322. SSLClient cli("127.0.0.1", PORT);
  15323. std::string cert;
  15324. read_file(SERVER_CERT2_FILE, cert);
  15325. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15326. cli.enable_server_certificate_verification(true);
  15327. cli.set_connection_timeout(30);
  15328. auto res = cli.Get("/test");
  15329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15330. ASSERT_EQ(StatusCode::OK_200, res->status);
  15331. }
  15332. // CA certs loaded through the universal Client must be transferred to the
  15333. // client created internally for following an HTTPS redirect. Regression test:
  15334. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15335. // the CA data for redirect transfer.
  15336. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15337. auto ssl_port = PORT + 1;
  15338. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15339. ASSERT_TRUE(ssl_svr1.is_valid());
  15340. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15341. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15342. "/index");
  15343. });
  15344. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15345. ASSERT_TRUE(ssl_svr2.is_valid());
  15346. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15347. res.set_content("test", "text/plain");
  15348. });
  15349. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15350. thread t2 =
  15351. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15352. auto se = detail::scope_exit([&] {
  15353. ssl_svr2.stop();
  15354. ssl_svr1.stop();
  15355. t2.join();
  15356. t.join();
  15357. ASSERT_FALSE(ssl_svr1.is_running());
  15358. });
  15359. ssl_svr1.wait_until_ready();
  15360. ssl_svr2.wait_until_ready();
  15361. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15362. std::string cert;
  15363. read_file(SERVER_CERT2_FILE, cert);
  15364. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15365. cli.enable_server_certificate_verification(true);
  15366. cli.set_follow_location(true);
  15367. cli.set_connection_timeout(30);
  15368. auto res = cli.Get("/index");
  15369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15370. ASSERT_EQ(StatusCode::OK_200, res->status);
  15371. }
  15372. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15373. // so a host signed by a system CA verifies even though a custom CA is set
  15374. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15375. std::string cert;
  15376. read_file(SERVER_CERT2_FILE, cert);
  15377. SSLClient cli("google.com");
  15378. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15379. cli.enable_system_ca(true);
  15380. cli.enable_server_certificate_verification(true);
  15381. auto res = cli.Get("/");
  15382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15383. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15384. }
  15385. // The custom CA remains effective when combined with the system CA
  15386. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15387. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15388. ASSERT_TRUE(svr.is_valid());
  15389. svr.Get("/test", [&](const Request &, Response &res) {
  15390. res.set_content("test", "text/plain");
  15391. });
  15392. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15393. auto se = detail::scope_exit([&] {
  15394. svr.stop();
  15395. t.join();
  15396. ASSERT_FALSE(svr.is_running());
  15397. });
  15398. svr.wait_until_ready();
  15399. SSLClient cli("127.0.0.1", PORT);
  15400. std::string cert;
  15401. read_file(SERVER_CERT2_FILE, cert);
  15402. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15403. cli.enable_system_ca(true);
  15404. cli.enable_server_certificate_verification(true);
  15405. cli.set_connection_timeout(30);
  15406. auto res = cli.Get("/test");
  15407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15408. ASSERT_EQ(StatusCode::OK_200, res->status);
  15409. }
  15410. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15411. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15412. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15413. static CFDictionaryRef
  15414. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15415. const SecTrustSettingsResult *result) {
  15416. auto constraint =
  15417. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15418. &kCFTypeDictionaryValueCallBacks);
  15419. if (policy) {
  15420. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15421. }
  15422. if (policy_string) {
  15423. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15424. kCFStringEncodingUTF8);
  15425. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15426. CFRelease(str);
  15427. }
  15428. if (result) {
  15429. auto number_value = static_cast<SInt32>(*result);
  15430. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15431. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15432. CFRelease(number);
  15433. }
  15434. return constraint;
  15435. }
  15436. static SecTrustSettingsResult
  15437. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15438. auto trust_settings =
  15439. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15440. for (auto constraint : constraints) {
  15441. CFArrayAppendValue(trust_settings, constraint);
  15442. CFRelease(constraint);
  15443. }
  15444. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15445. CFRelease(trust_settings);
  15446. return result;
  15447. }
  15448. // The system CA loader takes a Keychain certificate as a trusted root only
  15449. // when its Trust Settings say so for SSL, not merely because it has some.
  15450. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15451. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15452. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15453. const auto deny = kSecTrustSettingsResultDeny;
  15454. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15455. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15456. auto x509_policy = SecPolicyCreateBasicX509();
  15457. // "Always Trust", which stores no constraint at all
  15458. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15459. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15460. ssl_trust_settings_result(
  15461. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15462. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15463. ssl_trust_settings_result(
  15464. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15465. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15466. ssl_trust_settings_result(
  15467. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15468. // "Never Trust", for everything or for SSL
  15469. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15470. ssl_trust_settings_result(
  15471. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15472. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15473. ssl_trust_settings_result(
  15474. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15475. // Trusted for another policy, for one host, or not at all
  15476. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15477. ssl_trust_settings_result(
  15478. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15479. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15480. ssl_trust_settings_result({make_usage_constraint(
  15481. ssl_policy, "www.example.com", &trust_root)}));
  15482. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15483. ssl_trust_settings_result(
  15484. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15485. // The first constraint that applies to SSL decides
  15486. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15487. ssl_trust_settings_result(
  15488. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15489. make_usage_constraint(nullptr, nullptr, &deny)}));
  15490. CFRelease(x509_policy);
  15491. CFRelease(ssl_policy);
  15492. }
  15493. #endif
  15494. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15495. // skip chain verification entirely (only the certificate identity was
  15496. // checked), so a server presenting an untrusted certificate with a matching
  15497. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15498. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15499. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15500. ASSERT_TRUE(svr.is_valid());
  15501. svr.Get("/test", [&](const Request &, Response &res) {
  15502. res.set_content("test", "text/plain");
  15503. });
  15504. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15505. auto se = detail::scope_exit([&] {
  15506. svr.stop();
  15507. t.join();
  15508. ASSERT_FALSE(svr.is_running());
  15509. });
  15510. svr.wait_until_ready();
  15511. SSLClient cli("127.0.0.1", PORT);
  15512. std::string cert;
  15513. // A trusted CA that did not sign the server certificate. The server cert
  15514. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15515. // this connection.
  15516. read_file(CLIENT_CA_CERT_FILE, cert);
  15517. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15518. cli.enable_server_certificate_verification(true);
  15519. cli.set_connection_timeout(30);
  15520. auto res = cli.Get("/test");
  15521. ASSERT_FALSE(res);
  15522. }
  15523. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15524. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15525. // CA that failed to come through fails verification instead of trusting them.
  15526. // (wolfSSL does not list the system CAs it loaded.)
  15527. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15528. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15529. ASSERT_TRUE(svr.is_valid());
  15530. auto port = svr.bind_to_any_port("127.0.0.1");
  15531. ASSERT_LT(0, port);
  15532. thread t = thread([&] { svr.listen_after_bind(); });
  15533. auto se = detail::scope_exit([&] {
  15534. svr.stop();
  15535. t.join();
  15536. ASSERT_FALSE(svr.is_running());
  15537. });
  15538. svr.wait_until_ready();
  15539. // The CAs a client trusts once its first request has loaded them
  15540. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15541. Client cli("https://127.0.0.1:" + std::to_string(port));
  15542. setup(cli);
  15543. cli.Get("/");
  15544. return tls::get_ca_names(cli.tls_context()).size();
  15545. };
  15546. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15547. EXPECT_EQ(0u,
  15548. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15549. }
  15550. #endif
  15551. // A TLS setting changed between requests applies to the next one, not just to
  15552. // the next connection
  15553. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15554. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15555. ASSERT_TRUE(svr.is_valid());
  15556. svr.Get("/", [](const Request &req, Response &res) {
  15557. res.set_content(std::to_string(req.remote_port), "text/plain");
  15558. });
  15559. auto port = svr.bind_to_any_port("127.0.0.1");
  15560. ASSERT_LT(0, port);
  15561. thread t = thread([&] { svr.listen_after_bind(); });
  15562. auto se = detail::scope_exit([&] {
  15563. svr.stop();
  15564. t.join();
  15565. ASSERT_FALSE(svr.is_running());
  15566. });
  15567. svr.wait_until_ready();
  15568. SSLClient cli("127.0.0.1", port);
  15569. cli.set_keep_alive(true);
  15570. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15571. cli.enable_server_certificate_verification(false);
  15572. // The port the request went out from, so a new one means a new connection
  15573. auto client_port = [&] {
  15574. auto res = cli.Get("/");
  15575. return res ? res->body : std::string();
  15576. };
  15577. auto last = client_port();
  15578. ASSERT_FALSE(last.empty());
  15579. // Setting a value it already has keeps the connection
  15580. cli.enable_server_certificate_verification(false);
  15581. cli.enable_server_hostname_verification(true);
  15582. EXPECT_EQ(last, client_port());
  15583. cli.enable_server_certificate_verification(true);
  15584. auto res = cli.Get("/");
  15585. EXPECT_FALSE(res);
  15586. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15587. std::string ca;
  15588. read_file(SERVER_CERT2_FILE, ca);
  15589. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15590. last = client_port();
  15591. ASSERT_FALSE(last.empty());
  15592. std::vector<std::function<void()>> setters = {
  15593. [&] { cli.enable_server_hostname_verification(false); },
  15594. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15595. [&] {
  15596. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15597. },
  15598. [&] {
  15599. cli.set_server_certificate_verifier(
  15600. [](const tls::VerifyContext &) { return true; });
  15601. },
  15602. [&] {
  15603. cli.set_session_verifier(
  15604. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15605. },
  15606. };
  15607. for (const auto &setter : setters) {
  15608. setter();
  15609. auto next = client_port();
  15610. ASSERT_FALSE(next.empty());
  15611. EXPECT_NE(last, next);
  15612. last = next;
  15613. }
  15614. cli.set_session_verifier(
  15615. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15616. auto handle = cli.open_stream("GET", "/");
  15617. EXPECT_FALSE(handle.is_valid());
  15618. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15619. }
  15620. // A PEM given to create_ca_store() needs no NUL after it
  15621. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15622. std::string pem;
  15623. read_file(SERVER_CERT2_FILE, pem);
  15624. auto buf = pem + "X";
  15625. auto store = tls::create_ca_store(buf.data(), pem.size());
  15626. EXPECT_TRUE(store != nullptr);
  15627. SSLClient cli("localhost");
  15628. cli.set_ca_cert_store(store);
  15629. }
  15630. // enable_system_ca(false) prevents system CA loading entirely
  15631. TEST(SSLClientTest, DisableSystemCa_Online) {
  15632. SSLClient cli("google.com");
  15633. cli.enable_system_ca(false);
  15634. cli.enable_server_certificate_verification(true);
  15635. auto res = cli.Get("/");
  15636. ASSERT_FALSE(res);
  15637. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15638. // itself when the CA chain is empty
  15639. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15640. res.error() == Error::SSLConnection);
  15641. }
  15642. // The universal Client forwards enable_system_ca()
  15643. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15644. std::string cert;
  15645. read_file(SERVER_CERT2_FILE, cert);
  15646. Client cli("https://google.com");
  15647. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15648. cli.enable_system_ca(true);
  15649. cli.enable_server_certificate_verification(true);
  15650. auto res = cli.Get("/");
  15651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15652. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15653. }
  15654. // The system CA policy must carry over to the client created internally for
  15655. // following a cross-host HTTPS redirect
  15656. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15657. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15658. ASSERT_TRUE(svr.is_valid());
  15659. svr.Get("/index", [&](const Request &, Response &res) {
  15660. res.set_redirect("https://www.google.com/");
  15661. });
  15662. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15663. auto se = detail::scope_exit([&] {
  15664. svr.stop();
  15665. t.join();
  15666. ASSERT_FALSE(svr.is_running());
  15667. });
  15668. svr.wait_until_ready();
  15669. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15670. std::string cert;
  15671. read_file(SERVER_CERT2_FILE, cert);
  15672. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15673. cli.enable_system_ca(true);
  15674. cli.enable_server_certificate_verification(true);
  15675. cli.set_follow_location(true);
  15676. cli.set_connection_timeout(30);
  15677. // Receiving any response proves the redirect client completed the TLS
  15678. // handshake with a system-CA-signed host
  15679. auto res = cli.Get("/index");
  15680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15681. }
  15682. TEST(MultipartFormDataTest, LargeData) {
  15683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15684. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15685. const ContentReader &content_reader) {
  15686. if (req.is_multipart_form_data()) {
  15687. std::vector<FormData> items;
  15688. content_reader(
  15689. [&](const FormData &file) {
  15690. items.push_back(file);
  15691. return true;
  15692. },
  15693. [&](const char *data, size_t data_length) {
  15694. items.back().content.append(data, data_length);
  15695. return true;
  15696. });
  15697. EXPECT_TRUE(std::string(items[0].name) == "document");
  15698. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15699. EXPECT_TRUE(items[0].filename == "2MB_data");
  15700. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15701. EXPECT_TRUE(items[1].name == "hello");
  15702. EXPECT_TRUE(items[1].content == "world");
  15703. EXPECT_TRUE(items[1].filename == "");
  15704. EXPECT_TRUE(items[1].content_type == "");
  15705. } else {
  15706. std::string body;
  15707. content_reader([&](const char *data, size_t data_length) {
  15708. body.append(data, data_length);
  15709. return true;
  15710. });
  15711. }
  15712. });
  15713. auto port = svr.bind_to_any_port(HOST);
  15714. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15715. auto se = detail::scope_exit([&] {
  15716. svr.stop();
  15717. t.join();
  15718. ASSERT_FALSE(svr.is_running());
  15719. });
  15720. svr.wait_until_ready();
  15721. {
  15722. std::string data(1024 * 1024 * 2, '.');
  15723. std::stringstream buffer;
  15724. buffer << data;
  15725. SSLClient cli(HOST, port);
  15726. cli.enable_server_certificate_verification(false);
  15727. UploadFormDataItems items{
  15728. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15729. {"hello", "world", "", ""},
  15730. };
  15731. auto res = cli.Post("/post", items);
  15732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15733. ASSERT_EQ(StatusCode::OK_200, res->status);
  15734. }
  15735. }
  15736. TEST(MultipartFormDataTest, DataProviderItems) {
  15737. std::random_device seed_gen;
  15738. std::mt19937 random(seed_gen());
  15739. std::string rand1;
  15740. rand1.resize(1000);
  15741. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15742. std::string rand2;
  15743. rand2.resize(3000);
  15744. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15745. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15746. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15747. const ContentReader &content_reader) {
  15748. ASSERT_FALSE(req.is_multipart_form_data());
  15749. std::string body;
  15750. content_reader([&](const char *data, size_t data_length) {
  15751. body.append(data, data_length);
  15752. return true;
  15753. });
  15754. EXPECT_EQ(body, "");
  15755. });
  15756. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15757. const ContentReader &content_reader) {
  15758. ASSERT_TRUE(req.is_multipart_form_data());
  15759. std::vector<FormData> items;
  15760. content_reader(
  15761. [&](const FormData &file) {
  15762. items.push_back(file);
  15763. return true;
  15764. },
  15765. [&](const char *data, size_t data_length) {
  15766. items.back().content.append(data, data_length);
  15767. return true;
  15768. });
  15769. ASSERT_TRUE(items.size() == 2);
  15770. EXPECT_EQ(std::string(items[0].name), "name1");
  15771. EXPECT_EQ(items[0].content, "Testing123");
  15772. EXPECT_EQ(items[0].filename, "filename1");
  15773. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15774. EXPECT_EQ(items[1].name, "name2");
  15775. EXPECT_EQ(items[1].content, "Testing456");
  15776. EXPECT_EQ(items[1].filename, "");
  15777. EXPECT_EQ(items[1].content_type, "");
  15778. });
  15779. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15780. const ContentReader &content_reader) {
  15781. ASSERT_TRUE(req.is_multipart_form_data());
  15782. std::vector<FormData> items;
  15783. content_reader(
  15784. [&](const FormData &file) {
  15785. items.push_back(file);
  15786. return true;
  15787. },
  15788. [&](const char *data, size_t data_length) {
  15789. items.back().content.append(data, data_length);
  15790. return true;
  15791. });
  15792. ASSERT_TRUE(items.size() == 2);
  15793. EXPECT_EQ(items[0].name, "name3");
  15794. EXPECT_EQ(items[0].content, rand1);
  15795. EXPECT_EQ(items[0].filename, "filename3");
  15796. EXPECT_EQ(items[0].content_type, "");
  15797. EXPECT_EQ(items[1].name, "name4");
  15798. EXPECT_EQ(items[1].content, rand2);
  15799. EXPECT_EQ(items[1].filename, "filename4");
  15800. EXPECT_EQ(items[1].content_type, "");
  15801. });
  15802. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15803. const ContentReader &content_reader) {
  15804. ASSERT_TRUE(req.is_multipart_form_data());
  15805. std::vector<FormData> items;
  15806. content_reader(
  15807. [&](const FormData &file) {
  15808. items.push_back(file);
  15809. return true;
  15810. },
  15811. [&](const char *data, size_t data_length) {
  15812. items.back().content.append(data, data_length);
  15813. return true;
  15814. });
  15815. ASSERT_TRUE(items.size() == 4);
  15816. EXPECT_EQ(std::string(items[0].name), "name1");
  15817. EXPECT_EQ(items[0].content, "Testing123");
  15818. EXPECT_EQ(items[0].filename, "filename1");
  15819. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15820. EXPECT_EQ(items[1].name, "name2");
  15821. EXPECT_EQ(items[1].content, "Testing456");
  15822. EXPECT_EQ(items[1].filename, "");
  15823. EXPECT_EQ(items[1].content_type, "");
  15824. EXPECT_EQ(items[2].name, "name3");
  15825. EXPECT_EQ(items[2].content, rand1);
  15826. EXPECT_EQ(items[2].filename, "filename3");
  15827. EXPECT_EQ(items[2].content_type, "");
  15828. EXPECT_EQ(items[3].name, "name4");
  15829. EXPECT_EQ(items[3].content, rand2);
  15830. EXPECT_EQ(items[3].filename, "filename4");
  15831. EXPECT_EQ(items[3].content_type, "");
  15832. });
  15833. auto port = svr.bind_to_any_port("localhost");
  15834. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15835. auto se = detail::scope_exit([&] {
  15836. svr.stop();
  15837. t.join();
  15838. ASSERT_FALSE(svr.is_running());
  15839. });
  15840. svr.wait_until_ready();
  15841. {
  15842. SSLClient cli("localhost", port);
  15843. cli.enable_server_certificate_verification(false);
  15844. UploadFormDataItems items{
  15845. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15846. {"name2", "Testing456", "", ""}, // not a file
  15847. };
  15848. {
  15849. auto res = cli.Post("/post-none", {}, {}, {});
  15850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15851. ASSERT_EQ(StatusCode::OK_200, res->status);
  15852. }
  15853. FormDataProviderItems providers;
  15854. {
  15855. auto res =
  15856. cli.Post("/post-items", {}, items, providers); // empty providers
  15857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15858. ASSERT_EQ(StatusCode::OK_200, res->status);
  15859. }
  15860. providers.push_back({"name3",
  15861. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15862. // test the offset is given correctly at each step
  15863. if (!offset)
  15864. sink.os.write(rand1.data(), 30);
  15865. else if (offset == 30)
  15866. sink.os.write(rand1.data() + 30, 300);
  15867. else if (offset == 330)
  15868. sink.os.write(rand1.data() + 330, 670);
  15869. else if (offset == rand1.size())
  15870. sink.done();
  15871. return true;
  15872. },
  15873. "filename3",
  15874. {}});
  15875. providers.push_back({"name4",
  15876. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15877. // test the offset is given correctly at each step
  15878. if (!offset)
  15879. sink.os.write(rand2.data(), 2000);
  15880. else if (offset == 2000)
  15881. sink.os.write(rand2.data() + 2000, 1);
  15882. else if (offset == 2001)
  15883. sink.os.write(rand2.data() + 2001, 999);
  15884. else if (offset == rand2.size())
  15885. sink.done();
  15886. return true;
  15887. },
  15888. "filename4",
  15889. {}});
  15890. {
  15891. auto res = cli.Post("/post-providers", {}, {}, providers);
  15892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15893. ASSERT_EQ(StatusCode::OK_200, res->status);
  15894. }
  15895. {
  15896. auto res = cli.Post("/post-both", {}, items, providers);
  15897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15898. ASSERT_EQ(StatusCode::OK_200, res->status);
  15899. }
  15900. }
  15901. }
  15902. TEST(MultipartFormDataTest, BadHeader) {
  15903. Server svr;
  15904. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15905. res.set_content("ok", "text/plain");
  15906. });
  15907. thread t = thread([&] { svr.listen(HOST, PORT); });
  15908. auto se = detail::scope_exit([&] {
  15909. svr.stop();
  15910. t.join();
  15911. ASSERT_FALSE(svr.is_running());
  15912. });
  15913. svr.wait_until_ready();
  15914. const std::string body =
  15915. "This is the preamble. It is to be ignored, though it\r\n"
  15916. "is a handy place for composition agents to include an\r\n"
  15917. "explanatory note to non-MIME conformant readers.\r\n"
  15918. "\r\n"
  15919. "\r\n"
  15920. "--simple boundary\r\n"
  15921. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15922. ": BAD...\r\n"
  15923. "\r\n"
  15924. "value1\r\n"
  15925. "--simple boundary\r\n"
  15926. "Content-Disposition: form-data; name=\"field2\"; "
  15927. "filename=\"example.txt\"\r\n"
  15928. "\r\n"
  15929. "value2\r\n"
  15930. "--simple boundary--\r\n"
  15931. "This is the epilogue. It is also to be ignored.\r\n";
  15932. std::string content_type =
  15933. R"(multipart/form-data; boundary="simple boundary")";
  15934. Client cli(HOST, PORT);
  15935. auto res = cli.Post("/post", body, content_type.c_str());
  15936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15937. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15938. }
  15939. TEST(MultipartFormDataTest, WithPreamble) {
  15940. Server svr;
  15941. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15942. res.set_content("ok", "text/plain");
  15943. });
  15944. thread t = thread([&] { svr.listen(HOST, PORT); });
  15945. auto se = detail::scope_exit([&] {
  15946. svr.stop();
  15947. t.join();
  15948. ASSERT_FALSE(svr.is_running());
  15949. });
  15950. svr.wait_until_ready();
  15951. const std::string body =
  15952. "This is the preamble. It is to be ignored, though it\r\n"
  15953. "is a handy place for composition agents to include an\r\n"
  15954. "explanatory note to non-MIME conformant readers.\r\n"
  15955. "\r\n"
  15956. "\r\n"
  15957. "--simple boundary\r\n"
  15958. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15959. "\r\n"
  15960. "value1\r\n"
  15961. "--simple boundary\r\n"
  15962. "Content-Disposition: form-data; name=\"field2\"; "
  15963. "filename=\"example.txt\"\r\n"
  15964. "\r\n"
  15965. "value2\r\n"
  15966. "--simple boundary--\r\n"
  15967. "This is the epilogue. It is also to be ignored.\r\n";
  15968. std::string content_type =
  15969. R"(multipart/form-data; boundary="simple boundary")";
  15970. Client cli(HOST, PORT);
  15971. auto res = cli.Post("/post", body, content_type.c_str());
  15972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15973. EXPECT_EQ(StatusCode::OK_200, res->status);
  15974. }
  15975. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15976. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15977. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15978. const ContentReader &content_reader) {
  15979. if (req.is_multipart_form_data()) {
  15980. std::vector<FormData> items;
  15981. content_reader(
  15982. [&](const FormData &file) {
  15983. items.push_back(file);
  15984. return true;
  15985. },
  15986. [&](const char *data, size_t data_length) {
  15987. items.back().content.append(data, data_length);
  15988. return true;
  15989. });
  15990. EXPECT_TRUE(std::string(items[0].name) == "document");
  15991. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15992. EXPECT_TRUE(items[0].filename == "2MB_data");
  15993. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15994. EXPECT_TRUE(items[1].name == "hello");
  15995. EXPECT_TRUE(items[1].content == "world");
  15996. EXPECT_TRUE(items[1].filename == "");
  15997. EXPECT_TRUE(items[1].content_type == "");
  15998. } else {
  15999. std::string body;
  16000. content_reader([&](const char *data, size_t data_length) {
  16001. body.append(data, data_length);
  16002. return true;
  16003. });
  16004. }
  16005. });
  16006. auto port = svr.bind_to_any_port("localhost");
  16007. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16008. auto se = detail::scope_exit([&] {
  16009. svr.stop();
  16010. t.join();
  16011. ASSERT_FALSE(svr.is_running());
  16012. });
  16013. svr.wait_until_ready();
  16014. {
  16015. std::string data(1024 * 1024 * 2, '.');
  16016. std::stringstream buffer;
  16017. buffer << data;
  16018. SSLClient cli("localhost", port);
  16019. cli.enable_server_certificate_verification(false);
  16020. UploadFormDataItems items{
  16021. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16022. {"hello", "world", "", ""},
  16023. };
  16024. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16026. ASSERT_EQ(StatusCode::OK_200, res->status);
  16027. }
  16028. }
  16029. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16030. std::string data(1024 * 1024 * 2, '&');
  16031. std::stringstream buffer;
  16032. buffer << data;
  16033. Client cli("https://localhost:8080");
  16034. UploadFormDataItems items{
  16035. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16036. {"hello", "world", "", ""},
  16037. };
  16038. for (const char &c : " \t\r\n") {
  16039. auto res =
  16040. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16041. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16042. ASSERT_FALSE(res);
  16043. }
  16044. }
  16045. TEST(MultipartFormDataTest, PutFormData) {
  16046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16047. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16048. const ContentReader &content_reader) {
  16049. if (req.is_multipart_form_data()) {
  16050. std::vector<FormData> items;
  16051. content_reader(
  16052. [&](const FormData &file) {
  16053. items.push_back(file);
  16054. return true;
  16055. },
  16056. [&](const char *data, size_t data_length) {
  16057. items.back().content.append(data, data_length);
  16058. return true;
  16059. });
  16060. EXPECT_TRUE(std::string(items[0].name) == "document");
  16061. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16062. EXPECT_TRUE(items[0].filename == "2MB_data");
  16063. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16064. EXPECT_TRUE(items[1].name == "hello");
  16065. EXPECT_TRUE(items[1].content == "world");
  16066. EXPECT_TRUE(items[1].filename == "");
  16067. EXPECT_TRUE(items[1].content_type == "");
  16068. } else {
  16069. std::string body;
  16070. content_reader([&](const char *data, size_t data_length) {
  16071. body.append(data, data_length);
  16072. return true;
  16073. });
  16074. }
  16075. });
  16076. auto port = svr.bind_to_any_port("localhost");
  16077. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16078. auto se = detail::scope_exit([&] {
  16079. svr.stop();
  16080. t.join();
  16081. ASSERT_FALSE(svr.is_running());
  16082. });
  16083. svr.wait_until_ready();
  16084. {
  16085. std::string data(1024 * 1024 * 2, '&');
  16086. std::stringstream buffer;
  16087. buffer << data;
  16088. SSLClient cli("localhost", port);
  16089. cli.enable_server_certificate_verification(false);
  16090. UploadFormDataItems items{
  16091. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16092. {"hello", "world", "", ""},
  16093. };
  16094. auto res = cli.Put("/put", items);
  16095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16096. ASSERT_EQ(StatusCode::OK_200, res->status);
  16097. }
  16098. }
  16099. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16101. svr.Put("/put_customboundary",
  16102. [&](const Request &req, const Response & /*res*/,
  16103. const ContentReader &content_reader) {
  16104. if (req.is_multipart_form_data()) {
  16105. std::vector<FormData> items;
  16106. content_reader(
  16107. [&](const FormData &file) {
  16108. items.push_back(file);
  16109. return true;
  16110. },
  16111. [&](const char *data, size_t data_length) {
  16112. items.back().content.append(data, data_length);
  16113. return true;
  16114. });
  16115. EXPECT_TRUE(std::string(items[0].name) == "document");
  16116. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16117. EXPECT_TRUE(items[0].filename == "2MB_data");
  16118. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16119. EXPECT_TRUE(items[1].name == "hello");
  16120. EXPECT_TRUE(items[1].content == "world");
  16121. EXPECT_TRUE(items[1].filename == "");
  16122. EXPECT_TRUE(items[1].content_type == "");
  16123. } else {
  16124. std::string body;
  16125. content_reader([&](const char *data, size_t data_length) {
  16126. body.append(data, data_length);
  16127. return true;
  16128. });
  16129. }
  16130. });
  16131. auto port = svr.bind_to_any_port("localhost");
  16132. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16133. auto se = detail::scope_exit([&] {
  16134. svr.stop();
  16135. t.join();
  16136. ASSERT_FALSE(svr.is_running());
  16137. });
  16138. svr.wait_until_ready();
  16139. {
  16140. std::string data(1024 * 1024 * 2, '&');
  16141. std::stringstream buffer;
  16142. buffer << data;
  16143. SSLClient cli("localhost", port);
  16144. cli.enable_server_certificate_verification(false);
  16145. UploadFormDataItems items{
  16146. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16147. {"hello", "world", "", ""},
  16148. };
  16149. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16151. ASSERT_EQ(StatusCode::OK_200, res->status);
  16152. }
  16153. }
  16154. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16155. std::string data(1024 * 1024 * 2, '&');
  16156. std::stringstream buffer;
  16157. buffer << data;
  16158. Client cli("https://localhost:8080");
  16159. cli.enable_server_certificate_verification(false);
  16160. UploadFormDataItems items{
  16161. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16162. {"hello", "world", "", ""},
  16163. };
  16164. for (const char &c : " \t\r\n") {
  16165. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16166. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16167. ASSERT_FALSE(res);
  16168. }
  16169. }
  16170. TEST(MultipartFormDataTest, AlternateFilename) {
  16171. auto handled = false;
  16172. Server svr;
  16173. svr.Post("/test", [&](const Request &req, Response &res) {
  16174. ASSERT_EQ(2u, req.form.files.size());
  16175. ASSERT_EQ(1u, req.form.fields.size());
  16176. // Test files
  16177. const auto &file1 = req.form.get_file("file1");
  16178. ASSERT_EQ("file1", file1.name);
  16179. ASSERT_EQ("A.txt", file1.filename);
  16180. ASSERT_EQ("text/plain", file1.content_type);
  16181. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16182. const auto &file2 = req.form.get_file("file2");
  16183. ASSERT_EQ("file2", file2.name);
  16184. ASSERT_EQ("a.html", file2.filename);
  16185. ASSERT_EQ("text/html", file2.content_type);
  16186. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16187. file2.content);
  16188. // Test text field
  16189. const auto &text = req.form.get_field("text");
  16190. ASSERT_EQ("text default", text);
  16191. res.set_content("ok", "text/plain");
  16192. handled = true;
  16193. });
  16194. thread t = thread([&] { svr.listen(HOST, PORT); });
  16195. auto se = detail::scope_exit([&] {
  16196. svr.stop();
  16197. t.join();
  16198. ASSERT_FALSE(svr.is_running());
  16199. ASSERT_TRUE(handled);
  16200. });
  16201. svr.wait_until_ready();
  16202. auto req = "POST /test HTTP/1.1\r\n"
  16203. "Host: localhost\r\n"
  16204. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16205. "Content-Length: 399\r\n"
  16206. "\r\n"
  16207. "----------\r\n"
  16208. "Content-Disposition: form-data; name=\"text\"\r\n"
  16209. "\r\n"
  16210. "text default\r\n"
  16211. "----------\r\n"
  16212. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16213. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16214. "Content-Type: text/plain\r\n"
  16215. "\r\n"
  16216. "Content of a.txt.\r\n"
  16217. "\r\n"
  16218. "----------\r\n"
  16219. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16220. "\"a.html\"\r\n"
  16221. "Content-Type: text/html\r\n"
  16222. "\r\n"
  16223. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16224. "\r\n"
  16225. "------------\r\n";
  16226. ASSERT_TRUE(send_request(1, req));
  16227. }
  16228. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16229. auto handled = false;
  16230. Server svr;
  16231. svr.Post("/test", [&](const Request &req, Response &res) {
  16232. // Case-insensitive "utf-8''" prefix with a long value
  16233. const auto &file = req.form.get_file("file1");
  16234. ASSERT_EQ("file1", file.name);
  16235. // 8000 chars exercises both the Content-Disposition parser and the
  16236. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16237. // Prior to the fix, std::regex_match on this header would cause O(N)
  16238. // stack recursion in libstdc++, leading to SIGSEGV.
  16239. std::string expected_filename(8000, 'A');
  16240. ASSERT_EQ(expected_filename, file.filename);
  16241. res.set_content("ok", "text/plain");
  16242. handled = true;
  16243. });
  16244. thread t = thread([&] { svr.listen(HOST, PORT); });
  16245. auto se = detail::scope_exit([&] {
  16246. svr.stop();
  16247. t.join();
  16248. ASSERT_FALSE(svr.is_running());
  16249. ASSERT_TRUE(handled);
  16250. });
  16251. svr.wait_until_ready();
  16252. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16253. // Regression test for GHSA-qq6v-r583-3h69
  16254. std::string long_filename(8000, 'A');
  16255. std::string body = "----------\r\n"
  16256. "Content-Disposition: form-data; name=\"file1\"; "
  16257. "filename*=\"Utf-8''" +
  16258. long_filename +
  16259. "\"\r\n"
  16260. "\r\n"
  16261. "hello\r\n"
  16262. "------------\r\n";
  16263. auto req = "POST /test HTTP/1.1\r\n"
  16264. "Host: localhost\r\n"
  16265. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16266. "Content-Length: " +
  16267. std::to_string(body.size()) + "\r\n\r\n" + body;
  16268. ASSERT_TRUE(send_request(1, req));
  16269. }
  16270. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16271. auto handled = false;
  16272. Server svr;
  16273. svr.Post("/test", [&](const Request &req, Response &) {
  16274. ASSERT_EQ(2u, req.form.fields.size());
  16275. const auto &text1 = req.form.get_field("text1");
  16276. ASSERT_EQ("text1", text1);
  16277. const auto &text2 = req.form.get_field("text2");
  16278. ASSERT_EQ("text2", text2);
  16279. handled = true;
  16280. });
  16281. thread t = thread([&] { svr.listen(HOST, PORT); });
  16282. auto se = detail::scope_exit([&] {
  16283. svr.stop();
  16284. t.join();
  16285. ASSERT_FALSE(svr.is_running());
  16286. ASSERT_TRUE(handled);
  16287. });
  16288. svr.wait_until_ready();
  16289. auto req = "POST /test HTTP/1.1\r\n"
  16290. "Host: localhost\r\n"
  16291. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16292. "Content-Length: 146\r\n"
  16293. "\r\n----------\r\n"
  16294. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16295. "\r\n"
  16296. "text1"
  16297. "\r\n----------\r\n"
  16298. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16299. "\r\n"
  16300. "text2"
  16301. "\r\n------------";
  16302. std::string response;
  16303. ASSERT_TRUE(send_request(1, req, &response));
  16304. ASSERT_EQ("200", response.substr(9, 3));
  16305. }
  16306. TEST(MultipartFormDataTest, ContentLength) {
  16307. auto handled = false;
  16308. Server svr;
  16309. svr.Post("/test", [&](const Request &req, Response &) {
  16310. ASSERT_EQ(2u, req.form.fields.size());
  16311. const auto &text1 = req.form.get_field("text1");
  16312. ASSERT_EQ("text1", text1);
  16313. const auto &text2 = req.form.get_field("text2");
  16314. ASSERT_EQ("text2", text2);
  16315. handled = true;
  16316. });
  16317. thread t = thread([&] { svr.listen(HOST, PORT); });
  16318. auto se = detail::scope_exit([&] {
  16319. svr.stop();
  16320. t.join();
  16321. ASSERT_FALSE(svr.is_running());
  16322. ASSERT_TRUE(handled);
  16323. });
  16324. svr.wait_until_ready();
  16325. auto req = "POST /test HTTP/1.1\r\n"
  16326. "Host: localhost\r\n"
  16327. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16328. "Content-Length: 167\r\n"
  16329. "\r\n----------\r\n"
  16330. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16331. "Content-Length: 5\r\n"
  16332. "\r\n"
  16333. "text1"
  16334. "\r\n----------\r\n"
  16335. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16336. "\r\n"
  16337. "text2"
  16338. "\r\n------------\r\n";
  16339. std::string response;
  16340. ASSERT_TRUE(send_request(1, req, &response));
  16341. ASSERT_EQ("200", response.substr(9, 3));
  16342. }
  16343. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16344. auto handled = false;
  16345. Server svr;
  16346. svr.Post("/test", [&](const Request &req, Response &) {
  16347. ASSERT_EQ(2u, req.form.fields.size());
  16348. const auto &text1 = req.form.get_field("text1");
  16349. ASSERT_EQ("text1", text1);
  16350. // TODO: Add header access for text fields if needed
  16351. const auto &text2 = req.form.get_field("text2");
  16352. ASSERT_EQ("text2", text2);
  16353. // TODO: Header access for text fields needs to be implemented
  16354. // auto &headers = it->second.headers;
  16355. // ASSERT_EQ(3U, headers.size());
  16356. // auto custom_header = headers.find("x-whatever");
  16357. // ASSERT_TRUE(custom_header != headers.end());
  16358. // ASSERT_NE("customvalue", custom_header->second);
  16359. // ASSERT_EQ("CustomValue", custom_header->second);
  16360. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16361. handled = true;
  16362. });
  16363. thread t = thread([&] { svr.listen(HOST, PORT); });
  16364. auto se = detail::scope_exit([&] {
  16365. svr.stop();
  16366. t.join();
  16367. ASSERT_FALSE(svr.is_running());
  16368. ASSERT_TRUE(handled);
  16369. });
  16370. svr.wait_until_ready();
  16371. auto req = "POST /test HTTP/1.1\r\n"
  16372. "Host: localhost\r\n"
  16373. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16374. "Content-Length: 232\r\n"
  16375. "\r\n----------\r\n"
  16376. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16377. "Content-Length: 5\r\n"
  16378. "X-Test: 1\r\n"
  16379. "\r\n"
  16380. "text1"
  16381. "\r\n----------\r\n"
  16382. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16383. "Content-Type: text/plain\r\n"
  16384. "X-Whatever: CustomValue\r\n"
  16385. "\r\n"
  16386. "text2"
  16387. "\r\n------------\r\n"
  16388. "That should be disregarded. Not even read";
  16389. std::string response;
  16390. ASSERT_TRUE(send_request(1, req, &response));
  16391. ASSERT_EQ("200", response.substr(9, 3));
  16392. }
  16393. TEST(MultipartFormDataTest, LargeHeader) {
  16394. auto handled = false;
  16395. Server svr;
  16396. svr.Post("/test", [&](const Request &req, Response &) {
  16397. ASSERT_EQ(1u, req.form.fields.size());
  16398. const auto &text = req.form.get_field("name1");
  16399. ASSERT_EQ("text1", text);
  16400. handled = true;
  16401. });
  16402. thread t = thread([&] { svr.listen(HOST, PORT); });
  16403. auto se = detail::scope_exit([&] {
  16404. svr.stop();
  16405. t.join();
  16406. ASSERT_FALSE(svr.is_running());
  16407. ASSERT_TRUE(handled);
  16408. });
  16409. svr.wait_until_ready();
  16410. auto boundary = std::string("cpp-httplib-multipart-data");
  16411. std::string content = "--" + boundary +
  16412. "\r\n"
  16413. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16414. "\r\n"
  16415. "text1\r\n"
  16416. "--" +
  16417. boundary + "--\r\n";
  16418. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16419. "Host: localhost\r\n"
  16420. "Content-Type: multipart/form-data;boundary=" +
  16421. boundary +
  16422. "\r\n"
  16423. "Content-Length: " +
  16424. std::to_string(content.size()) +
  16425. "\r\n"
  16426. "Dummy-Header: ";
  16427. std::string header_suffix = "\r\n"
  16428. "\r\n";
  16429. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16430. size_t header_dummy_size =
  16431. read_buff_size -
  16432. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16433. auto header_dummy = std::string(header_dummy_size, '@');
  16434. auto req = header_prefix + header_dummy + header_suffix + content;
  16435. std::string response;
  16436. ASSERT_TRUE(send_request(1, req, &response));
  16437. ASSERT_EQ("200", response.substr(9, 3));
  16438. }
  16439. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16440. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16441. // (not chunked Transfer-Encoding) after the streaming refactor.
  16442. auto handled = false;
  16443. Server svr;
  16444. svr.Post("/upload", [&](const Request &req, Response &res) {
  16445. auto cl_it = req.headers.find("Content-Length");
  16446. EXPECT_TRUE(cl_it != req.headers.end());
  16447. auto te_it = req.headers.find("Transfer-Encoding");
  16448. EXPECT_TRUE(te_it == req.headers.end());
  16449. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16450. res.set_content("ok", "text/plain");
  16451. handled = true;
  16452. });
  16453. auto port = svr.bind_to_any_port(HOST);
  16454. auto t = thread([&] { svr.listen_after_bind(); });
  16455. auto se = detail::scope_exit([&] {
  16456. svr.stop();
  16457. t.join();
  16458. ASSERT_FALSE(svr.is_running());
  16459. ASSERT_TRUE(handled);
  16460. });
  16461. svr.wait_until_ready();
  16462. UploadFormDataItems items = {
  16463. {"field1", "hello", "", "text/plain"},
  16464. {"file1", "world", "test.txt", "application/octet-stream"},
  16465. };
  16466. Client cli(HOST, port);
  16467. auto res = cli.Post("/upload", {}, items);
  16468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16469. EXPECT_EQ(StatusCode::OK_200, res->status);
  16470. }
  16471. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16472. // Verify that make_multipart_content_provider coalesces many small segments
  16473. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16474. constexpr size_t kItemCount = 1000;
  16475. UploadFormDataItems items;
  16476. items.reserve(kItemCount);
  16477. for (size_t i = 0; i < kItemCount; i++) {
  16478. items.push_back(
  16479. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16480. }
  16481. const std::string boundary = "----test-boundary";
  16482. auto content_length = detail::get_multipart_content_length(items, boundary);
  16483. auto provider = detail::make_multipart_content_provider(items, boundary);
  16484. // Drive the provider the same way write_content_with_progress does
  16485. size_t write_count = 0;
  16486. size_t total_bytes = 0;
  16487. DataSink sink;
  16488. size_t offset = 0;
  16489. sink.write = [&](const char *d, size_t l) -> bool {
  16490. (void)d;
  16491. write_count++;
  16492. total_bytes += l;
  16493. offset += l;
  16494. return true;
  16495. };
  16496. sink.is_writable = []() -> bool { return true; };
  16497. while (offset < content_length) {
  16498. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16499. }
  16500. EXPECT_EQ(content_length, total_bytes);
  16501. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16502. // With buffering into 64KB blocks, write_count should be much smaller.
  16503. auto segment_count = 3 * kItemCount + 1;
  16504. EXPECT_LT(write_count, segment_count / 10);
  16505. }
  16506. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16507. // Integration test: send many UploadFormDataItems and verify the server
  16508. // receives all of them correctly (#2410).
  16509. constexpr size_t kItemCount = 500;
  16510. auto handled = false;
  16511. Server svr;
  16512. svr.Post("/upload", [&](const Request &req, Response &res) {
  16513. EXPECT_EQ(kItemCount, req.form.fields.size());
  16514. for (size_t i = 0; i < kItemCount; i++) {
  16515. auto key = "field" + std::to_string(i);
  16516. auto val = "value" + std::to_string(i);
  16517. auto it = req.form.fields.find(key);
  16518. if (it != req.form.fields.end()) {
  16519. EXPECT_EQ(val, it->second.content);
  16520. } else {
  16521. ADD_FAILURE() << "Missing field: " << key;
  16522. }
  16523. }
  16524. res.set_content("ok", "text/plain");
  16525. handled = true;
  16526. });
  16527. auto port = svr.bind_to_any_port(HOST);
  16528. auto t = thread([&] { svr.listen_after_bind(); });
  16529. auto se = detail::scope_exit([&] {
  16530. svr.stop();
  16531. t.join();
  16532. ASSERT_FALSE(svr.is_running());
  16533. ASSERT_TRUE(handled);
  16534. });
  16535. svr.wait_until_ready();
  16536. UploadFormDataItems items;
  16537. items.reserve(kItemCount);
  16538. for (size_t i = 0; i < kItemCount; i++) {
  16539. items.push_back(
  16540. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16541. }
  16542. Client cli(HOST, port);
  16543. auto res = cli.Post("/upload", items);
  16544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16545. EXPECT_EQ(StatusCode::OK_200, res->status);
  16546. }
  16547. TEST(MultipartFormDataTest, MakeFileProvider) {
  16548. // Verify make_file_provider sends a file's contents correctly.
  16549. const std::string file_content(4096, 'Z');
  16550. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16551. {
  16552. std::ofstream ofs(tmp_path, std::ios::binary);
  16553. ofs.write(file_content.data(),
  16554. static_cast<std::streamsize>(file_content.size()));
  16555. }
  16556. auto handled = false;
  16557. Server svr;
  16558. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16559. const ContentReader &content_reader) {
  16560. ASSERT_TRUE(req.is_multipart_form_data());
  16561. std::vector<FormData> items;
  16562. content_reader(
  16563. [&](const FormData &file) {
  16564. items.push_back(file);
  16565. return true;
  16566. },
  16567. [&](const char *data, size_t data_length) {
  16568. items.back().content.append(data, data_length);
  16569. return true;
  16570. });
  16571. ASSERT_EQ(1u, items.size());
  16572. EXPECT_EQ("myfile", items[0].name);
  16573. EXPECT_EQ("data.bin", items[0].filename);
  16574. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16575. EXPECT_EQ(file_content, items[0].content);
  16576. handled = true;
  16577. });
  16578. auto port = svr.bind_to_any_port(HOST);
  16579. auto t = thread([&] { svr.listen_after_bind(); });
  16580. auto se = detail::scope_exit([&] {
  16581. svr.stop();
  16582. t.join();
  16583. ASSERT_FALSE(svr.is_running());
  16584. ASSERT_TRUE(handled);
  16585. std::remove(tmp_path.c_str());
  16586. });
  16587. svr.wait_until_ready();
  16588. FormDataProviderItems providers;
  16589. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16590. "application/octet-stream"));
  16591. Client cli(HOST, port);
  16592. auto res = cli.Post("/upload", {}, {}, providers);
  16593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16594. EXPECT_EQ(StatusCode::OK_200, res->status);
  16595. }
  16596. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16597. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16598. // (100) headers is rejected with a 400 Bad Request response.
  16599. Server svr;
  16600. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16601. res.set_content("ok", "text/plain");
  16602. });
  16603. thread t = thread([&] { svr.listen(HOST, PORT); });
  16604. auto se = detail::scope_exit([&] {
  16605. svr.stop();
  16606. t.join();
  16607. ASSERT_FALSE(svr.is_running());
  16608. });
  16609. svr.wait_until_ready();
  16610. // Build a multipart part with 101 custom headers (exceeding
  16611. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16612. std::stringstream body;
  16613. body << "--simpleboundary\r\n"
  16614. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16615. for (int i = 0; i < 101; i++) {
  16616. body << "X-Custom-Header-" << i << ": value\r\n";
  16617. }
  16618. body << "\r\n"
  16619. << "value1\r\n"
  16620. << "--simpleboundary--\r\n";
  16621. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16622. Client cli(HOST, PORT);
  16623. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16625. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16626. }
  16627. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16628. // A body that never contains the declared boundary must not be accumulated
  16629. // while the parser waits for it. Buffering it would also make every read
  16630. // rescan everything seen so far, which is quadratic in the body size.
  16631. Server svr;
  16632. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16633. res.set_content("ok", "text/plain");
  16634. });
  16635. auto port = svr.bind_to_any_port(HOST);
  16636. thread t = thread([&] { svr.listen_after_bind(); });
  16637. auto se = detail::scope_exit([&] {
  16638. svr.stop();
  16639. t.join();
  16640. ASSERT_FALSE(svr.is_running());
  16641. });
  16642. svr.wait_until_ready();
  16643. Client cli(HOST, port);
  16644. cli.set_read_timeout(60, 0);
  16645. cli.set_write_timeout(60, 0);
  16646. // '-' is the worst case: it matches the first character of the boundary, so
  16647. // every position has to be checked against it.
  16648. auto post_dashes = [&](size_t size) {
  16649. const std::string body(size, '-');
  16650. auto start = std::chrono::steady_clock::now();
  16651. auto res =
  16652. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16653. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16654. std::chrono::steady_clock::now() - start)
  16655. .count();
  16656. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16657. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16658. return ms;
  16659. };
  16660. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16661. // Windows.
  16662. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16663. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16664. // Comparing the two sizes rather than checking an absolute duration keeps
  16665. // this meaningful across build types and CI load, both of which move the
  16666. // absolute numbers by more than an order of magnitude. Four times the bytes
  16667. // costs about four times the time when parsing is linear, and about sixteen
  16668. // times when the body is buffered and rescanned.
  16669. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16670. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16671. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16672. << "ms, which suggests the body is being buffered and rescanned";
  16673. }
  16674. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16675. // A boundary can only be followed by CRLF or by "--", so anything else is
  16676. // malformed no matter what comes next. The parser must say so right away
  16677. // instead of buffering the rest of the declared body.
  16678. Server svr;
  16679. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16680. res.set_content("ok", "text/plain");
  16681. });
  16682. auto port = svr.bind_to_any_port(HOST);
  16683. thread t = thread([&] { svr.listen_after_bind(); });
  16684. auto se = detail::scope_exit([&] {
  16685. svr.stop();
  16686. t.join();
  16687. ASSERT_FALSE(svr.is_running());
  16688. });
  16689. svr.wait_until_ready();
  16690. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16691. // buffers instead of failing would still be waiting for the remaining bytes.
  16692. const std::string body = "--zzzz\r\n"
  16693. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16694. "\r\n"
  16695. "text1"
  16696. "\r\n--zzzzXX";
  16697. const std::string req = "POST /post HTTP/1.1\r\n"
  16698. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16699. "Content-Length: 1048576\r\n"
  16700. "\r\n" +
  16701. body;
  16702. std::string response;
  16703. ASSERT_TRUE(send_request(3, req, &response, port));
  16704. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16705. EXPECT_EQ("400", response.substr(9, 3));
  16706. }
  16707. // Posts a multipart body split into two writes, so that the server sees the
  16708. // split at whatever offset the caller chose, and expects the single "text1"
  16709. // field to come through.
  16710. static void expect_split_multipart_ok(const std::string &body1,
  16711. const std::string &body2) {
  16712. auto handled = false;
  16713. Server svr;
  16714. svr.Post("/post", [&](const Request &req, Response &) {
  16715. EXPECT_EQ(1u, req.form.fields.size());
  16716. EXPECT_EQ("text1", req.form.get_field("text1"));
  16717. handled = true;
  16718. });
  16719. auto port = svr.bind_to_any_port(HOST);
  16720. thread t = thread([&] { svr.listen_after_bind(); });
  16721. auto se = detail::scope_exit([&] {
  16722. svr.stop();
  16723. t.join();
  16724. ASSERT_FALSE(svr.is_running());
  16725. ASSERT_TRUE(handled);
  16726. });
  16727. svr.wait_until_ready();
  16728. // "Connection: close" makes the server close once it has answered, so the
  16729. // response drain ends immediately instead of idling until the read timeout.
  16730. const std::string head =
  16731. "POST /post HTTP/1.1\r\n"
  16732. "Host: localhost\r\n"
  16733. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16734. "Connection: close\r\n"
  16735. "Content-Length: " +
  16736. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16737. std::string response;
  16738. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16739. ASSERT_GE(response.size(), 12u) << "no response";
  16740. EXPECT_EQ("200", response.substr(9, 3));
  16741. }
  16742. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16743. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16744. // ignored, including when it does not arrive in the same read as the
  16745. // close-delimiter itself.
  16746. expect_split_multipart_ok("--zzzz\r\n"
  16747. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16748. "\r\n"
  16749. "text1"
  16750. "\r\n--zzzz--",
  16751. "\r\nthis epilogue must be ignored\r\n");
  16752. }
  16753. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16754. // The initial boundary may be preceded by a preamble of any length and may
  16755. // straddle a read boundary. Discarding data while waiting for it must not
  16756. // throw away a partial boundary sitting at the end of the buffer.
  16757. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16758. "zz\r\n"
  16759. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16760. "\r\n"
  16761. "text1"
  16762. "\r\n--zzzz--\r\n");
  16763. }
  16764. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16765. // The received boundary was only checked for being non-empty, so it could be
  16766. // as long as a header is allowed to be. The parser scans the body for
  16767. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16768. // costs a nearly full comparison at nearly every position, making the
  16769. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16770. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16771. Server svr;
  16772. svr.Post("/post", [](const Request &req, Response &res) {
  16773. EXPECT_EQ(1u, req.form.fields.size());
  16774. EXPECT_EQ("text1", req.form.get_field("text1"));
  16775. res.set_content("ok", "text/plain");
  16776. });
  16777. auto port = svr.bind_to_any_port(HOST);
  16778. thread t = thread([&] { svr.listen_after_bind(); });
  16779. auto se = detail::scope_exit([&] {
  16780. svr.stop();
  16781. t.join();
  16782. ASSERT_FALSE(svr.is_running());
  16783. });
  16784. svr.wait_until_ready();
  16785. Client cli(HOST, port);
  16786. auto post_with_boundary_of_length = [&](size_t len) {
  16787. const std::string boundary(len, 'a');
  16788. const std::string body =
  16789. "--" + boundary +
  16790. "\r\n"
  16791. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16792. "\r\n"
  16793. "text1"
  16794. "\r\n--" +
  16795. boundary + "--\r\n";
  16796. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16797. };
  16798. auto res = post_with_boundary_of_length(70);
  16799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16800. EXPECT_EQ(StatusCode::OK_200, res->status);
  16801. res = post_with_boundary_of_length(71);
  16802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16803. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16804. }
  16805. TEST(MakeFileBodyTest, Basic) {
  16806. const std::string file_content(4096, 'Z');
  16807. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16808. {
  16809. std::ofstream ofs(tmp_path, std::ios::binary);
  16810. ofs.write(file_content.data(),
  16811. static_cast<std::streamsize>(file_content.size()));
  16812. }
  16813. auto handled = false;
  16814. Server svr;
  16815. svr.Post("/upload", [&](const Request &req, Response &res) {
  16816. EXPECT_EQ(file_content, req.body);
  16817. handled = true;
  16818. res.status = StatusCode::OK_200;
  16819. });
  16820. auto port = svr.bind_to_any_port(HOST);
  16821. auto t = thread([&] { svr.listen_after_bind(); });
  16822. auto se = detail::scope_exit([&] {
  16823. svr.stop();
  16824. t.join();
  16825. ASSERT_FALSE(svr.is_running());
  16826. ASSERT_TRUE(handled);
  16827. std::remove(tmp_path.c_str());
  16828. });
  16829. svr.wait_until_ready();
  16830. auto fb = make_file_body(tmp_path);
  16831. ASSERT_GT(fb.first, 0u);
  16832. Client cli(HOST, port);
  16833. auto res =
  16834. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16836. EXPECT_EQ(StatusCode::OK_200, res->status);
  16837. }
  16838. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16839. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16840. {
  16841. std::ofstream ofs(path, std::ios::binary);
  16842. const std::string content(100, 'A');
  16843. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16844. }
  16845. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16846. auto body = make_file_body(path);
  16847. ASSERT_EQ(100u, body.first);
  16848. ASSERT_TRUE(static_cast<bool>(body.second));
  16849. // Rewritten shorter after its length was measured - and, on a server, after
  16850. // that length has already gone out as Content-Length.
  16851. {
  16852. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16853. const std::string content(10, 'A');
  16854. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16855. }
  16856. std::string written;
  16857. DataSink sink;
  16858. sink.write = [&](const char *d, size_t l) {
  16859. written.append(d, l);
  16860. return true;
  16861. };
  16862. // The provider has to report failure. write_content_with_progress() advances
  16863. // its offset only by what was written, so a provider that returns true
  16864. // without completing the length it promised is called again straight away,
  16865. // and again.
  16866. EXPECT_FALSE(body.second(0, body.first, sink));
  16867. EXPECT_EQ(std::string(10, 'A'), written);
  16868. }
  16869. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16870. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16871. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16872. {
  16873. std::ofstream ofs(path, std::ios::binary);
  16874. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16875. }
  16876. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16877. auto body = make_file_body(path);
  16878. ASSERT_EQ(content.size(), body.first);
  16879. ASSERT_TRUE(static_cast<bool>(body.second));
  16880. std::string written;
  16881. DataSink sink;
  16882. sink.write = [&](const char *d, size_t l) {
  16883. written.append(d, l);
  16884. return true;
  16885. };
  16886. EXPECT_TRUE(body.second(0, body.first, sink));
  16887. EXPECT_EQ(content, written);
  16888. }
  16889. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16890. static constexpr unsigned int number_of_tasks{1000000};
  16891. std::atomic_uint count{0};
  16892. std::unique_ptr<TaskQueue> task_queue{
  16893. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16894. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16895. auto queued = task_queue->enqueue(
  16896. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16897. EXPECT_TRUE(queued);
  16898. }
  16899. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16900. task_queue->shutdown();
  16901. #else
  16902. EXPECT_NO_THROW(task_queue->shutdown());
  16903. #endif
  16904. EXPECT_EQ(number_of_tasks, count.load());
  16905. }
  16906. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16907. static constexpr unsigned int number_of_tasks{1000000};
  16908. static constexpr unsigned int qlimit{2};
  16909. unsigned int queued_count{0};
  16910. std::atomic_uint count{0};
  16911. std::unique_ptr<TaskQueue> task_queue{
  16912. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16913. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16914. if (task_queue->enqueue(
  16915. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16916. queued_count++;
  16917. }
  16918. }
  16919. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16920. task_queue->shutdown();
  16921. #else
  16922. EXPECT_NO_THROW(task_queue->shutdown());
  16923. #endif
  16924. EXPECT_EQ(queued_count, count.load());
  16925. EXPECT_TRUE(queued_count <= number_of_tasks);
  16926. EXPECT_TRUE(queued_count >= qlimit);
  16927. }
  16928. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16929. // Use a short idle timeout so a dynamic thread spawns, times out and
  16930. // exits during the test, and the pool keeps working afterwards.
  16931. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16932. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16933. /*idle_timeout_sec=*/1}};
  16934. std::atomic_uint count{0};
  16935. std::condition_variable cv;
  16936. std::mutex mtx;
  16937. bool release = false;
  16938. // Block the base thread so the second task spawns a dynamic thread.
  16939. EXPECT_TRUE(task_queue->enqueue([&] {
  16940. std::unique_lock<std::mutex> lock(mtx);
  16941. while (!release) {
  16942. cv.wait(lock);
  16943. }
  16944. count++;
  16945. }));
  16946. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16947. // Let the dynamic thread finish its task and exceed the idle timeout.
  16948. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16949. {
  16950. std::unique_lock<std::mutex> lock(mtx);
  16951. release = true;
  16952. }
  16953. cv.notify_all();
  16954. // The pool must still accept and run tasks after the dynamic thread exited.
  16955. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16956. task_queue->shutdown();
  16957. EXPECT_EQ(3u, count.load());
  16958. }
  16959. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16960. static constexpr size_t number_of_tasks{32};
  16961. std::unique_ptr<TaskQueue> task_queue{
  16962. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16963. // Let the base threads go idle so the burst below finds them waiting.
  16964. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16965. std::mutex mtx;
  16966. std::condition_variable cv;
  16967. size_t running = 0;
  16968. bool release = false;
  16969. for (size_t i = 0; i < number_of_tasks; i++) {
  16970. EXPECT_TRUE(task_queue->enqueue([&] {
  16971. std::unique_lock<std::mutex> lock(mtx);
  16972. running++;
  16973. cv.notify_all();
  16974. cv.wait(lock, [&] { return release; });
  16975. }));
  16976. }
  16977. {
  16978. std::unique_lock<std::mutex> lock(mtx);
  16979. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16980. [&] { return running == number_of_tasks; }));
  16981. release = true;
  16982. }
  16983. cv.notify_all();
  16984. task_queue->shutdown();
  16985. }
  16986. TEST(TaskQueueTest, MaxQueuedRequests) {
  16987. static constexpr unsigned int qlimit{3};
  16988. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16989. std::condition_variable sem_cv;
  16990. std::mutex sem_mtx;
  16991. int credits = 0;
  16992. bool queued;
  16993. /* Fill up the queue with tasks that will block until we give them credits to
  16994. * complete. */
  16995. for (unsigned int n = 0; n <= qlimit;) {
  16996. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16997. std::unique_lock<std::mutex> lock(sem_mtx);
  16998. while (credits <= 0) {
  16999. sem_cv.wait(lock);
  17000. }
  17001. /* Consume the credit and signal the test code if they are all gone. */
  17002. if (--credits == 0) { sem_cv.notify_one(); }
  17003. });
  17004. if (n < qlimit) {
  17005. /* The first qlimit enqueues must succeed. */
  17006. EXPECT_TRUE(queued);
  17007. } else {
  17008. /* The last one will succeed only when the worker thread
  17009. * starts and dequeues the first blocking task. Although
  17010. * not necessary for the correctness of this test, we sleep for
  17011. * a short while to avoid busy waiting. */
  17012. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17013. }
  17014. if (queued) { n++; }
  17015. }
  17016. /* Further enqueues must fail since the queue is full. */
  17017. for (auto i = 0; i < 4; i++) {
  17018. queued = task_queue->enqueue([] {});
  17019. EXPECT_FALSE(queued);
  17020. }
  17021. /* Give the credits to allow the previous tasks to complete. */
  17022. {
  17023. std::unique_lock<std::mutex> lock(sem_mtx);
  17024. credits += qlimit + 1;
  17025. }
  17026. sem_cv.notify_all();
  17027. /* Wait for all the credits to be consumed. */
  17028. {
  17029. std::unique_lock<std::mutex> lock(sem_mtx);
  17030. while (credits > 0) {
  17031. sem_cv.wait(lock);
  17032. }
  17033. }
  17034. /* Check that we are able again to enqueue at least qlimit tasks. */
  17035. for (unsigned int i = 0; i < qlimit; i++) {
  17036. queued = task_queue->enqueue([] {});
  17037. EXPECT_TRUE(queued);
  17038. }
  17039. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17040. task_queue->shutdown();
  17041. #else
  17042. EXPECT_NO_THROW(task_queue->shutdown());
  17043. #endif
  17044. }
  17045. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17046. Server svr;
  17047. std::string method;
  17048. std::string body;
  17049. auto has_content_length = false;
  17050. auto has_transfer_encoding = false;
  17051. std::atomic<int> bad_requests{0};
  17052. // Leftover body bytes get parsed as a malformed request and answered with
  17053. // 400
  17054. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17055. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17056. });
  17057. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17058. res.set_redirect("/down", StatusCode::SeeOther_303);
  17059. });
  17060. svr.Get("/down", [&](const Request &req, Response &res) {
  17061. method = req.method;
  17062. body = req.body;
  17063. has_content_length = req.has_header("Content-Length");
  17064. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17065. res.set_content("ok", "text/plain");
  17066. });
  17067. auto port = svr.bind_to_any_port(HOST);
  17068. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17069. auto se = detail::scope_exit([&] {
  17070. svr.stop();
  17071. thread.join();
  17072. ASSERT_FALSE(svr.is_running());
  17073. });
  17074. svr.wait_until_ready();
  17075. const std::string payload = "SECRET-BODY";
  17076. auto check = [&](Client &cli, const Result &res) {
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. EXPECT_EQ(StatusCode::OK_200, res->status);
  17079. EXPECT_EQ("ok", res->body);
  17080. EXPECT_EQ("GET", method);
  17081. EXPECT_TRUE(body.empty());
  17082. EXPECT_FALSE(has_content_length);
  17083. EXPECT_FALSE(has_transfer_encoding);
  17084. // Nothing of the original body may be left on the connection
  17085. auto res2 = cli.Get("/down");
  17086. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17087. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17088. EXPECT_EQ("ok", res2->body);
  17089. EXPECT_EQ(0, bad_requests);
  17090. };
  17091. // With content length
  17092. {
  17093. Client cli(HOST, port);
  17094. cli.set_keep_alive(true);
  17095. cli.set_follow_location(true);
  17096. auto res = cli.Post(
  17097. "/up", payload.size(),
  17098. [&](size_t offset, size_t length, DataSink &sink) {
  17099. return sink.write(payload.data() + offset, length);
  17100. },
  17101. "text/plain");
  17102. check(cli, res);
  17103. }
  17104. // Without content length (chunked)
  17105. {
  17106. Client cli(HOST, port);
  17107. cli.set_keep_alive(true);
  17108. cli.set_follow_location(true);
  17109. auto res = cli.Post(
  17110. "/up",
  17111. [&](size_t /*offset*/, DataSink &sink) {
  17112. sink.write(payload.data(), payload.size());
  17113. sink.done();
  17114. return true;
  17115. },
  17116. "text/plain");
  17117. check(cli, res);
  17118. }
  17119. }
  17120. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17121. Server svr;
  17122. std::string target;
  17123. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17124. // Echo the still-encoded name back in the Location
  17125. const std::string prefix = "/start/";
  17126. res.status = StatusCode::Found_302;
  17127. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17128. });
  17129. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17130. target = req.target;
  17131. res.set_content("ok", "text/plain");
  17132. });
  17133. auto port = svr.bind_to_any_port(HOST);
  17134. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17135. auto se = detail::scope_exit([&] {
  17136. svr.stop();
  17137. thread.join();
  17138. ASSERT_FALSE(svr.is_running());
  17139. });
  17140. svr.wait_until_ready();
  17141. // Decoding the Location path would turn the first four into a path
  17142. // separator, a query delimiter, a fragment delimiter and a different
  17143. // percent-encoded octet. The rest must keep reaching the server as they are.
  17144. const std::vector<std::string> names = {
  17145. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17146. };
  17147. for (auto path_encode : {true, false}) {
  17148. Client cli(HOST, port);
  17149. cli.set_follow_location(true);
  17150. cli.set_path_encode(path_encode);
  17151. for (const auto &name : names) {
  17152. target.clear();
  17153. auto res = cli.Get("/start/" + name);
  17154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17155. EXPECT_EQ(StatusCode::OK_200, res->status);
  17156. EXPECT_EQ("/dest/" + name, target);
  17157. }
  17158. }
  17159. }
  17160. TEST(RedirectTest, NotModifiedIsReturned) {
  17161. Server svr;
  17162. svr.Get("/cached", [](const Request &, Response &res) {
  17163. res.status = StatusCode::NotModified_304;
  17164. });
  17165. auto port = svr.bind_to_any_port(HOST);
  17166. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17167. auto se = detail::scope_exit([&] {
  17168. svr.stop();
  17169. thread.join();
  17170. ASSERT_FALSE(svr.is_running());
  17171. });
  17172. svr.wait_until_ready();
  17173. Client cli(HOST, port);
  17174. cli.set_follow_location(true);
  17175. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17177. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17178. }
  17179. TEST(RedirectTest, NoLocationIsReturned) {
  17180. Server svr;
  17181. svr.Get("/no-location", [](const Request &, Response &res) {
  17182. res.status = StatusCode::Found_302;
  17183. res.set_content("no location", "text/plain");
  17184. });
  17185. auto port = svr.bind_to_any_port(HOST);
  17186. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17187. auto se = detail::scope_exit([&] {
  17188. svr.stop();
  17189. thread.join();
  17190. ASSERT_FALSE(svr.is_running());
  17191. });
  17192. svr.wait_until_ready();
  17193. Client cli(HOST, port);
  17194. cli.set_follow_location(true);
  17195. auto res = cli.Get("/no-location");
  17196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17197. EXPECT_EQ(StatusCode::Found_302, res->status);
  17198. EXPECT_EQ("no location", res->body);
  17199. // The callbacks see the body of the response that is returned
  17200. auto handler_called = false;
  17201. auto progress_called = false;
  17202. std::string body;
  17203. auto res2 = cli.Get(
  17204. "/no-location",
  17205. [&](const Response &) {
  17206. handler_called = true;
  17207. return true;
  17208. },
  17209. [&](const char *data, size_t data_length) {
  17210. body.append(data, data_length);
  17211. return true;
  17212. },
  17213. [&](size_t, size_t) {
  17214. progress_called = true;
  17215. return true;
  17216. });
  17217. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17218. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17219. EXPECT_TRUE(handler_called);
  17220. EXPECT_TRUE(progress_called);
  17221. EXPECT_EQ("no location", body);
  17222. }
  17223. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17224. Server svr;
  17225. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17226. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17227. });
  17228. svr.Get("/hello", [](const Request &req, Response &res) {
  17229. res.set_content(req.get_param_value("key"), "text/plain");
  17230. });
  17231. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17232. auto se = detail::scope_exit([&] {
  17233. svr.stop();
  17234. thread.join();
  17235. ASSERT_FALSE(svr.is_running());
  17236. });
  17237. svr.wait_until_ready();
  17238. {
  17239. Client cli(HOST, PORT);
  17240. cli.set_follow_location(true);
  17241. auto res = cli.Get("/");
  17242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17243. EXPECT_EQ(StatusCode::OK_200, res->status);
  17244. EXPECT_EQ("val&key2=val2", res->body);
  17245. }
  17246. }
  17247. #endif
  17248. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17249. Server svr;
  17250. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17251. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17252. });
  17253. svr.Get("/hello", [](const Request &req, Response &res) {
  17254. res.set_content(req.get_param_value("key"), "text/plain");
  17255. });
  17256. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17257. auto se = detail::scope_exit([&] {
  17258. svr.stop();
  17259. thread.join();
  17260. ASSERT_FALSE(svr.is_running());
  17261. });
  17262. svr.wait_until_ready();
  17263. {
  17264. Client cli(HOST, PORT);
  17265. cli.set_follow_location(true);
  17266. auto res = cli.Get("/");
  17267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17268. EXPECT_EQ(StatusCode::OK_200, res->status);
  17269. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17270. }
  17271. }
  17272. TEST(RedirectTest, RedirectWithPlusInPath) {
  17273. Server svr;
  17274. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17275. res.set_redirect("/a+b");
  17276. });
  17277. // Route pattern uses regex; escape + as \\+
  17278. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17279. res.set_content(req.path, "text/plain");
  17280. });
  17281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17282. auto se = detail::scope_exit([&] {
  17283. svr.stop();
  17284. thread.join();
  17285. ASSERT_FALSE(svr.is_running());
  17286. });
  17287. svr.wait_until_ready();
  17288. {
  17289. Client cli(HOST, PORT);
  17290. cli.set_follow_location(true);
  17291. auto res = cli.Get("/");
  17292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17293. EXPECT_EQ(StatusCode::OK_200, res->status);
  17294. EXPECT_EQ("/a+b", res->body);
  17295. }
  17296. }
  17297. TEST(RedirectTest, ResolveRelativeLocation) {
  17298. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17299. const std::vector<std::pair<std::string, std::string>> cases = {
  17300. {"g", "/b/c/g"},
  17301. {"./g", "/b/c/g"},
  17302. {"g/", "/b/c/g/"},
  17303. {"?y", "/b/c/d;p?y"},
  17304. {"g?y", "/b/c/g?y"},
  17305. {"#s", "/b/c/d;p?q#s"},
  17306. {"g#s", "/b/c/g#s"},
  17307. {"g?y#s", "/b/c/g?y#s"},
  17308. {";x", "/b/c/;x"},
  17309. {"g;x", "/b/c/g;x"},
  17310. {".", "/b/c/"},
  17311. {"./", "/b/c/"},
  17312. {"..", "/b/"},
  17313. {"../", "/b/"},
  17314. {"../g", "/b/g"},
  17315. {"../..", "/"},
  17316. {"../../", "/"},
  17317. {"../../g", "/g"},
  17318. {"../../../g", "/g"},
  17319. {"g.", "/b/c/g."},
  17320. {".g", "/b/c/.g"},
  17321. {"g..", "/b/c/g.."},
  17322. {"..g", "/b/c/..g"},
  17323. {"./../g", "/b/g"},
  17324. {"./g/.", "/b/c/g/"},
  17325. {"g/./h", "/b/c/g/h"},
  17326. {"g/../h", "/b/c/h"},
  17327. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17328. {"g;x=1/../y", "/b/c/y"},
  17329. {"g?y/./x", "/b/c/g?y/./x"},
  17330. {"g#s/../x", "/b/c/g#s/../x"},
  17331. // Not relative-path references, so left for parse_url.
  17332. {"/g", "/g"},
  17333. {"//g", "//g"},
  17334. {"http://g/x", "http://g/x"},
  17335. {"g:h", "g:h"},
  17336. };
  17337. for (const auto &c : cases) {
  17338. EXPECT_EQ(c.second,
  17339. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17340. << c.first;
  17341. }
  17342. }
  17343. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17344. Server svr;
  17345. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17346. res.set_redirect(req.get_param_value("to"));
  17347. });
  17348. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17349. res.set_content(req.target, "text/plain");
  17350. });
  17351. svr.Get("/other", [](const Request &req, Response &res) {
  17352. res.set_content(req.target, "text/plain");
  17353. });
  17354. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17355. auto se = detail::scope_exit([&] {
  17356. svr.stop();
  17357. thread.join();
  17358. ASSERT_FALSE(svr.is_running());
  17359. });
  17360. svr.wait_until_ready();
  17361. const std::vector<std::pair<std::string, std::string>> cases = {
  17362. {"next", "/dir/next"},
  17363. {"./next?x=1", "/dir/next?x=1"},
  17364. {"../other", "/other"},
  17365. };
  17366. for (const auto &c : cases) {
  17367. Client cli(HOST, PORT);
  17368. cli.set_follow_location(true);
  17369. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17370. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17371. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17372. EXPECT_EQ(c.second, res->body) << c.first;
  17373. }
  17374. }
  17375. #ifdef CPPHTTPLIB_SSL_ENABLED
  17376. TEST(RedirectTest, Issue2185_Online) {
  17377. SSLClient client("github.com");
  17378. client.set_follow_location(true);
  17379. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17380. "Coollab-Windows.zip");
  17381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17382. EXPECT_EQ(StatusCode::OK_200, res->status);
  17383. EXPECT_EQ(9920427U, res->body.size());
  17384. }
  17385. #endif
  17386. TEST(VulnerabilityTest, CRLFInjection) {
  17387. Server svr;
  17388. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17389. res.set_content("Hello 1", "text/plain");
  17390. });
  17391. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17392. res.set_content("Hello 2", "text/plain");
  17393. });
  17394. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17395. res.set_content("Hello 3", "text/plain");
  17396. });
  17397. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17398. res.set_content("Hello 4", "text/plain");
  17399. });
  17400. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17401. for (const auto &x : req.headers) {
  17402. auto key = x.first;
  17403. EXPECT_STRNE("evil", key.c_str());
  17404. }
  17405. });
  17406. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17407. auto se = detail::scope_exit([&] {
  17408. svr.stop();
  17409. thread.join();
  17410. ASSERT_FALSE(svr.is_running());
  17411. });
  17412. svr.wait_until_ready();
  17413. {
  17414. Client cli(HOST, PORT);
  17415. cli.Post("/test1", "A=B",
  17416. "application/x-www-form-urlencoded\r\nevil: hello1");
  17417. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17418. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17419. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17420. }
  17421. }
  17422. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17423. auto server_thread = std::thread([] {
  17424. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17425. default_socket_options(srv);
  17426. sockaddr_in addr{};
  17427. addr.sin_family = AF_INET;
  17428. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17429. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17430. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17431. ::listen(srv, 1);
  17432. sockaddr_in cli_addr{};
  17433. socklen_t cli_len = sizeof(cli_addr);
  17434. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17435. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17436. std::string buf_all;
  17437. char buf[2048];
  17438. ssize_t n;
  17439. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17440. buf_all.append(buf, static_cast<size_t>(n));
  17441. size_t pos;
  17442. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17443. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17444. auto e = request_block.find("\r\n");
  17445. if (e != std::string::npos) {
  17446. auto request_line = request_block.substr(0, e);
  17447. std::string msg =
  17448. "CRLF injection detected in request line: '" + request_line + "'";
  17449. EXPECT_FALSE(true) << msg;
  17450. }
  17451. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17452. ::send(cli,
  17453. #ifdef _WIN32
  17454. static_cast<const char *>(resp.c_str()),
  17455. static_cast<int>(resp.size()),
  17456. #else
  17457. resp.c_str(), resp.size(),
  17458. #endif
  17459. 0);
  17460. buf_all.erase(0, pos + 4);
  17461. }
  17462. }
  17463. detail::close_socket(cli);
  17464. detail::close_socket(srv);
  17465. });
  17466. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17467. auto cli = Client("127.0.0.1", PORT + 1);
  17468. auto headers = Headers{
  17469. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17470. {"Connection", "keep-alive"}};
  17471. auto res = cli.Get("/hi", headers);
  17472. EXPECT_FALSE(res);
  17473. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17474. server_thread.join();
  17475. }
  17476. // A request rejected before any byte reaches the socket must fail right away
  17477. // instead of waiting for a response the server will never send.
  17478. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17479. // The kernel completes the TCP handshake from the listen backlog, so the
  17480. // client connects, but nothing ever reads, responds or closes.
  17481. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17482. default_socket_options(srv);
  17483. sockaddr_in addr{};
  17484. addr.sin_family = AF_INET;
  17485. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17486. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17487. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17488. ASSERT_EQ(0, ::listen(srv, 8));
  17489. auto cli = Client("127.0.0.1", PORT + 1);
  17490. cli.set_read_timeout(10, 0);
  17491. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17492. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17493. std::chrono::steady_clock::now() - start)
  17494. .count();
  17495. };
  17496. {
  17497. Request req;
  17498. req.method = "GE T";
  17499. req.path = "/";
  17500. auto start = std::chrono::steady_clock::now();
  17501. auto res = cli.send(req);
  17502. EXPECT_FALSE(res);
  17503. EXPECT_EQ(Error::Write, res.error());
  17504. EXPECT_LT(elapsed_ms(start), 1000);
  17505. }
  17506. {
  17507. auto start = std::chrono::steady_clock::now();
  17508. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17509. EXPECT_FALSE(res);
  17510. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17511. EXPECT_LT(elapsed_ms(start), 1000);
  17512. }
  17513. EXPECT_FALSE(cli.is_socket_open());
  17514. detail::close_socket(srv);
  17515. }
  17516. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17517. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17518. default_socket_options(srv);
  17519. sockaddr_in addr{};
  17520. addr.sin_family = AF_INET;
  17521. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17522. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17523. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17524. ASSERT_EQ(0, ::listen(srv, 1));
  17525. std::string received;
  17526. auto server_thread = std::thread([&] {
  17527. auto sock = ::accept(srv, nullptr, nullptr);
  17528. if (sock == INVALID_SOCKET) { return; }
  17529. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17530. char buf[2048];
  17531. ssize_t n;
  17532. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17533. received.append(buf, static_cast<size_t>(n));
  17534. }
  17535. detail::close_socket(sock);
  17536. });
  17537. {
  17538. auto cli = Client("127.0.0.1", PORT + 1);
  17539. // "Z" sorts after the default headers, so writing straight to the socket
  17540. // would have sent the request line and those headers before the rejection.
  17541. auto handle =
  17542. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17543. EXPECT_FALSE(handle.is_valid());
  17544. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17545. }
  17546. server_thread.join();
  17547. detail::close_socket(srv);
  17548. EXPECT_TRUE(received.empty()) << received;
  17549. }
  17550. TEST(PathParamsTest, StaticMatch) {
  17551. const auto pattern = "/users/all";
  17552. detail::PathParamsMatcher matcher(pattern);
  17553. Request request;
  17554. request.path = "/users/all";
  17555. ASSERT_TRUE(matcher.match(request));
  17556. std::unordered_map<std::string, std::string> expected_params = {};
  17557. EXPECT_EQ(request.path_params, expected_params);
  17558. }
  17559. TEST(PathParamsTest, StaticMismatch) {
  17560. const auto pattern = "/users/all";
  17561. detail::PathParamsMatcher matcher(pattern);
  17562. Request request;
  17563. request.path = "/users/1";
  17564. ASSERT_FALSE(matcher.match(request));
  17565. }
  17566. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17567. const auto pattern = "/users/:id/subscriptions";
  17568. detail::PathParamsMatcher matcher(pattern);
  17569. Request request;
  17570. request.path = "/users/42/subscriptions";
  17571. ASSERT_TRUE(matcher.match(request));
  17572. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17573. EXPECT_EQ(request.path_params, expected_params);
  17574. }
  17575. TEST(PathParamsTest, SingleParamInTheEnd) {
  17576. const auto pattern = "/users/:id";
  17577. detail::PathParamsMatcher matcher(pattern);
  17578. Request request;
  17579. request.path = "/users/24";
  17580. ASSERT_TRUE(matcher.match(request));
  17581. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17582. EXPECT_EQ(request.path_params, expected_params);
  17583. }
  17584. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17585. const auto pattern = "/users/:id/";
  17586. detail::PathParamsMatcher matcher(pattern);
  17587. Request request;
  17588. request.path = "/users/42/";
  17589. ASSERT_TRUE(matcher.match(request));
  17590. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17591. EXPECT_EQ(request.path_params, expected_params);
  17592. }
  17593. TEST(PathParamsTest, EmptyParam) {
  17594. const auto pattern = "/users/:id/";
  17595. detail::PathParamsMatcher matcher(pattern);
  17596. Request request;
  17597. request.path = "/users//";
  17598. ASSERT_TRUE(matcher.match(request));
  17599. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17600. EXPECT_EQ(request.path_params, expected_params);
  17601. }
  17602. TEST(PathParamsTest, FragmentMismatch) {
  17603. const auto pattern = "/users/:id/";
  17604. detail::PathParamsMatcher matcher(pattern);
  17605. Request request;
  17606. request.path = "/admins/24/";
  17607. ASSERT_FALSE(matcher.match(request));
  17608. }
  17609. TEST(PathParamsTest, ExtraFragments) {
  17610. const auto pattern = "/users/:id";
  17611. detail::PathParamsMatcher matcher(pattern);
  17612. Request request;
  17613. request.path = "/users/42/subscriptions";
  17614. ASSERT_FALSE(matcher.match(request));
  17615. }
  17616. TEST(PathParamsTest, MissingTrailingParam) {
  17617. const auto pattern = "/users/:id";
  17618. detail::PathParamsMatcher matcher(pattern);
  17619. Request request;
  17620. request.path = "/users";
  17621. ASSERT_FALSE(matcher.match(request));
  17622. }
  17623. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17624. const auto pattern = "/users/:id/subscriptions";
  17625. detail::PathParamsMatcher matcher(pattern);
  17626. Request request;
  17627. request.path = "/users/subscriptions";
  17628. ASSERT_FALSE(matcher.match(request));
  17629. }
  17630. TEST(PathParamsTest, MultipleParams) {
  17631. const auto pattern = "/users/:userid/subscriptions/:subid";
  17632. detail::PathParamsMatcher matcher(pattern);
  17633. Request request;
  17634. request.path = "/users/42/subscriptions/2";
  17635. ASSERT_TRUE(matcher.match(request));
  17636. std::unordered_map<std::string, std::string> expected_params = {
  17637. {"userid", "42"}, {"subid", "2"}};
  17638. EXPECT_EQ(request.path_params, expected_params);
  17639. }
  17640. TEST(PathParamsTest, SequenceOfParams) {
  17641. const auto pattern = "/values/:x/:y/:z";
  17642. detail::PathParamsMatcher matcher(pattern);
  17643. Request request;
  17644. request.path = "/values/1/2/3";
  17645. ASSERT_TRUE(matcher.match(request));
  17646. std::unordered_map<std::string, std::string> expected_params = {
  17647. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17648. EXPECT_EQ(request.path_params, expected_params);
  17649. }
  17650. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17651. const auto pattern = "/prefix:suffix";
  17652. detail::PathParamsMatcher matcher(pattern);
  17653. Request request;
  17654. request.path = "/prefix:suffix";
  17655. ASSERT_TRUE(matcher.match(request));
  17656. const std::unordered_map<std::string, std::string> expected_params = {};
  17657. EXPECT_EQ(request.path_params, expected_params);
  17658. }
  17659. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17660. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17661. // calling thread's stack on a long enough path for a quantified pattern;
  17662. // RegexMatcher must refuse to run regex matching on paths beyond
  17663. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17664. detail::RegexMatcher matcher("/files/(.*)");
  17665. Request within_limit;
  17666. within_limit.path = "/files/" + std::string(10, 'A');
  17667. EXPECT_TRUE(matcher.match(within_limit));
  17668. Request over_limit;
  17669. over_limit.path =
  17670. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17671. EXPECT_FALSE(matcher.match(over_limit));
  17672. }
  17673. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17674. Server svr;
  17675. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17676. res.set_content("ok", "text/plain");
  17677. });
  17678. auto port = svr.bind_to_any_port(HOST);
  17679. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17680. auto se = detail::scope_exit([&] {
  17681. svr.stop();
  17682. thread.join();
  17683. ASSERT_FALSE(svr.is_running());
  17684. });
  17685. svr.wait_until_ready();
  17686. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17687. // request URI limit; this used to be able to crash the process.
  17688. std::string path =
  17689. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17690. std::string req = "GET " + path +
  17691. " HTTP/1.1\r\n"
  17692. "Host: " +
  17693. std::string(HOST) + ":" + std::to_string(port) +
  17694. "\r\n"
  17695. "Connection: close\r\n"
  17696. "\r\n";
  17697. std::string response;
  17698. ASSERT_TRUE(send_request(5, req, &response, port));
  17699. EXPECT_NE(std::string::npos, response.find("404"));
  17700. }
  17701. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17702. Server svr;
  17703. auto handler = [](const Request & /*req*/, Response &res) {
  17704. res.set_content("hit", "text/plain");
  17705. };
  17706. // No regex metacharacter, so this one is compared literally
  17707. svr.Get("/literal/route", handler);
  17708. // '.' is a regex metacharacter, so this one must keep regex semantics
  17709. svr.Get("/a.c", handler);
  17710. auto port = svr.bind_to_any_port(HOST);
  17711. std::thread t([&]() { svr.listen_after_bind(); });
  17712. auto se = detail::scope_exit([&] {
  17713. svr.stop();
  17714. t.join();
  17715. ASSERT_FALSE(svr.is_running());
  17716. });
  17717. svr.wait_until_ready();
  17718. Client cli(HOST, port);
  17719. struct {
  17720. const char *path;
  17721. int status;
  17722. } cases[] = {
  17723. {"/literal/route", StatusCode::OK_200},
  17724. {"/literal/routes", StatusCode::NotFound_404},
  17725. {"/literal/rout", StatusCode::NotFound_404},
  17726. {"/abc", StatusCode::OK_200},
  17727. {"/a.c", StatusCode::OK_200},
  17728. };
  17729. for (const auto &x : cases) {
  17730. auto res = cli.Get(x.path);
  17731. ASSERT_TRUE(res) << x.path;
  17732. EXPECT_EQ(x.status, res->status) << x.path;
  17733. }
  17734. }
  17735. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17736. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17737. // from exhausting the stack, so it must only constrain routes that actually
  17738. // run a regular expression. A literal route is matched by comparison and
  17739. // stays usable at any length.
  17740. Server svr;
  17741. const std::string pattern =
  17742. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17743. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17744. res.set_content("hit", "text/plain");
  17745. });
  17746. auto port = svr.bind_to_any_port(HOST);
  17747. std::thread t([&]() { svr.listen_after_bind(); });
  17748. auto se = detail::scope_exit([&] {
  17749. svr.stop();
  17750. t.join();
  17751. ASSERT_FALSE(svr.is_running());
  17752. });
  17753. svr.wait_until_ready();
  17754. Client cli(HOST, port);
  17755. auto res = cli.Get(pattern);
  17756. ASSERT_TRUE(res);
  17757. EXPECT_EQ(StatusCode::OK_200, res->status);
  17758. }
  17759. TEST(ParseUrlTest, VariousPatterns) {
  17760. {
  17761. detail::UrlComponents uc;
  17762. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17763. EXPECT_EQ("http", uc.scheme);
  17764. EXPECT_EQ("example.com", uc.host);
  17765. EXPECT_EQ("8080", uc.port);
  17766. EXPECT_EQ("/path", uc.path);
  17767. EXPECT_EQ("?q=1", uc.query);
  17768. }
  17769. {
  17770. detail::UrlComponents uc;
  17771. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17772. EXPECT_EQ("https", uc.scheme);
  17773. EXPECT_EQ("example.com", uc.host);
  17774. EXPECT_TRUE(uc.port.empty());
  17775. EXPECT_EQ("/path", uc.path);
  17776. }
  17777. {
  17778. detail::UrlComponents uc;
  17779. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17780. EXPECT_EQ("::1", uc.host);
  17781. EXPECT_EQ("8080", uc.port);
  17782. EXPECT_EQ("/path", uc.path);
  17783. }
  17784. {
  17785. detail::UrlComponents uc;
  17786. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17787. }
  17788. {
  17789. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17790. // the path while the connection still targets the bracketed host.
  17791. detail::UrlComponents uc;
  17792. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17793. }
  17794. {
  17795. detail::UrlComponents uc;
  17796. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17797. }
  17798. {
  17799. detail::UrlComponents uc;
  17800. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17801. EXPECT_EQ("::1", uc.host);
  17802. EXPECT_TRUE(uc.port.empty());
  17803. EXPECT_EQ("/path", uc.path);
  17804. }
  17805. {
  17806. detail::UrlComponents uc;
  17807. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17808. EXPECT_TRUE(uc.scheme.empty());
  17809. EXPECT_EQ("example.com", uc.host);
  17810. EXPECT_EQ("/path", uc.path);
  17811. EXPECT_EQ("?q=1", uc.query);
  17812. }
  17813. {
  17814. detail::UrlComponents uc;
  17815. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17816. EXPECT_TRUE(uc.host.empty());
  17817. EXPECT_EQ("/path", uc.path);
  17818. EXPECT_EQ("?q=1", uc.query);
  17819. }
  17820. {
  17821. detail::UrlComponents uc;
  17822. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17823. EXPECT_EQ("example.com", uc.host);
  17824. EXPECT_EQ("8080", uc.port);
  17825. }
  17826. {
  17827. // Unix socket path — must not be parsed as host
  17828. detail::UrlComponents uc;
  17829. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17830. EXPECT_TRUE(uc.host.empty());
  17831. }
  17832. {
  17833. detail::UrlComponents uc;
  17834. ASSERT_TRUE(detail::parse_url("", uc));
  17835. EXPECT_TRUE(uc.host.empty());
  17836. EXPECT_TRUE(uc.path.empty());
  17837. }
  17838. {
  17839. detail::UrlComponents uc;
  17840. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17841. }
  17842. {
  17843. detail::UrlComponents uc;
  17844. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17845. }
  17846. {
  17847. // Accepted by parse_url; callers restrict to http/https
  17848. detail::UrlComponents uc;
  17849. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17850. EXPECT_EQ("ftp", uc.scheme);
  17851. }
  17852. {
  17853. detail::UrlComponents uc;
  17854. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17855. }
  17856. {
  17857. detail::UrlComponents uc;
  17858. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17859. }
  17860. }
  17861. TEST(ParseUrlTest, FragmentHandling) {
  17862. {
  17863. detail::UrlComponents uc;
  17864. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17865. EXPECT_EQ("/path", uc.path);
  17866. EXPECT_TRUE(uc.query.empty());
  17867. }
  17868. {
  17869. detail::UrlComponents uc;
  17870. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17871. EXPECT_TRUE(uc.path.empty());
  17872. EXPECT_TRUE(uc.query.empty());
  17873. }
  17874. }
  17875. TEST(ParseUrlTest, UserinfoHandling) {
  17876. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17877. // parsers would see evil.com as the host.
  17878. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17879. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17880. for (auto url : urls) {
  17881. detail::UrlComponents uc;
  17882. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17883. }
  17884. }
  17885. TEST(ParseUrlTest, IPv6EdgeCases) {
  17886. {
  17887. detail::UrlComponents uc;
  17888. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17889. EXPECT_TRUE(uc.scheme.empty());
  17890. EXPECT_EQ("::1", uc.host);
  17891. EXPECT_EQ("8080", uc.port);
  17892. }
  17893. {
  17894. // Zone ID '%25' is not in [a-fA-F0-9:]
  17895. detail::UrlComponents uc;
  17896. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17897. }
  17898. }
  17899. TEST(ParseUrlTest, SchemeEdgeCases) {
  17900. {
  17901. detail::UrlComponents uc;
  17902. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17903. }
  17904. {
  17905. detail::UrlComponents uc;
  17906. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17907. }
  17908. {
  17909. detail::UrlComponents uc;
  17910. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17911. }
  17912. }
  17913. TEST(ParseUrlTest, PortEdgeCases) {
  17914. {
  17915. detail::UrlComponents uc;
  17916. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17917. EXPECT_TRUE(uc.port.empty());
  17918. EXPECT_EQ("/path", uc.path);
  17919. }
  17920. {
  17921. // parse_url accepts any port string; validation is done by parse_port
  17922. detail::UrlComponents uc;
  17923. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17924. EXPECT_EQ("abc", uc.port);
  17925. }
  17926. }
  17927. TEST(ParseUrlTest, WebSocketPatterns) {
  17928. {
  17929. detail::UrlComponents uc;
  17930. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17931. EXPECT_EQ("ws", uc.scheme);
  17932. EXPECT_EQ("echo.example.com", uc.host);
  17933. EXPECT_EQ("8080", uc.port);
  17934. EXPECT_EQ("/ws", uc.path);
  17935. }
  17936. {
  17937. detail::UrlComponents uc;
  17938. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17939. EXPECT_EQ("wss", uc.scheme);
  17940. EXPECT_EQ("echo.example.com", uc.host);
  17941. EXPECT_TRUE(uc.port.empty());
  17942. EXPECT_EQ("/ws", uc.path);
  17943. }
  17944. }
  17945. TEST(ParseUrlTest, QueryOnly) {
  17946. detail::UrlComponents uc;
  17947. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17948. EXPECT_TRUE(uc.host.empty());
  17949. EXPECT_TRUE(uc.path.empty());
  17950. EXPECT_EQ("?q=1&r=2", uc.query);
  17951. }
  17952. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17953. detail::UrlComponents uc;
  17954. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17955. EXPECT_TRUE(uc.scheme.empty());
  17956. EXPECT_EQ("example.com", uc.host);
  17957. EXPECT_EQ("443", uc.port);
  17958. EXPECT_EQ("/path", uc.path);
  17959. }
  17960. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17961. // If ipv6 regex working, regex match codepath is taken.
  17962. // else port will default to 80 in Client impl
  17963. int clientImplMagicPort = 80;
  17964. int port = 4321;
  17965. // above ports must be different to avoid false negative
  17966. EXPECT_NE(clientImplMagicPort, port);
  17967. std::string ipV6TestURL = "http://[ff06::c3]";
  17968. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17969. CLIENT_PRIVATE_KEY_FILE);
  17970. EXPECT_EQ(cli.port(), port);
  17971. }
  17972. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17973. auto file_path = "./www/dir/index.html";
  17974. auto dir_path = "./www/dir";
  17975. detail::FileStat stat_file(file_path);
  17976. EXPECT_TRUE(stat_file.is_file());
  17977. EXPECT_FALSE(stat_file.is_dir());
  17978. detail::FileStat stat_dir(dir_path);
  17979. EXPECT_FALSE(stat_dir.is_file());
  17980. EXPECT_TRUE(stat_dir.is_dir());
  17981. }
  17982. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17983. // IPv4 with default HTTP port (80)
  17984. EXPECT_EQ("example.com",
  17985. detail::make_host_and_port_string("example.com", 80, false));
  17986. // IPv4 with default HTTPS port (443)
  17987. EXPECT_EQ("example.com",
  17988. detail::make_host_and_port_string("example.com", 443, true));
  17989. // IPv4 with non-default HTTP port
  17990. EXPECT_EQ("example.com:8080",
  17991. detail::make_host_and_port_string("example.com", 8080, false));
  17992. // IPv4 with non-default HTTPS port
  17993. EXPECT_EQ("example.com:8443",
  17994. detail::make_host_and_port_string("example.com", 8443, true));
  17995. // IPv6 with default HTTP port (80)
  17996. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17997. // IPv6 with default HTTPS port (443)
  17998. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17999. // IPv6 with non-default HTTP port
  18000. EXPECT_EQ("[::1]:8080",
  18001. detail::make_host_and_port_string("::1", 8080, false));
  18002. // IPv6 with non-default HTTPS port
  18003. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18004. // IPv6 full address with default port
  18005. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18006. detail::make_host_and_port_string(
  18007. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18008. // IPv6 full address with non-default port
  18009. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18010. detail::make_host_and_port_string(
  18011. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18012. // IPv6 localhost with non-default port
  18013. EXPECT_EQ("[::1]:3000",
  18014. detail::make_host_and_port_string("::1", 3000, false));
  18015. // IPv6 with zone ID (link-local address) with default port
  18016. EXPECT_EQ("[fe80::1%eth0]",
  18017. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18018. // IPv6 with zone ID (link-local address) with non-default port
  18019. EXPECT_EQ("[fe80::1%eth0]:8080",
  18020. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18021. // Edge case: Port 443 with is_ssl=false (should add port)
  18022. EXPECT_EQ("example.com:443",
  18023. detail::make_host_and_port_string("example.com", 443, false));
  18024. // Edge case: Port 80 with is_ssl=true (should add port)
  18025. EXPECT_EQ("example.com:80",
  18026. detail::make_host_and_port_string("example.com", 80, true));
  18027. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18028. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18029. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18030. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18031. // Security fix: Already bracketed IPv6 should not get double brackets
  18032. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18033. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18034. EXPECT_EQ("[::1]:8080",
  18035. detail::make_host_and_port_string("[::1]", 8080, false));
  18036. EXPECT_EQ("[2001:db8::1]:8080",
  18037. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18038. EXPECT_EQ("[fe80::1%eth0]",
  18039. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18040. EXPECT_EQ("[fe80::1%eth0]:8080",
  18041. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18042. // Edge case: Empty host (should return as-is)
  18043. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18044. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18045. // This is a known limitation but shouldn't crash
  18046. EXPECT_EQ("[host:name]",
  18047. detail::make_host_and_port_string("host:name", 80, false));
  18048. // Port number edge cases (no validation, but should not crash)
  18049. EXPECT_EQ("example.com:0",
  18050. detail::make_host_and_port_string("example.com", 0, false));
  18051. EXPECT_EQ("example.com:-1",
  18052. detail::make_host_and_port_string("example.com", -1, false));
  18053. EXPECT_EQ("example.com:65535",
  18054. detail::make_host_and_port_string("example.com", 65535, false));
  18055. EXPECT_EQ("example.com:65536",
  18056. detail::make_host_and_port_string("example.com", 65536, false));
  18057. }
  18058. #ifdef CPPHTTPLIB_SSL_ENABLED
  18059. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18060. httplib::SSLClient cli("roblox.com", 443);
  18061. cli.set_follow_location(true);
  18062. auto res = cli.Get("/");
  18063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18064. EXPECT_EQ(StatusCode::OK_200, res->status);
  18065. }
  18066. #endif
  18067. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18068. Server svr;
  18069. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18070. EXPECT_EQ(res.status, 400);
  18071. });
  18072. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18073. auto se = detail::scope_exit([&] {
  18074. svr.stop();
  18075. thread.join();
  18076. ASSERT_FALSE(svr.is_running());
  18077. });
  18078. svr.wait_until_ready();
  18079. Client cli(HOST, PORT);
  18080. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18081. }
  18082. TEST(InvalidHeaderCharsTest, is_field_name) {
  18083. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18084. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18085. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18086. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18087. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18088. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18089. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18090. EXPECT_FALSE(detail::fields::is_field_name(""));
  18091. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18092. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18093. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18094. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18095. }
  18096. TEST(InvalidHeaderCharsTest, is_field_value) {
  18097. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18098. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18099. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18100. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18101. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18102. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18103. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18104. EXPECT_TRUE(detail::fields::is_field_value(""));
  18105. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18106. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18107. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18108. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18109. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18110. }
  18111. TEST(InvalidHeaderCharsTest, OnServer) {
  18112. Server svr;
  18113. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18114. std::string header = "Not Set";
  18115. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18116. res.set_header(header, "value");
  18117. res.set_content("Page Content Page Content", "text/plain");
  18118. });
  18119. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18120. std::string header = "Not Set";
  18121. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18122. res.set_header("X-Test", header);
  18123. res.set_content("Page Content Page Content", "text/plain");
  18124. });
  18125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18126. auto se = detail::scope_exit([&] {
  18127. svr.stop();
  18128. thread.join();
  18129. ASSERT_FALSE(svr.is_running());
  18130. });
  18131. svr.wait_until_ready();
  18132. Client cli(HOST, PORT);
  18133. {
  18134. auto res = cli.Get(
  18135. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18137. EXPECT_EQ("Page Content Page Content", res->body);
  18138. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18139. }
  18140. {
  18141. auto res = cli.Get(
  18142. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18144. EXPECT_EQ("Page Content Page Content", res->body);
  18145. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18146. }
  18147. }
  18148. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18149. auto handled = false;
  18150. Server svr;
  18151. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18152. thread t = thread([&] { svr.listen(HOST, PORT); });
  18153. auto se = detail::scope_exit([&] {
  18154. svr.stop();
  18155. t.join();
  18156. ASSERT_FALSE(svr.is_running());
  18157. ASSERT_FALSE(handled);
  18158. });
  18159. svr.wait_until_ready();
  18160. auto req = "POST /test HTTP/1.1\r\n"
  18161. "Content-Length: x\r\n"
  18162. "\r\n";
  18163. std::string response;
  18164. ASSERT_TRUE(send_request(1, req, &response));
  18165. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18166. response.substr(0, response.find("\r\n")));
  18167. }
  18168. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18169. // case-insensitive, and a server that receives a 100-continue expectation in
  18170. // an HTTP/1.0 request MUST ignore it.
  18171. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18172. std::string response;
  18173. ASSERT_TRUE(send_request(1, req, &response, port));
  18174. *got_100 = response.find("100 Continue") != std::string::npos;
  18175. }
  18176. class ExpectTokenTest : public ::testing::Test {
  18177. protected:
  18178. void SetUp() override {
  18179. svr_.Post("/p", [](const Request &, Response &res) {
  18180. res.set_content("ok", "text/plain");
  18181. });
  18182. port_ = svr_.bind_to_any_port(HOST);
  18183. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18184. svr_.wait_until_ready();
  18185. }
  18186. void TearDown() override {
  18187. svr_.stop();
  18188. if (thread_.joinable()) { thread_.join(); }
  18189. }
  18190. std::string request(const char *version, const char *expect_value) const {
  18191. return std::string("POST /p ") + version +
  18192. "\r\n"
  18193. "Host: localhost\r\n"
  18194. "Content-Length: 2\r\n"
  18195. "Connection: close\r\n"
  18196. "Expect: " +
  18197. expect_value +
  18198. "\r\n"
  18199. "\r\n"
  18200. "hi";
  18201. }
  18202. Server svr_;
  18203. int port_ = 0;
  18204. thread thread_;
  18205. };
  18206. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18207. bool got_100 = false;
  18208. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18209. EXPECT_TRUE(got_100);
  18210. }
  18211. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18212. bool got_100 = true;
  18213. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18214. EXPECT_FALSE(got_100);
  18215. }
  18216. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18217. bool got_100 = false;
  18218. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18219. EXPECT_TRUE(got_100);
  18220. }
  18221. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18222. bool got_100 = false;
  18223. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18224. EXPECT_TRUE(got_100);
  18225. }
  18226. // `100 Continue` is sent only when the server starts reading the body, so a
  18227. // request rejected before that never invites the client to send it. The
  18228. // requests below carry the expectation but withhold the body, as a client
  18229. // waiting for `100 Continue` would.
  18230. // A POST that expects `100 Continue` and withholds its two-byte body.
  18231. static std::string expect_headers_only(const std::string &path) {
  18232. return "POST " + path +
  18233. " HTTP/1.1\r\n"
  18234. "Host: localhost\r\n"
  18235. "Content-Length: 2\r\n"
  18236. "Expect: 100-continue\r\n"
  18237. "\r\n";
  18238. }
  18239. class ExpectLazyContinueTest : public ::testing::Test {
  18240. protected:
  18241. void SetUp() override {
  18242. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18243. if (req.path == "/pre-routing") {
  18244. res.status = StatusCode::Unauthorized_401;
  18245. return Server::HandlerResponse::Handled;
  18246. }
  18247. return Server::HandlerResponse::Unhandled;
  18248. });
  18249. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18250. if (req.matched_route == "/pre-request") {
  18251. res.status = StatusCode::Forbidden_403;
  18252. return Server::HandlerResponse::Handled;
  18253. }
  18254. return Server::HandlerResponse::Unhandled;
  18255. });
  18256. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18257. res.set_content("ok", "text/plain");
  18258. });
  18259. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18260. res.set_content("ok", "text/plain");
  18261. });
  18262. svr_.Post("/reader-used", [](const Request &, Response &res,
  18263. const ContentReader &content_reader) {
  18264. std::string body;
  18265. content_reader([&](const char *data, size_t len) {
  18266. body.append(data, len);
  18267. return true;
  18268. });
  18269. res.set_content(body, "text/plain");
  18270. });
  18271. svr_.Post("/reader-unused",
  18272. [](const Request &, Response &res, const ContentReader &) {
  18273. res.set_content("ignored", "text/plain");
  18274. });
  18275. port_ = svr_.bind_to_any_port(HOST);
  18276. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18277. svr_.wait_until_ready();
  18278. }
  18279. void TearDown() override {
  18280. svr_.stop();
  18281. if (thread_.joinable()) { thread_.join(); }
  18282. }
  18283. // Sends `req` and reads until the server closes the connection. Returns
  18284. // false if the read had to wait for the client-side timeout instead.
  18285. bool send_until_closed(const std::string &req, std::string *resp) const {
  18286. auto start = std::chrono::steady_clock::now();
  18287. if (!send_request(3, req, resp, port_)) { return false; }
  18288. auto elapsed = std::chrono::steady_clock::now() - start;
  18289. return elapsed < std::chrono::seconds(2);
  18290. }
  18291. // The final response comes without `100 Continue`, and the server closes
  18292. // the connection since the body may or may not follow.
  18293. void expect_final_without_interim(const std::string &path,
  18294. const char *status_line) const {
  18295. std::string resp;
  18296. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18297. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18298. EXPECT_EQ(0u, resp.find(status_line));
  18299. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18300. }
  18301. Server svr_;
  18302. int port_ = 0;
  18303. thread thread_;
  18304. };
  18305. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18306. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18307. }
  18308. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18309. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18310. }
  18311. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18312. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18313. }
  18314. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18315. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18316. }
  18317. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18318. // The body follows once `100 Continue` has had time to arrive.
  18319. auto req = expect_headers_only("/reader-used");
  18320. req.insert(req.size() - 2, "Connection: close\r\n");
  18321. std::string resp;
  18322. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18323. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18324. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18325. EXPECT_NE(std::string::npos, resp.find("hi"));
  18326. }
  18327. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18328. // Large enough for the client to add `Expect: 100-continue` itself.
  18329. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18330. std::atomic<bool> body_sent{false};
  18331. Client cli(HOST, port_);
  18332. auto res = cli.Post(
  18333. "/pre-request", length,
  18334. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18335. body_sent = true;
  18336. std::string chunk(len, 'x');
  18337. sink.write(chunk.data(), chunk.size());
  18338. return true;
  18339. },
  18340. "application/octet-stream");
  18341. ASSERT_TRUE(res);
  18342. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18343. EXPECT_FALSE(body_sent);
  18344. }
  18345. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18346. Server svr;
  18347. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18348. return StatusCode::ExpectationFailed_417;
  18349. });
  18350. svr.Post("/p", [](const Request &, Response &res) {
  18351. res.set_content("ok", "text/plain");
  18352. });
  18353. auto port = svr.bind_to_any_port(HOST);
  18354. thread t = thread([&] { svr.listen_after_bind(); });
  18355. auto se = detail::scope_exit([&] {
  18356. svr.stop();
  18357. t.join();
  18358. });
  18359. svr.wait_until_ready();
  18360. std::string resp;
  18361. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18362. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18363. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18364. // Exactly one response: the route handler must not run after the 417.
  18365. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18366. }
  18367. #ifndef _WIN32
  18368. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18369. static constexpr char reject[] = "Unauthorized";
  18370. static constexpr char accept[] = "Upload accepted";
  18371. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18372. Server svr;
  18373. svr.set_expect_100_continue_handler(
  18374. [](const Request & /*req*/, Response &res) {
  18375. res.status = StatusCode::Unauthorized_401;
  18376. res.set_content(reject, "text/plain");
  18377. return res.status;
  18378. });
  18379. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18380. res.set_content(accept, "text/plain");
  18381. });
  18382. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18383. auto se = detail::scope_exit([&] {
  18384. svr.stop();
  18385. thread.join();
  18386. ASSERT_FALSE(svr.is_running());
  18387. });
  18388. svr.wait_until_ready();
  18389. {
  18390. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18391. curl_easy_init(), &curl_easy_cleanup};
  18392. ASSERT_NE(curl, nullptr);
  18393. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18394. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18395. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18396. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18397. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18398. &curl_slist_free_all};
  18399. ASSERT_NE(list, nullptr);
  18400. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18401. struct read_data {
  18402. uint64_t read_size;
  18403. uint64_t total_size;
  18404. } data = {0, total_size};
  18405. using read_callback_t =
  18406. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18407. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18408. void *userdata) -> size_t {
  18409. read_data *d = (read_data *)userdata;
  18410. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18411. std::fill_n(ptr, size * nmemb, 'A');
  18412. d->read_size += size * nmemb;
  18413. return size * nmemb;
  18414. };
  18415. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18416. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18417. std::vector<char> buffer;
  18418. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18419. using write_callback_t =
  18420. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18421. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18422. void *userdata) -> size_t {
  18423. std::vector<char> *buf = (std::vector<char> *)userdata;
  18424. buf->reserve(buf->size() + size * nmemb + 1);
  18425. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18426. return size * nmemb;
  18427. };
  18428. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18429. {
  18430. const auto res = curl_easy_perform(curl.get());
  18431. ASSERT_EQ(res, CURLE_OK);
  18432. }
  18433. {
  18434. auto response_code = long{};
  18435. const auto res =
  18436. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18437. ASSERT_EQ(res, CURLE_OK);
  18438. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18439. }
  18440. {
  18441. auto dl = curl_off_t{};
  18442. const auto res =
  18443. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18444. ASSERT_EQ(res, CURLE_OK);
  18445. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18446. }
  18447. {
  18448. buffer.push_back('\0');
  18449. ASSERT_STRCASEEQ(buffer.data(), reject);
  18450. }
  18451. }
  18452. }
  18453. #endif
  18454. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18455. // Regression test for #2458.
  18456. //
  18457. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18458. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18459. // ticket can make the client socket spuriously readable during the
  18460. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18461. // the client withholds the body and then blocks reading a response that never
  18462. // comes, failing with `Failed to read connection`.
  18463. //
  18464. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18465. // within the timeout. This raw OpenSSL server deliberately never sends
  18466. // `100 Continue`; the client must still deliver the body and receive 200.
  18467. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18468. signal(SIGPIPE, SIG_IGN);
  18469. const auto port = PORT + 4;
  18470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18471. ASSERT_NE(srv, INVALID_SOCKET);
  18472. int opt = 1;
  18473. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18474. sockaddr_in addr{};
  18475. addr.sin_family = AF_INET;
  18476. addr.sin_port = htons(static_cast<uint16_t>(port));
  18477. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18478. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18479. ASSERT_EQ(0, ::listen(srv, 1));
  18480. std::atomic<size_t> server_body_bytes{0};
  18481. auto server_thread = std::thread([&] {
  18482. sockaddr_in cli_addr{};
  18483. socklen_t cli_len = sizeof(cli_addr);
  18484. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18485. if (cli == INVALID_SOCKET) { return; }
  18486. // Bound the lifetime of the server side so a buggy client (which never
  18487. // sends the body) cannot make this thread block forever on join.
  18488. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18489. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18490. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18491. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18492. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18493. SSL *ssl = SSL_new(ctx);
  18494. SSL_set_fd(ssl, static_cast<int>(cli));
  18495. if (SSL_accept(ssl) > 0) {
  18496. // Read the request headers. Reading here also flushes the TLS 1.3
  18497. // session tickets to the client. Deliberately do NOT send
  18498. // `100 Continue`.
  18499. std::string buf;
  18500. char tmp[1024];
  18501. while (buf.find("\r\n\r\n") == std::string::npos) {
  18502. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18503. if (n <= 0) { break; }
  18504. buf.append(tmp, static_cast<size_t>(n));
  18505. }
  18506. // A correct client sends the body now; count what arrives.
  18507. auto pos = buf.find("\r\n\r\n");
  18508. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18509. while (body < 4096) {
  18510. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18511. if (n <= 0) { break; }
  18512. body += static_cast<size_t>(n);
  18513. }
  18514. server_body_bytes = body;
  18515. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18516. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18517. SSL_shutdown(ssl);
  18518. }
  18519. SSL_free(ssl);
  18520. detail::close_socket(cli);
  18521. SSL_CTX_free(ctx);
  18522. });
  18523. auto se = detail::scope_exit([&] {
  18524. server_thread.join();
  18525. detail::close_socket(srv);
  18526. });
  18527. SSLClient cli("127.0.0.1", port);
  18528. cli.enable_server_certificate_verification(false);
  18529. cli.set_connection_timeout(5, 0);
  18530. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18531. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18532. std::string body(4096, 'A');
  18533. auto res = cli.Put("/api/test", body, "application/json");
  18534. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18535. EXPECT_EQ(StatusCode::OK_200, res->status);
  18536. EXPECT_EQ(body.size(), server_body_bytes.load());
  18537. }
  18538. #endif
  18539. template <typename S, typename C>
  18540. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18541. svr.Get("/stream", [&](const Request &, Response &res) {
  18542. auto data = new std::string("01234567890123456789");
  18543. res.set_content_provider(
  18544. data->size(), "text/plain",
  18545. [&, data](size_t offset, size_t length, DataSink &sink) {
  18546. const size_t DATA_CHUNK_SIZE = 4;
  18547. const auto &d = *data;
  18548. std::this_thread::sleep_for(std::chrono::seconds(1));
  18549. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18550. return true;
  18551. },
  18552. [data](bool success) {
  18553. EXPECT_FALSE(success);
  18554. delete data;
  18555. });
  18556. });
  18557. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18558. auto i = new size_t(0);
  18559. res.set_content_provider(
  18560. "text/plain",
  18561. [i](size_t, DataSink &sink) {
  18562. if (*i < 5) {
  18563. std::this_thread::sleep_for(std::chrono::seconds(1));
  18564. sink.write("abcd", 4);
  18565. (*i)++;
  18566. } else {
  18567. sink.done();
  18568. }
  18569. return true;
  18570. },
  18571. [i](bool success) {
  18572. EXPECT_FALSE(success);
  18573. delete i;
  18574. });
  18575. });
  18576. svr.Get("/chunked", [&](const Request &, Response &res) {
  18577. auto i = new size_t(0);
  18578. res.set_chunked_content_provider(
  18579. "text/plain",
  18580. [i](size_t, DataSink &sink) {
  18581. if (*i < 5) {
  18582. std::this_thread::sleep_for(std::chrono::seconds(1));
  18583. sink.os << "abcd";
  18584. (*i)++;
  18585. } else {
  18586. sink.done();
  18587. }
  18588. return true;
  18589. },
  18590. [i](bool success) {
  18591. EXPECT_FALSE(success);
  18592. delete i;
  18593. });
  18594. });
  18595. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18596. auto se = detail::scope_exit([&] {
  18597. svr.stop();
  18598. listen_thread.join();
  18599. ASSERT_FALSE(svr.is_running());
  18600. });
  18601. svr.wait_until_ready();
  18602. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18603. {
  18604. auto start = std::chrono::steady_clock::now();
  18605. auto res = cli.Get("/stream");
  18606. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18607. std::chrono::steady_clock::now() - start)
  18608. .count();
  18609. ASSERT_FALSE(res);
  18610. EXPECT_EQ(Error::Read, res.error());
  18611. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18612. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18613. }
  18614. {
  18615. auto start = std::chrono::steady_clock::now();
  18616. auto res = cli.Get("/stream_without_length");
  18617. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18618. std::chrono::steady_clock::now() - start)
  18619. .count();
  18620. ASSERT_FALSE(res);
  18621. EXPECT_EQ(Error::Read, res.error());
  18622. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18623. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18624. }
  18625. {
  18626. auto start = std::chrono::steady_clock::now();
  18627. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18628. EXPECT_EQ("abcd", string(data, data_length));
  18629. return true;
  18630. });
  18631. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18632. std::chrono::steady_clock::now() - start)
  18633. .count();
  18634. ASSERT_FALSE(res);
  18635. EXPECT_EQ(Error::Read, res.error());
  18636. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18637. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18638. }
  18639. }
  18640. TEST(MaxTimeoutTest, ContentStream) {
  18641. time_t timeout = 2000;
  18642. time_t threshold = 200;
  18643. Server svr;
  18644. Client cli("localhost", PORT);
  18645. max_timeout_test(svr, cli, timeout, threshold);
  18646. }
  18647. #ifdef CPPHTTPLIB_SSL_ENABLED
  18648. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18649. time_t timeout = 2000;
  18650. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18651. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18652. SSLClient cli("localhost", PORT);
  18653. cli.enable_server_certificate_verification(false);
  18654. max_timeout_test(svr, cli, timeout, threshold);
  18655. }
  18656. #endif
  18657. class EventDispatcher {
  18658. public:
  18659. EventDispatcher() {}
  18660. bool wait_event(DataSink *sink) {
  18661. unique_lock<mutex> lk(m_);
  18662. int id = id_;
  18663. // Wait with timeout to prevent hanging if client disconnects
  18664. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18665. [&] { return cid_ == id; })) {
  18666. return false; // Timeout occurred
  18667. }
  18668. sink->write(message_.data(), message_.size());
  18669. return true;
  18670. }
  18671. void send_event(const string &message) {
  18672. lock_guard<mutex> lk(m_);
  18673. cid_ = id_++;
  18674. message_ = message;
  18675. cv_.notify_all();
  18676. }
  18677. private:
  18678. mutex m_;
  18679. condition_variable cv_;
  18680. atomic_int id_{0};
  18681. atomic_int cid_{-1};
  18682. string message_;
  18683. };
  18684. TEST(ClientInThreadTest, Issue2068) {
  18685. EventDispatcher ed;
  18686. Server svr;
  18687. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18688. res.set_chunked_content_provider("text/event-stream",
  18689. [&](size_t /*offset*/, DataSink &sink) {
  18690. return ed.wait_event(&sink);
  18691. });
  18692. });
  18693. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18694. svr.wait_until_ready();
  18695. thread event_thread([&] {
  18696. int id = 0;
  18697. while (svr.is_running()) {
  18698. this_thread::sleep_for(chrono::milliseconds(500));
  18699. std::stringstream ss;
  18700. ss << "data: " << id << "\n\n";
  18701. ed.send_event(ss.str());
  18702. id++;
  18703. }
  18704. });
  18705. auto se = detail::scope_exit([&] {
  18706. svr.stop();
  18707. listen_thread.join();
  18708. event_thread.join();
  18709. ASSERT_FALSE(svr.is_running());
  18710. });
  18711. {
  18712. auto client = detail::make_unique<Client>(HOST, PORT);
  18713. client->set_read_timeout(std::chrono::minutes(10));
  18714. std::atomic<bool> stop{false};
  18715. std::thread t([&] {
  18716. client->Get("/event1",
  18717. [&](const char *, size_t) -> bool { return !stop; });
  18718. });
  18719. std::this_thread::sleep_for(std::chrono::seconds(2));
  18720. stop = true;
  18721. client->stop();
  18722. t.join();
  18723. // Reset client after thread has finished
  18724. client.reset();
  18725. }
  18726. }
  18727. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18728. auto handled = false;
  18729. Server svr;
  18730. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18731. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18732. auto se = detail::scope_exit([&] {
  18733. svr.stop();
  18734. t.join();
  18735. ASSERT_FALSE(svr.is_running());
  18736. ASSERT_FALSE(handled);
  18737. });
  18738. svr.wait_until_ready();
  18739. // Two Content-Length headers with different values — must be rejected
  18740. auto req = "POST /test HTTP/1.1\r\n"
  18741. "Content-Length: 5\r\n"
  18742. "Content-Length: 10\r\n"
  18743. "\r\n"
  18744. "hello";
  18745. std::string response;
  18746. ASSERT_TRUE(send_request(1, req, &response));
  18747. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18748. response.substr(0, response.find("\r\n")));
  18749. }
  18750. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18751. auto handled = false;
  18752. Server svr;
  18753. svr.Post("/test", [&](const Request &, Response &res) {
  18754. handled = true;
  18755. res.set_content("ok", "text/plain");
  18756. });
  18757. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18758. auto se = detail::scope_exit([&] {
  18759. svr.stop();
  18760. t.join();
  18761. ASSERT_FALSE(svr.is_running());
  18762. ASSERT_TRUE(handled);
  18763. });
  18764. svr.wait_until_ready();
  18765. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18766. auto req = "POST /test HTTP/1.1\r\n"
  18767. "Host: localhost\r\n"
  18768. "Content-Length: 5\r\n"
  18769. "Content-Length: 5\r\n"
  18770. "\r\n"
  18771. "hello";
  18772. std::string response;
  18773. ASSERT_TRUE(send_request(1, req, &response));
  18774. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18775. }
  18776. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18777. Server svr;
  18778. svr.Get("/test", [](const Request &, Response &res) {
  18779. res.set_content("ok", "text/plain");
  18780. });
  18781. auto port = svr.bind_to_any_port(HOST);
  18782. thread t = thread([&] { svr.listen_after_bind(); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. auto status_line = [&](const std::string &host_lines) {
  18790. std::string res;
  18791. send_request(
  18792. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18793. &res, port);
  18794. return res.substr(0, res.find("\r\n"));
  18795. };
  18796. const char *accepted[] = {
  18797. "Host: localhost\r\n",
  18798. "Host: a.example:8080\r\n",
  18799. "Host: my_service\r\n",
  18800. "Host: [::1]:8080\r\n",
  18801. "Host: [fe80::1%25eth0]\r\n",
  18802. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18803. };
  18804. for (auto host_lines : accepted) {
  18805. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18806. }
  18807. const char *rejected[] = {
  18808. "Host: a.example\r\nHost: b.example\r\n",
  18809. "Host: a.example\r\nHost: a.example\r\n",
  18810. "Host: a@b.example\r\n",
  18811. "Host: a.example/b\r\n",
  18812. "Host: a.example\\b\r\n",
  18813. "Host: a.example?b\r\n",
  18814. "Host: a.example#b\r\n",
  18815. "Host: a.example b.example\r\n",
  18816. };
  18817. for (auto host_lines : rejected) {
  18818. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18819. << host_lines;
  18820. }
  18821. }
  18822. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18823. Server svr;
  18824. svr.Get("/", [](const Request &req, Response &res) {
  18825. EXPECT_EQ(2U, req.trailers.size());
  18826. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18827. // Denied
  18828. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18829. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18830. // Accepted
  18831. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18832. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18833. EXPECT_TRUE(req.has_trailer("X-World"));
  18834. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18835. res.set_content("ok", "text/plain");
  18836. });
  18837. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18838. auto se = detail::scope_exit([&] {
  18839. svr.stop();
  18840. t.join();
  18841. ASSERT_FALSE(svr.is_running());
  18842. });
  18843. svr.wait_until_ready();
  18844. const std::string req = "GET / HTTP/1.1\r\n"
  18845. "Transfer-Encoding: chunked\r\n"
  18846. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18847. "\r\n"
  18848. "0\r\n"
  18849. "Content-Length: 10\r\n"
  18850. "Host: internal.local\r\n"
  18851. "Content-Type: malicious/content\r\n"
  18852. "Cookie: any\r\n"
  18853. "Set-Cookie: any\r\n"
  18854. "X-Forwarded-For: attacker.com\r\n"
  18855. "X-Real-Ip: 1.1.1.1\r\n"
  18856. "X-Hello: hello\r\n"
  18857. "X-World: world\r\n"
  18858. "\r\n";
  18859. std::string res;
  18860. ASSERT_TRUE(send_request(1, req, &res));
  18861. }
  18862. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18863. // several field lines, and the combined value is what has to be parsed. A
  18864. // Trailer field split across lines therefore declares every name it lists;
  18865. // reading only the first line silently drops the trailers the later lines
  18866. // declare. The prohibited-trailer filter still applies to every line.
  18867. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18868. Server svr;
  18869. size_t observed_trailer_count = 0;
  18870. std::string observed_hello;
  18871. std::string observed_world;
  18872. bool observed_content_length = true;
  18873. svr.Get("/", [&](const Request &req, Response &res) {
  18874. observed_trailer_count = req.trailers.size();
  18875. observed_hello = req.get_trailer_value("X-Hello");
  18876. observed_world = req.get_trailer_value("X-World");
  18877. observed_content_length = req.has_trailer("Content-Length");
  18878. res.set_content("ok", "text/plain");
  18879. });
  18880. auto port = svr.bind_to_any_port(HOST);
  18881. thread t = thread([&]() { svr.listen_after_bind(); });
  18882. auto se = detail::scope_exit([&] {
  18883. svr.stop();
  18884. t.join();
  18885. ASSERT_FALSE(svr.is_running());
  18886. });
  18887. svr.wait_until_ready();
  18888. const std::string req = "GET / HTTP/1.1\r\n"
  18889. "Host: localhost\r\n"
  18890. "Transfer-Encoding: chunked\r\n"
  18891. "Trailer: X-Hello\r\n"
  18892. "Trailer: X-World, Content-Length\r\n"
  18893. "\r\n"
  18894. "0\r\n"
  18895. "X-Hello: hello\r\n"
  18896. "X-World: world\r\n"
  18897. "Content-Length: 10\r\n"
  18898. "\r\n";
  18899. std::string res;
  18900. ASSERT_TRUE(send_request(1, req, &res, port));
  18901. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18902. // Accepted: both field lines contribute to the declared set
  18903. EXPECT_EQ(2U, observed_trailer_count);
  18904. EXPECT_EQ(observed_hello, "hello");
  18905. EXPECT_EQ(observed_world, "world");
  18906. // Denied: a prohibited name stays prohibited on a later field line
  18907. EXPECT_FALSE(observed_content_length);
  18908. }
  18909. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18910. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18911. // unbounded run of fields that are never declared, because the counter would
  18912. // only advance for declared fields.
  18913. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18914. Server svr;
  18915. bool handler_called = false;
  18916. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18917. handler_called = true;
  18918. res.set_content("ok", "text/plain");
  18919. });
  18920. auto port = svr.bind_to_any_port(HOST);
  18921. thread t = thread([&]() { svr.listen_after_bind(); });
  18922. auto se = detail::scope_exit([&] {
  18923. svr.stop();
  18924. t.join();
  18925. ASSERT_FALSE(svr.is_running());
  18926. });
  18927. svr.wait_until_ready();
  18928. // Declare nothing, then send far more undeclared trailer fields than the
  18929. // header-count limit. Parsing must stop and reject the request rather than
  18930. // read every line.
  18931. std::string req = "GET / HTTP/1.1\r\n"
  18932. "Transfer-Encoding: chunked\r\n"
  18933. "\r\n"
  18934. "0\r\n";
  18935. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18936. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18937. }
  18938. req += "\r\n";
  18939. std::string res;
  18940. ASSERT_TRUE(send_request(1, req, &res, port));
  18941. // The request is rejected before the handler runs.
  18942. EXPECT_FALSE(handler_called);
  18943. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18944. }
  18945. // The set of declared trailer names is capped so a peer cannot grow it without
  18946. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18947. // declared past the cap is not honored, even if the field is actually sent.
  18948. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18949. Server svr;
  18950. // One name inside the cap and one past it, so the test tracks the cap rather
  18951. // than a fixed count.
  18952. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18953. const std::string within_cap_name = "X-T-0";
  18954. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18955. bool observed_within_cap = false;
  18956. bool observed_past_cap = false;
  18957. svr.Get("/", [&](const Request &req, Response &res) {
  18958. observed_within_cap = req.has_trailer(within_cap_name);
  18959. observed_past_cap = req.has_trailer(past_cap_name);
  18960. res.set_content("ok", "text/plain");
  18961. });
  18962. auto port = svr.bind_to_any_port(HOST);
  18963. thread t = thread([&]() { svr.listen_after_bind(); });
  18964. auto se = detail::scope_exit([&] {
  18965. svr.stop();
  18966. t.join();
  18967. ASSERT_FALSE(svr.is_running());
  18968. });
  18969. svr.wait_until_ready();
  18970. // Declare more trailer names than the cap in a single Trailer field, then
  18971. // actually send the first (within the cap) and the last (past it).
  18972. std::string trailer_decl = "Trailer: ";
  18973. for (int i = 0; i < declared_count; i++) {
  18974. if (i != 0) { trailer_decl += ", "; }
  18975. trailer_decl += "X-T-" + std::to_string(i);
  18976. }
  18977. trailer_decl += "\r\n";
  18978. const std::string req = "GET / HTTP/1.1\r\n"
  18979. "Host: localhost\r\n"
  18980. "Transfer-Encoding: chunked\r\n" +
  18981. trailer_decl +
  18982. "\r\n"
  18983. "0\r\n" +
  18984. within_cap_name + ": a\r\n" + past_cap_name +
  18985. ": b\r\n"
  18986. "\r\n";
  18987. std::string res;
  18988. ASSERT_TRUE(send_request(1, req, &res, port));
  18989. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18990. // A name within the cap is honored; one declared past the cap is dropped.
  18991. EXPECT_TRUE(observed_within_cap);
  18992. EXPECT_FALSE(observed_past_cap);
  18993. }
  18994. // A direct client that is not listed in trusted_proxies must not be able to
  18995. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18996. // the peer address on the actual TCP connection determines whether the
  18997. // header is honored.
  18998. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18999. Server svr;
  19000. // Deliberately does NOT include the loopback address the test client
  19001. // actually connects from, so the direct connection is not a trusted proxy.
  19002. svr.set_trusted_proxies({"203.0.113.66"});
  19003. std::string observed_remote_addr;
  19004. svr.Get("/ip", [&](const Request &req, Response &res) {
  19005. observed_remote_addr = req.remote_addr;
  19006. res.set_content("ok", "text/plain");
  19007. });
  19008. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19009. auto se = detail::scope_exit([&] {
  19010. svr.stop();
  19011. t.join();
  19012. ASSERT_FALSE(svr.is_running());
  19013. });
  19014. svr.wait_until_ready();
  19015. Client cli(HOST, PORT);
  19016. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19018. EXPECT_EQ(StatusCode::OK_200, res->status);
  19019. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19020. // ignored entirely and the real connection-level address retained.
  19021. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19022. observed_remote_addr == "127.0.0.1");
  19023. }
  19024. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19025. Server svr;
  19026. std::string observed_remote_addr;
  19027. std::string observed_xff;
  19028. svr.Get("/ip", [&](const Request &req, Response &res) {
  19029. observed_remote_addr = req.remote_addr;
  19030. observed_xff = req.get_header_value("X-Forwarded-For");
  19031. res.set_content("ok", "text/plain");
  19032. });
  19033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19034. auto se = detail::scope_exit([&] {
  19035. svr.stop();
  19036. t.join();
  19037. ASSERT_FALSE(svr.is_running());
  19038. });
  19039. svr.wait_until_ready();
  19040. Client cli(HOST, PORT);
  19041. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19043. EXPECT_EQ(StatusCode::OK_200, res->status);
  19044. EXPECT_EQ(observed_xff, "203.0.113.66");
  19045. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19046. observed_remote_addr == "127.0.0.1");
  19047. }
  19048. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19049. Server svr;
  19050. svr.set_trusted_proxies({"203.0.113.66"});
  19051. std::string observed_remote_addr;
  19052. std::string observed_xff;
  19053. svr.Get("/ip", [&](const Request &req, Response &res) {
  19054. observed_remote_addr = req.remote_addr;
  19055. observed_xff = req.get_header_value("X-Forwarded-For");
  19056. res.set_content("ok", "text/plain");
  19057. });
  19058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19059. auto se = detail::scope_exit([&] {
  19060. svr.stop();
  19061. t.join();
  19062. ASSERT_FALSE(svr.is_running());
  19063. });
  19064. svr.wait_until_ready();
  19065. Client cli(HOST, PORT);
  19066. auto res = cli.Get("/ip");
  19067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19068. EXPECT_EQ(StatusCode::OK_200, res->status);
  19069. EXPECT_EQ(observed_xff, "");
  19070. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19071. observed_remote_addr == "127.0.0.1");
  19072. }
  19073. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19074. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19075. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19076. Server svr;
  19077. svr.set_trusted_proxies({"127.0.0.1"});
  19078. svr.Get("/ip", [](const Request &req, Response &res) {
  19079. res.set_content(req.remote_addr, "text/plain");
  19080. });
  19081. auto port = svr.bind_to_any_port("::");
  19082. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19083. thread t = thread([&] { svr.listen_after_bind(); });
  19084. auto se = detail::scope_exit([&] {
  19085. svr.stop();
  19086. t.join();
  19087. ASSERT_FALSE(svr.is_running());
  19088. });
  19089. svr.wait_until_ready();
  19090. Client cli("127.0.0.1", port);
  19091. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19093. EXPECT_EQ("198.51.100.23", res->body);
  19094. }
  19095. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19096. Server svr;
  19097. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19098. svr.Get("/ip", [](const Request &req, Response &res) {
  19099. res.set_content(req.remote_addr, "text/plain");
  19100. });
  19101. auto port = svr.bind_to_any_port(HOST);
  19102. ASSERT_GT(port, 0);
  19103. thread t = thread([&] { svr.listen_after_bind(); });
  19104. auto se = detail::scope_exit([&] {
  19105. svr.stop();
  19106. t.join();
  19107. ASSERT_FALSE(svr.is_running());
  19108. });
  19109. svr.wait_until_ready();
  19110. Client cli(HOST, port);
  19111. auto res = cli.Get(
  19112. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19114. EXPECT_EQ("198.51.100.23", res->body);
  19115. }
  19116. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19117. Server svr;
  19118. // Include the loopback address the test client actually connects from, so
  19119. // the direct connection itself is recognized as the trusted proxy hop.
  19120. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19121. std::string observed_remote_addr;
  19122. std::string observed_xff;
  19123. svr.Get("/ip", [&](const Request &req, Response &res) {
  19124. observed_remote_addr = req.remote_addr;
  19125. observed_xff = req.get_header_value("X-Forwarded-For");
  19126. res.set_content("ok", "text/plain");
  19127. });
  19128. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19129. auto se = detail::scope_exit([&] {
  19130. svr.stop();
  19131. t.join();
  19132. ASSERT_FALSE(svr.is_running());
  19133. });
  19134. svr.wait_until_ready();
  19135. Client cli(HOST, PORT);
  19136. auto res = cli.Get(
  19137. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19139. EXPECT_EQ(StatusCode::OK_200, res->status);
  19140. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19141. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19142. }
  19143. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19144. Server svr;
  19145. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19146. std::string observed_remote_addr;
  19147. std::string observed_xff;
  19148. svr.Get("/ip", [&](const Request &req, Response &res) {
  19149. observed_remote_addr = req.remote_addr;
  19150. observed_xff = req.get_header_value("X-Forwarded-For");
  19151. res.set_content("ok", "text/plain");
  19152. });
  19153. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19154. auto se = detail::scope_exit([&] {
  19155. svr.stop();
  19156. t.join();
  19157. ASSERT_FALSE(svr.is_running());
  19158. });
  19159. svr.wait_until_ready();
  19160. Client cli(HOST, PORT);
  19161. auto res = cli.Get(
  19162. "/ip",
  19163. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19165. EXPECT_EQ(StatusCode::OK_200, res->status);
  19166. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19167. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19168. }
  19169. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19170. Server svr;
  19171. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19172. std::string observed_remote_addr;
  19173. std::string observed_xff;
  19174. svr.Get("/ip", [&](const Request &req, Response &res) {
  19175. observed_remote_addr = req.remote_addr;
  19176. observed_xff = req.get_header_value("X-Forwarded-For");
  19177. res.set_content("ok", "text/plain");
  19178. });
  19179. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19180. auto se = detail::scope_exit([&] {
  19181. svr.stop();
  19182. t.join();
  19183. ASSERT_FALSE(svr.is_running());
  19184. });
  19185. svr.wait_until_ready();
  19186. Client cli(HOST, PORT);
  19187. auto res = cli.Get(
  19188. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19190. EXPECT_EQ(StatusCode::OK_200, res->status);
  19191. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19192. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19193. // and must not be selected.
  19194. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19195. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19196. }
  19197. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19198. Server svr;
  19199. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19200. std::string observed_remote_addr;
  19201. svr.Get("/ip", [&](const Request &req, Response &res) {
  19202. observed_remote_addr = req.remote_addr;
  19203. res.set_content("ok", "text/plain");
  19204. });
  19205. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19206. auto se = detail::scope_exit([&] {
  19207. svr.stop();
  19208. t.join();
  19209. ASSERT_FALSE(svr.is_running());
  19210. });
  19211. svr.wait_until_ready();
  19212. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19213. // a forged address and the trusted proxy's own address; the forged value must
  19214. // not win over the address the trusted proxy actually recorded.
  19215. Client cli(HOST, PORT);
  19216. auto res = cli.Get(
  19217. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19219. EXPECT_EQ(StatusCode::OK_200, res->status);
  19220. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19221. }
  19222. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19223. Server svr;
  19224. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19225. std::string observed_remote_addr;
  19226. std::string observed_xff;
  19227. svr.Get("/ip", [&](const Request &req, Response &res) {
  19228. observed_remote_addr = req.remote_addr;
  19229. observed_xff = req.get_header_value("X-Forwarded-For");
  19230. res.set_content("ok", "text/plain");
  19231. });
  19232. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19233. auto se = detail::scope_exit([&] {
  19234. svr.stop();
  19235. t.join();
  19236. ASSERT_FALSE(svr.is_running());
  19237. });
  19238. svr.wait_until_ready();
  19239. Client cli(HOST, PORT);
  19240. auto res = cli.Get(
  19241. "/ip",
  19242. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19244. EXPECT_EQ(StatusCode::OK_200, res->status);
  19245. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19246. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19247. }
  19248. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19249. Server svr;
  19250. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19251. std::string observed_remote_addr;
  19252. std::string observed_xff;
  19253. svr.Get("/ip", [&](const Request &req, Response &res) {
  19254. observed_remote_addr = req.remote_addr;
  19255. observed_xff = req.get_header_value("X-Forwarded-For");
  19256. res.set_content("ok", "text/plain");
  19257. });
  19258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19259. auto se = detail::scope_exit([&] {
  19260. svr.stop();
  19261. t.join();
  19262. ASSERT_FALSE(svr.is_running());
  19263. });
  19264. svr.wait_until_ready();
  19265. std::string raw_req =
  19266. "GET /ip HTTP/1.1\r\n"
  19267. "Host: localhost\r\n"
  19268. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19269. "Connection: close\r\n"
  19270. "\r\n";
  19271. std::string out;
  19272. ASSERT_TRUE(send_request(5, raw_req, &out));
  19273. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19274. // Header parser trims surrounding whitespace of the header value
  19275. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19276. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19277. }
  19278. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19279. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19280. // their own X-Forwarded-For as a separate field line rather than extending the
  19281. // one the client sent, so every occurrence has to be taken into account.
  19282. // Reading only the first one hands back the address the client chose.
  19283. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19284. Server svr;
  19285. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19286. std::string observed_remote_addr;
  19287. size_t observed_xff_count = 0;
  19288. svr.Get("/ip", [&](const Request &req, Response &res) {
  19289. observed_remote_addr = req.remote_addr;
  19290. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19291. res.set_content("ok", "text/plain");
  19292. });
  19293. auto port = svr.bind_to_any_port(HOST);
  19294. thread t = thread([&]() { svr.listen_after_bind(); });
  19295. auto se = detail::scope_exit([&] {
  19296. svr.stop();
  19297. t.join();
  19298. ASSERT_FALSE(svr.is_running());
  19299. });
  19300. svr.wait_until_ready();
  19301. // The client supplies the first field line; the trusted proxy appends the
  19302. // address it observed as a second one.
  19303. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19304. "Host: localhost\r\n"
  19305. "X-Forwarded-For: 1.2.3.4\r\n"
  19306. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19307. "Connection: close\r\n"
  19308. "\r\n";
  19309. std::string out;
  19310. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19311. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19312. EXPECT_EQ(observed_xff_count, 2U);
  19313. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19314. // The same chain spread over one field line per hop derives the same client
  19315. // address, i.e. the split and the comma-joined representations agree.
  19316. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19317. "Host: localhost\r\n"
  19318. "X-Forwarded-For: 1.2.3.4\r\n"
  19319. "X-Forwarded-For: 198.51.100.23\r\n"
  19320. "X-Forwarded-For: 192.0.2.45\r\n"
  19321. "Connection: close\r\n"
  19322. "\r\n";
  19323. out.clear();
  19324. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19325. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19326. EXPECT_EQ(observed_xff_count, 3U);
  19327. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19328. }
  19329. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19330. // crash the server (it used to call front() on an empty vector inside
  19331. // get_client_ip). The connection-level remote address must be retained instead.
  19332. static void run_malformed_xff_test(const std::string &xff_value) {
  19333. Server svr;
  19334. svr.set_trusted_proxies({"192.0.2.45"});
  19335. std::string observed_remote_addr;
  19336. svr.Get("/ip", [&](const Request &req, Response &res) {
  19337. observed_remote_addr = req.remote_addr;
  19338. res.set_content("ok", "text/plain");
  19339. });
  19340. int port = 0;
  19341. thread t = thread([&]() {
  19342. port = svr.bind_to_any_port(HOST);
  19343. svr.listen_after_bind();
  19344. });
  19345. auto se = detail::scope_exit([&] {
  19346. svr.stop();
  19347. t.join();
  19348. ASSERT_FALSE(svr.is_running());
  19349. });
  19350. svr.wait_until_ready();
  19351. Client cli(HOST, port);
  19352. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19354. EXPECT_EQ(StatusCode::OK_200, res->status);
  19355. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19356. observed_remote_addr == "127.0.0.1");
  19357. }
  19358. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19359. run_malformed_xff_test("");
  19360. }
  19361. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19362. run_malformed_xff_test(",");
  19363. }
  19364. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19365. run_malformed_xff_test(", , ,");
  19366. }
  19367. // The same rule applies to Accept: a request whose acceptable types are spread
  19368. // over several field lines must be negotiated against all of them.
  19369. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19370. // case-insensitive connection options. Comparing the whole field value against
  19371. // one option misses a client that sends several of them, and misses every
  19372. // casing but the one written in the comparison.
  19373. //
  19374. // Sends req, reads the response, then reuses the same socket for a second
  19375. // request to find out whether the server kept the connection.
  19376. static void probe_connection_reuse(int port, const std::string &req,
  19377. bool *announced_close, bool *reusable) {
  19378. auto error = Error::Success;
  19379. auto sock = detail::create_client_socket(
  19380. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19381. /*connection_timeout_sec=*/5, 0,
  19382. /*read_timeout_sec=*/1, 0,
  19383. /*write_timeout_sec=*/5, 0, std::string(), error);
  19384. ASSERT_NE(sock, INVALID_SOCKET);
  19385. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19386. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19387. "Host: localhost\r\n"
  19388. "Connection: close\r\n"
  19389. "\r\n";
  19390. std::string first_response;
  19391. std::string second_response;
  19392. detail::process_client_socket(
  19393. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19394. [&](Stream &strm) {
  19395. if (strm.write(req.data(), req.size()) !=
  19396. static_cast<ssize_t>(req.size())) {
  19397. return false;
  19398. }
  19399. char buf[512];
  19400. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19401. // Headers plus the two-byte body of the handler below
  19402. while (reader.getline()) {
  19403. first_response += reader.ptr();
  19404. if (first_response.find("ok") != std::string::npos) { break; }
  19405. }
  19406. if (strm.write(second.data(), second.size()) !=
  19407. static_cast<ssize_t>(second.size())) {
  19408. return true;
  19409. }
  19410. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19411. while (reader2.getline()) {
  19412. second_response += reader2.ptr();
  19413. if (second_response.find("ok") != std::string::npos) { break; }
  19414. }
  19415. return true;
  19416. });
  19417. *announced_close =
  19418. first_response.find("Connection: close") != std::string::npos;
  19419. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19420. }
  19421. class ConnectionTokenTest : public ::testing::Test {
  19422. protected:
  19423. void SetUp() override {
  19424. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19425. res.set_content("ok", "text/plain");
  19426. });
  19427. port_ = svr_.bind_to_any_port(HOST);
  19428. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19429. svr_.wait_until_ready();
  19430. }
  19431. void TearDown() override {
  19432. svr_.stop();
  19433. if (thread_.joinable()) { thread_.join(); }
  19434. }
  19435. Server svr_;
  19436. int port_ = 0;
  19437. thread thread_;
  19438. };
  19439. // "close" alongside another option still closes the connection, and the
  19440. // response says so rather than leaving the peer to discover it.
  19441. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19442. bool announced_close = false;
  19443. bool reusable = true;
  19444. probe_connection_reuse(port_,
  19445. "GET /keepalive HTTP/1.1\r\n"
  19446. "Host: localhost\r\n"
  19447. "Connection: keep-alive, close\r\n"
  19448. "\r\n",
  19449. &announced_close, &reusable);
  19450. EXPECT_TRUE(announced_close);
  19451. EXPECT_FALSE(reusable);
  19452. }
  19453. // "close" split over two field lines is the same list, so it is honored too.
  19454. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19455. bool announced_close = false;
  19456. bool reusable = true;
  19457. probe_connection_reuse(port_,
  19458. "GET /keepalive HTTP/1.1\r\n"
  19459. "Host: localhost\r\n"
  19460. "Connection: keep-alive\r\n"
  19461. "Connection: close\r\n"
  19462. "\r\n",
  19463. &announced_close, &reusable);
  19464. EXPECT_TRUE(announced_close);
  19465. EXPECT_FALSE(reusable);
  19466. }
  19467. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19468. // keep-alive in the spelling everyone actually sends keeps its connection.
  19469. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19470. bool announced_close = false;
  19471. bool reusable = false;
  19472. probe_connection_reuse(port_,
  19473. "GET /keepalive HTTP/1.0\r\n"
  19474. "Host: localhost\r\n"
  19475. "Connection: keep-alive\r\n"
  19476. "\r\n",
  19477. &announced_close, &reusable);
  19478. EXPECT_FALSE(announced_close);
  19479. EXPECT_TRUE(reusable);
  19480. }
  19481. // A token the value merely contains is not the token itself.
  19482. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19483. bool announced_close = false;
  19484. bool reusable = false;
  19485. probe_connection_reuse(port_,
  19486. "GET /keepalive HTTP/1.1\r\n"
  19487. "Host: localhost\r\n"
  19488. "Connection: notclose\r\n"
  19489. "\r\n",
  19490. &announced_close, &reusable);
  19491. EXPECT_FALSE(announced_close);
  19492. EXPECT_TRUE(reusable);
  19493. }
  19494. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19495. Server svr;
  19496. std::vector<std::string> observed_types;
  19497. svr.Get("/", [&](const Request &req, Response &res) {
  19498. observed_types = req.accept_content_types;
  19499. res.set_content("ok", "text/plain");
  19500. });
  19501. auto port = svr.bind_to_any_port(HOST);
  19502. thread t = thread([&]() { svr.listen_after_bind(); });
  19503. auto se = detail::scope_exit([&] {
  19504. svr.stop();
  19505. t.join();
  19506. ASSERT_FALSE(svr.is_running());
  19507. });
  19508. svr.wait_until_ready();
  19509. Client cli(HOST, port);
  19510. Headers headers;
  19511. headers.emplace("Accept", "text/plain;q=0.5");
  19512. headers.emplace("Accept", "application/json");
  19513. auto res = cli.Get("/", headers);
  19514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19515. EXPECT_EQ(StatusCode::OK_200, res->status);
  19516. // Sorted by q-value, so the second field line's type comes first
  19517. ASSERT_EQ(2U, observed_types.size());
  19518. EXPECT_EQ("application/json", observed_types[0]);
  19519. EXPECT_EQ("text/plain", observed_types[1]);
  19520. }
  19521. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19522. // empty field line must not contribute a bare comma to the combined value.
  19523. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19524. Server svr;
  19525. std::vector<std::string> observed_types;
  19526. svr.Get("/", [&](const Request &req, Response &res) {
  19527. observed_types = req.accept_content_types;
  19528. res.set_content("ok", "text/plain");
  19529. });
  19530. auto port = svr.bind_to_any_port(HOST);
  19531. thread t = thread([&]() { svr.listen_after_bind(); });
  19532. auto se = detail::scope_exit([&] {
  19533. svr.stop();
  19534. t.join();
  19535. ASSERT_FALSE(svr.is_running());
  19536. });
  19537. svr.wait_until_ready();
  19538. // Empty first field line, then a real one
  19539. std::string raw_req = "GET / HTTP/1.1\r\n"
  19540. "Host: localhost\r\n"
  19541. "Accept:\r\n"
  19542. "Accept: application/json\r\n"
  19543. "Connection: close\r\n"
  19544. "\r\n";
  19545. std::string out;
  19546. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19547. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19548. ASSERT_EQ(1U, observed_types.size());
  19549. EXPECT_EQ("application/json", observed_types[0]);
  19550. }
  19551. // The skip in get_combined_header_value() is what keeps an empty field line
  19552. // from contributing a bare comma. Only a trailing empty field line exercises
  19553. // it: a leading one is already covered by the "combined is still empty" check,
  19554. // and parse_accept_header() now ignores the empty element either way, so the
  19555. // request-level test above can no longer tell the two apart.
  19556. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19557. Headers headers;
  19558. headers.emplace("Accept", "text/html");
  19559. headers.emplace("Accept", "");
  19560. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19561. headers.clear();
  19562. headers.emplace("Accept", "");
  19563. headers.emplace("Accept", "application/json");
  19564. EXPECT_EQ("application/json",
  19565. detail::get_combined_header_value(headers, "Accept"));
  19566. }
  19567. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19568. // An encoding offered on a later Accept-Encoding field line is still offered.
  19569. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19570. Server svr;
  19571. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19572. res.set_content(std::string(1024, 'x'), "text/plain");
  19573. });
  19574. auto port = svr.bind_to_any_port(HOST);
  19575. thread t = thread([&]() { svr.listen_after_bind(); });
  19576. auto se = detail::scope_exit([&] {
  19577. svr.stop();
  19578. t.join();
  19579. ASSERT_FALSE(svr.is_running());
  19580. });
  19581. svr.wait_until_ready();
  19582. Client cli(HOST, port);
  19583. cli.set_decompress(false);
  19584. Headers headers;
  19585. headers.emplace("Accept-Encoding", "identity");
  19586. headers.emplace("Accept-Encoding", "gzip");
  19587. auto res = cli.Get("/", headers);
  19588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19589. EXPECT_EQ(StatusCode::OK_200, res->status);
  19590. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19591. }
  19592. #endif
  19593. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19594. // Transfer-Encoding is not its body.
  19595. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19596. Server svr;
  19597. svr.set_payload_max_length(8);
  19598. svr.Post("/test", [](const Request &, Response &res) {
  19599. res.set_content("ok", "text/plain");
  19600. });
  19601. auto port = svr.bind_to_any_port(HOST);
  19602. ASSERT_GT(port, 0);
  19603. thread t = thread([&] { svr.listen_after_bind(); });
  19604. auto se = detail::scope_exit([&] {
  19605. svr.stop();
  19606. t.join();
  19607. ASSERT_FALSE(svr.is_running());
  19608. });
  19609. svr.wait_until_ready();
  19610. std::string resp;
  19611. ASSERT_TRUE(send_request(1,
  19612. "POST /test HTTP/1.1\r\n"
  19613. "Host: localhost\r\n"
  19614. "Connection: close\r\n"
  19615. "\r\n" +
  19616. std::string(16, 'X'),
  19617. &resp, port));
  19618. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19619. }
  19620. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19621. Server svr;
  19622. svr.Post("/post", [&](const Request &req, Response &res) {
  19623. res.set_content(req.body, "text/plain");
  19624. });
  19625. svr.Put("/put", [&](const Request &req, Response &res) {
  19626. res.set_content(req.body, "text/plain");
  19627. });
  19628. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19629. res.set_content(req.body, "text/plain");
  19630. });
  19631. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19632. res.set_content(req.body, "text/plain");
  19633. });
  19634. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19635. auto se = detail::scope_exit([&] {
  19636. svr.stop();
  19637. t.join();
  19638. ASSERT_FALSE(svr.is_running());
  19639. });
  19640. svr.wait_until_ready();
  19641. std::string resp;
  19642. // POST without Content-Length
  19643. ASSERT_TRUE(send_request(5,
  19644. "POST /post HTTP/1.1\r\n"
  19645. "Host: localhost\r\n"
  19646. "Connection: close\r\n"
  19647. "\r\n",
  19648. &resp));
  19649. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19650. // PUT without Content-Length
  19651. resp.clear();
  19652. ASSERT_TRUE(send_request(5,
  19653. "PUT /put HTTP/1.1\r\n"
  19654. "Host: localhost\r\n"
  19655. "Connection: close\r\n"
  19656. "\r\n",
  19657. &resp));
  19658. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19659. // PATCH without Content-Length
  19660. resp.clear();
  19661. ASSERT_TRUE(send_request(5,
  19662. "PATCH /patch HTTP/1.1\r\n"
  19663. "Host: localhost\r\n"
  19664. "Connection: close\r\n"
  19665. "\r\n",
  19666. &resp));
  19667. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19668. // DELETE without Content-Length
  19669. resp.clear();
  19670. ASSERT_TRUE(send_request(5,
  19671. "DELETE /delete HTTP/1.1\r\n"
  19672. "Host: localhost\r\n"
  19673. "Connection: close\r\n"
  19674. "\r\n",
  19675. &resp));
  19676. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19677. }
  19678. //==============================================================================
  19679. // open_stream() Tests
  19680. //==============================================================================
  19681. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19682. std::string result;
  19683. char buf[8192];
  19684. ssize_t n;
  19685. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19686. result.append(buf, static_cast<size_t>(n));
  19687. }
  19688. return result;
  19689. }
  19690. // Mock stream for unit tests
  19691. class MockStream : public Stream {
  19692. public:
  19693. std::string data;
  19694. size_t pos = 0;
  19695. ssize_t error_after = -1; // -1 = no error
  19696. explicit MockStream(const std::string &d, ssize_t err = -1)
  19697. : data(d), error_after(err) {}
  19698. bool is_readable() const override { return true; }
  19699. bool wait_readable() const override { return true; }
  19700. bool wait_writable() const override { return true; }
  19701. ssize_t read(char *ptr, size_t size) override {
  19702. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19703. if (pos >= data.size()) return 0;
  19704. size_t limit =
  19705. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19706. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19707. std::memcpy(ptr, data.data() + pos, to_read);
  19708. pos += to_read;
  19709. return static_cast<ssize_t>(to_read);
  19710. }
  19711. ssize_t write(const char *, size_t) override { return -1; }
  19712. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19713. ip = "127.0.0.1";
  19714. port = 0;
  19715. }
  19716. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19717. ip = "127.0.0.1";
  19718. port = 0;
  19719. }
  19720. socket_t socket() const override { return INVALID_SOCKET; }
  19721. time_t duration() const override { return 0; }
  19722. };
  19723. TEST(StreamHandleTest, Basic) {
  19724. ClientImpl::StreamHandle handle;
  19725. EXPECT_FALSE(handle.is_valid());
  19726. handle.response = detail::make_unique<Response>();
  19727. handle.error = Error::Connection;
  19728. EXPECT_FALSE(handle.is_valid());
  19729. handle.error = Error::Success;
  19730. EXPECT_TRUE(handle.is_valid());
  19731. }
  19732. TEST(BodyReaderTest, Basic) {
  19733. MockStream stream("Hello, World!");
  19734. detail::BodyReader reader;
  19735. reader.stream = &stream;
  19736. reader.content_length = 13;
  19737. char buf[32];
  19738. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19739. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19740. EXPECT_TRUE(reader.eof);
  19741. }
  19742. TEST(BodyReaderTest, NoStream) {
  19743. detail::BodyReader reader;
  19744. char buf[32];
  19745. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19746. EXPECT_EQ(Error::Connection, reader.last_error);
  19747. }
  19748. TEST(BodyReaderTest, Error) {
  19749. MockStream stream("Hello, World!", 5);
  19750. detail::BodyReader reader;
  19751. reader.stream = &stream;
  19752. reader.content_length = 13;
  19753. char buf[32];
  19754. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19755. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19756. EXPECT_EQ(Error::Read, reader.last_error);
  19757. }
  19758. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19759. // Mock-based StreamHandle tests relying on private internals are removed.
  19760. class OpenStreamTest : public ::testing::Test {
  19761. protected:
  19762. void SetUp() override {
  19763. svr_.Get("/hello", [](const Request &, Response &res) {
  19764. res.set_content("Hello World!", "text/plain");
  19765. });
  19766. svr_.Get("/large", [](const Request &, Response &res) {
  19767. res.set_content(std::string(10000, 'X'), "text/plain");
  19768. });
  19769. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19770. res.set_content("Hello World!", "image/jpeg");
  19771. res.set_header("Content-Encoding", "UTF-8");
  19772. });
  19773. svr_.Get("/chunked", [](const Request &, Response &res) {
  19774. res.set_chunked_content_provider("text/plain",
  19775. [](size_t offset, DataSink &sink) {
  19776. if (offset < 15) {
  19777. sink.write("chunk", 5);
  19778. return true;
  19779. }
  19780. sink.done();
  19781. return true;
  19782. });
  19783. });
  19784. svr_.Get("/compressible", [](const Request &, Response &res) {
  19785. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19786. DataSink &sink) {
  19787. if (offset < 100 * 1024) {
  19788. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19789. sink.write(chunk.data(), chunk.size());
  19790. return true;
  19791. }
  19792. sink.done();
  19793. return true;
  19794. });
  19795. });
  19796. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19797. [](const Request & /*req*/, Response &res) {
  19798. auto i = new int(0);
  19799. res.set_header("Trailer", "Content-Length, X-Allowed");
  19800. res.set_chunked_content_provider(
  19801. "text/plain",
  19802. [i](size_t /*offset*/, DataSink &sink) {
  19803. switch (*i) {
  19804. case 0: sink.os << "123"; break;
  19805. case 1: sink.os << "456"; break;
  19806. case 2: sink.os << "789"; break;
  19807. case 3: {
  19808. sink.done_with_trailer(
  19809. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19810. } break;
  19811. }
  19812. (*i)++;
  19813. return true;
  19814. },
  19815. [i](bool success) {
  19816. EXPECT_TRUE(success);
  19817. delete i;
  19818. });
  19819. });
  19820. // Echo headers endpoint for header-related tests
  19821. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19822. std::string body;
  19823. for (const auto &h : req.headers) {
  19824. body.append(h.first);
  19825. body.push_back(':');
  19826. body.append(h.second);
  19827. body.push_back('\n');
  19828. }
  19829. res.set_content(body, "text/plain");
  19830. });
  19831. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19832. std::string body;
  19833. for (const auto &h : req.headers) {
  19834. body.append(h.first);
  19835. body.push_back(':');
  19836. body.append(h.second);
  19837. body.push_back('\n');
  19838. }
  19839. res.set_content(body, "text/plain");
  19840. });
  19841. port_ = svr_.bind_to_any_port("127.0.0.1");
  19842. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19843. svr_.wait_until_ready();
  19844. }
  19845. void TearDown() override {
  19846. svr_.stop();
  19847. if (thread_.joinable()) thread_.join();
  19848. }
  19849. Server svr_;
  19850. std::thread thread_;
  19851. int port_ = 0;
  19852. };
  19853. TEST_F(OpenStreamTest, Basic) {
  19854. Client cli("127.0.0.1", port_);
  19855. auto handle = cli.open_stream("GET", "/hello");
  19856. EXPECT_TRUE(handle.is_valid());
  19857. EXPECT_EQ("Hello World!", read_all(handle));
  19858. }
  19859. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19860. Client cli("127.0.0.1", port_);
  19861. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19862. ASSERT_TRUE(handle.is_valid());
  19863. EXPECT_EQ("Hello World!", read_all(handle));
  19864. }
  19865. TEST_F(OpenStreamTest, SmallBuffer) {
  19866. Client cli("127.0.0.1", port_);
  19867. auto handle = cli.open_stream("GET", "/hello");
  19868. std::string result;
  19869. char buf[4];
  19870. ssize_t n;
  19871. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19872. result.append(buf, static_cast<size_t>(n));
  19873. EXPECT_EQ("Hello World!", result);
  19874. }
  19875. TEST_F(OpenStreamTest, DefaultHeaders) {
  19876. Client cli("127.0.0.1", port_);
  19877. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19878. {
  19879. auto handle = cli.open_stream("GET", "/echo-headers");
  19880. ASSERT_TRUE(handle.is_valid());
  19881. auto body = read_all(handle);
  19882. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19883. std::string::npos);
  19884. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19885. std::string::npos);
  19886. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19887. }
  19888. // open_stream POST with body and no explicit content_type should NOT add
  19889. // text/plain Content-Type (behavior differs from non-streaming path), but
  19890. // should include Content-Length
  19891. {
  19892. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19893. ASSERT_TRUE(handle.is_valid());
  19894. auto body = read_all(handle);
  19895. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19896. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19897. }
  19898. // open_stream POST with explicit Content-Type should preserve it
  19899. {
  19900. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19901. {{"Content-Type", "application/custom"}},
  19902. "{}", "application/custom");
  19903. ASSERT_TRUE(handle.is_valid());
  19904. auto body = read_all(handle);
  19905. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19906. }
  19907. // User-specified User-Agent must not be overwritten for stream API
  19908. {
  19909. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19910. {{"User-Agent", "MyAgent/1.2"}});
  19911. ASSERT_TRUE(handle.is_valid());
  19912. auto body = read_all(handle);
  19913. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19914. }
  19915. }
  19916. TEST_F(OpenStreamTest, Large) {
  19917. Client cli("127.0.0.1", port_);
  19918. auto handle = cli.open_stream("GET", "/large");
  19919. EXPECT_EQ(10000u, read_all(handle).size());
  19920. }
  19921. TEST_F(OpenStreamTest, ConnectionError) {
  19922. Client cli("127.0.0.1", 9999);
  19923. auto handle = cli.open_stream("GET", "/hello");
  19924. EXPECT_FALSE(handle.is_valid());
  19925. }
  19926. TEST_F(OpenStreamTest, Chunked) {
  19927. Client cli("127.0.0.1", port_);
  19928. auto handle = cli.open_stream("GET", "/chunked");
  19929. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19930. "Transfer-Encoding") == "chunked");
  19931. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19932. }
  19933. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19934. Client cli("127.0.0.1", port_);
  19935. auto handle =
  19936. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19937. ASSERT_TRUE(handle.is_valid());
  19938. // Consume body to allow trailers to be received/parsed
  19939. auto body = read_all(handle);
  19940. // Explicitly parse trailers (ensure trailers are available for assertion)
  19941. handle.parse_trailers_if_needed();
  19942. EXPECT_EQ(std::string("123456789"), body);
  19943. // The response should include a Trailer header declaring both names
  19944. ASSERT_TRUE(handle.response);
  19945. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19946. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19947. handle.response->get_header_value("Trailer"));
  19948. // Prohibited trailer must not be present
  19949. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19950. // Allowed trailer should be present
  19951. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19952. EXPECT_EQ(std::string("yes"),
  19953. handle.response->get_trailer_value("X-Allowed"));
  19954. // Verify trailers are NOT present as regular headers
  19955. EXPECT_EQ(std::string(""),
  19956. handle.response->get_header_value("Content-Length"));
  19957. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19958. }
  19959. // Accepts one connection on an OS-assigned port, which it hands over through
  19960. // port_promise, reads the request head and sends back response. after_send,
  19961. // if given, runs on the connection before it is closed.
  19962. static std::thread
  19963. serve_single_response(std::promise<int> &port_promise,
  19964. const std::string &response,
  19965. std::function<void(socket_t)> after_send = nullptr) {
  19966. return std::thread([&port_promise, response, after_send] {
  19967. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19968. default_socket_options(srv);
  19969. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19970. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19971. sockaddr_in addr{};
  19972. addr.sin_family = AF_INET;
  19973. addr.sin_port = htons(0); // Let OS assign a free port
  19974. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19975. int opt = 1;
  19976. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19977. #ifdef _WIN32
  19978. reinterpret_cast<const char *>(&opt),
  19979. #else
  19980. &opt,
  19981. #endif
  19982. sizeof(opt));
  19983. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19984. ::listen(srv, 1) != 0) {
  19985. port_promise.set_value(-1);
  19986. detail::close_socket(srv);
  19987. return;
  19988. }
  19989. socklen_t addr_len = sizeof(addr);
  19990. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19991. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19992. sockaddr_in cli_addr{};
  19993. socklen_t cli_len = sizeof(cli_addr);
  19994. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19995. if (cli != INVALID_SOCKET) {
  19996. // Read the complete HTTP request (until the blank line that terminates
  19997. // headers) before sending the response. If the server closes the socket
  19998. // while the client's request data is still unread in the kernel receive
  19999. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20000. // connection on both sides: it discards the client's receive buffer
  20001. // (which already holds our response) and causes any in-progress write on
  20002. // the client to fail with ECONNRESET. Reading all request data first
  20003. // ensures close() emits a graceful FIN.
  20004. {
  20005. char rbuf[256];
  20006. std::string req;
  20007. while (req.find("\r\n\r\n") == std::string::npos) {
  20008. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20009. if (n <= 0) { break; }
  20010. req.append(rbuf, static_cast<size_t>(n));
  20011. }
  20012. }
  20013. ::send(cli,
  20014. #ifdef _WIN32
  20015. static_cast<const char *>(response.c_str()),
  20016. static_cast<int>(response.size()),
  20017. #else
  20018. response.c_str(), response.size(),
  20019. #endif
  20020. 0);
  20021. if (after_send) { after_send(cli); }
  20022. detail::close_socket(cli);
  20023. }
  20024. detail::close_socket(srv);
  20025. });
  20026. }
  20027. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20028. #ifndef _WIN32
  20029. signal(SIGPIPE, SIG_IGN);
  20030. #endif
  20031. std::promise<int> port_promise;
  20032. auto port_future = port_promise.get_future();
  20033. auto server_thread =
  20034. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20035. "Content-Type: text/plain\r\n"
  20036. "Content-Length: not-a-number\r\n"
  20037. "Connection: close\r\n"
  20038. "\r\n"
  20039. "hello");
  20040. auto port = port_future.get();
  20041. ASSERT_GT(port, 0);
  20042. Client cli("127.0.0.1", port);
  20043. auto handle = cli.open_stream("GET", "/");
  20044. EXPECT_FALSE(handle.is_valid());
  20045. server_thread.join();
  20046. }
  20047. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20048. #ifndef _WIN32
  20049. signal(SIGPIPE, SIG_IGN);
  20050. #endif
  20051. std::promise<int> port_promise;
  20052. auto port_future = port_promise.get_future();
  20053. auto server_thread = serve_single_response(
  20054. port_promise, "HTTP/1.1 200 OK\r\n"
  20055. "Content-Type: text/plain\r\n"
  20056. "Content-Length: 99999999999999999999999999\r\n"
  20057. "Connection: close\r\n"
  20058. "\r\n"
  20059. "hello");
  20060. auto port = port_future.get();
  20061. ASSERT_GT(port, 0);
  20062. // Historically std::stoull would throw std::out_of_range here and crash
  20063. // the process, then parsing silently clamped to a bogus framing length and
  20064. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20065. // so the stream fails to open, matching the not-a-number case above. The
  20066. // process still must NOT terminate.
  20067. Client cli("127.0.0.1", port);
  20068. auto handle = cli.open_stream("GET", "/");
  20069. EXPECT_FALSE(handle.is_valid());
  20070. server_thread.join();
  20071. }
  20072. #ifndef _WIN32
  20073. // As above for the body of a streamed request: a send() cut short by the write
  20074. // timeout must not leave the rest of the body unsent.
  20075. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20076. signal(SIGPIPE, SIG_IGN);
  20077. Server svr;
  20078. svr.set_socket_options([](socket_t sock) {
  20079. int size = 8192;
  20080. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20081. reinterpret_cast<const char *>(&size), sizeof(size));
  20082. });
  20083. svr.Post("/size", [](const Request &, Response &res,
  20084. const ContentReader &content_reader) {
  20085. // Outlast the client's write timeout before reading the body.
  20086. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20087. size_t received = 0;
  20088. content_reader([&](const char *, size_t len) {
  20089. received += len;
  20090. return true;
  20091. });
  20092. res.set_content(std::to_string(received), "text/plain");
  20093. });
  20094. auto port = svr.bind_to_any_port(HOST);
  20095. std::thread t([&]() { svr.listen_after_bind(); });
  20096. auto se = detail::scope_exit([&] {
  20097. svr.stop();
  20098. t.join();
  20099. });
  20100. svr.wait_until_ready();
  20101. Client cli(HOST, port);
  20102. cli.set_write_timeout(0, 500000);
  20103. cli.set_socket_options([](socket_t sock) {
  20104. int size = 8192;
  20105. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20106. reinterpret_cast<const char *>(&size), sizeof(size));
  20107. });
  20108. const std::string body(4 * 1024 * 1024, 'A');
  20109. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20110. "application/octet-stream");
  20111. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20112. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20113. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20114. }
  20115. #endif
  20116. // Serves `response` to the single request `fn` makes with a fresh client.
  20117. template <typename Fn>
  20118. static void with_single_response(const std::string &response, Fn fn) {
  20119. #ifndef _WIN32
  20120. signal(SIGPIPE, SIG_IGN);
  20121. #endif
  20122. std::promise<int> port_promise;
  20123. auto port_future = port_promise.get_future();
  20124. auto server_thread = serve_single_response(port_promise, response);
  20125. auto se = detail::scope_exit([&] { server_thread.join(); });
  20126. auto port = port_future.get();
  20127. ASSERT_GT(port, 0);
  20128. Client cli("127.0.0.1", port);
  20129. fn(cli);
  20130. }
  20131. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20132. // too, also in a build without the decoder for the advertised coding.
  20133. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20134. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20135. const auto response = "HTTP/1.1 200 OK\r\n"
  20136. "Content-Encoding: gzip\r\n"
  20137. "Content-Length: " +
  20138. std::to_string(gzipped.size()) +
  20139. "\r\n"
  20140. "Connection: close\r\n\r\n" +
  20141. gzipped;
  20142. with_single_response(response, [&](Client &cli) {
  20143. cli.set_decompress(false);
  20144. auto handle = cli.open_stream("GET", "/");
  20145. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20146. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20147. EXPECT_EQ(gzipped, read_all(handle));
  20148. EXPECT_FALSE(handle.has_read_error());
  20149. });
  20150. with_single_response(response, [&](Client &cli) {
  20151. cli.set_decompress(false);
  20152. auto res = stream::Get(cli, "/", 7);
  20153. ASSERT_TRUE(res) << to_string(res.error());
  20154. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20155. EXPECT_EQ(gzipped, res.read_all());
  20156. EXPECT_FALSE(res.has_read_error());
  20157. });
  20158. }
  20159. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20160. // Neither Content-Length nor chunked: the body ends at the close
  20161. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20162. "Connection: close\r\n"
  20163. "\r\n"
  20164. "hello";
  20165. with_single_response(close_delimited, [](Client &cli) {
  20166. auto handle = cli.open_stream("GET", "/");
  20167. ASSERT_TRUE(handle.is_valid());
  20168. EXPECT_EQ("hello", read_all(handle));
  20169. EXPECT_FALSE(handle.has_read_error());
  20170. });
  20171. // A close before the end of the Content-Length is still an error
  20172. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20173. "Content-Length: 10\r\n"
  20174. "\r\n"
  20175. "hello";
  20176. with_single_response(short_content_length, [](Client &cli) {
  20177. auto handle = cli.open_stream("GET", "/");
  20178. ASSERT_TRUE(handle.is_valid());
  20179. read_all(handle);
  20180. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20181. });
  20182. // So is a close before the last chunk
  20183. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20184. "Transfer-Encoding: chunked\r\n"
  20185. "\r\n"
  20186. "5\r\nhello\r\n";
  20187. with_single_response(short_chunked, [](Client &cli) {
  20188. auto handle = cli.open_stream("GET", "/");
  20189. ASSERT_TRUE(handle.is_valid());
  20190. read_all(handle);
  20191. EXPECT_TRUE(handle.has_read_error());
  20192. });
  20193. }
  20194. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20195. const char *responses[] = {
  20196. "HTTP/1.1 103 Early Hints\r\n"
  20197. "Link: </style.css>; rel=preload\r\n"
  20198. "\r\n"
  20199. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20200. "HTTP/1.1 100 Continue\r\n"
  20201. "X-Note: interim\r\n"
  20202. "\r\n"
  20203. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20204. };
  20205. for (auto response : responses) {
  20206. with_single_response(response, [](Client &cli) {
  20207. auto res = cli.Get("/");
  20208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20209. EXPECT_EQ(StatusCode::OK_200, res->status);
  20210. EXPECT_EQ("ok", res->body);
  20211. });
  20212. }
  20213. }
  20214. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20215. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20216. const std::string final_response =
  20217. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20218. std::string interims;
  20219. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20220. interims += interim;
  20221. }
  20222. with_single_response(interims + final_response, [](Client &cli) {
  20223. auto res = cli.Get("/");
  20224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20225. EXPECT_EQ("ok", res->body);
  20226. });
  20227. with_single_response(interims + interim + final_response, [](Client &cli) {
  20228. auto res = cli.Get("/");
  20229. ASSERT_FALSE(res);
  20230. EXPECT_EQ(Error::Read, res.error());
  20231. });
  20232. }
  20233. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20234. #ifndef _WIN32
  20235. signal(SIGPIPE, SIG_IGN);
  20236. #endif
  20237. // The server answers the head without asking for the body. Bytes it then
  20238. // reads on the connection would be taken for the body the request declared.
  20239. auto closed_by_client = false;
  20240. std::promise<int> port_promise;
  20241. auto server_thread = serve_single_response(
  20242. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20243. [&](socket_t sock) {
  20244. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20245. char buf[256];
  20246. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20247. });
  20248. Client cli("127.0.0.1", port_promise.get_future().get());
  20249. cli.set_keep_alive(true);
  20250. cli.set_read_timeout(1, 0);
  20251. // Long enough for the client to send Expect: 100-continue.
  20252. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20254. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20255. cli.Get("/second");
  20256. server_thread.join();
  20257. EXPECT_TRUE(closed_by_client);
  20258. }
  20259. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20260. // Long enough for the client to send Expect: 100-continue
  20261. with_single_response(
  20262. "HTTP/1.1 103 Early Hints\r\n"
  20263. "Link: </style.css>; rel=preload\r\n"
  20264. "\r\n"
  20265. "HTTP/1.1 401 Unauthorized\r\n"
  20266. "Content-Length: 0\r\n\r\n",
  20267. [](Client &cli) {
  20268. cli.set_read_timeout(2, 0);
  20269. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20271. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20272. });
  20273. }
  20274. #ifdef CPPHTTPLIB_SSL_ENABLED
  20275. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20276. #ifndef _WIN32
  20277. signal(SIGPIPE, SIG_IGN);
  20278. #endif
  20279. auto reused = false;
  20280. std::promise<int> port_promise;
  20281. auto server_thread = serve_single_response(
  20282. port_promise,
  20283. "HTTP/1.1 401 Unauthorized\r\n"
  20284. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20285. "Content-Length: 0\r\n\r\n",
  20286. [&](socket_t sock) {
  20287. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20288. char buf[256];
  20289. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20290. });
  20291. Client cli("127.0.0.1", port_promise.get_future().get());
  20292. cli.set_keep_alive(true);
  20293. cli.set_digest_auth("user", "pass");
  20294. cli.set_read_timeout(1, 0);
  20295. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20296. server_thread.join();
  20297. EXPECT_FALSE(reused);
  20298. }
  20299. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20300. // Any other answer to CONNECT would read as the origin's response.
  20301. struct {
  20302. const char *response;
  20303. bool passed_on;
  20304. } cases[] = {
  20305. {"HTTP/1.1 201 Created\r\n"
  20306. "Set-Cookie: session=from-proxy\r\n"
  20307. "Content-Length: 0\r\n\r\n",
  20308. false},
  20309. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20310. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20311. "Content-Length: 0\r\n\r\n",
  20312. true},
  20313. };
  20314. for (const auto &c : cases) {
  20315. std::promise<int> port_promise;
  20316. auto server_thread = serve_single_response(port_promise, c.response);
  20317. SSLClient cli("example.com", 443);
  20318. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20319. auto res = cli.Get("/");
  20320. server_thread.join();
  20321. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20322. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20323. if (res) {
  20324. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20325. }
  20326. }
  20327. }
  20328. #endif
  20329. // Records the client's error logger calls as "error METHOD path", or
  20330. // "error null" for a call without a request
  20331. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20332. return [&log](const Error &err, const Request *req) {
  20333. log.push_back(to_string(err) + " " +
  20334. (req ? req->method + " " + req->path : "null"));
  20335. };
  20336. }
  20337. // A failed request is reported once, with the request the caller made
  20338. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20339. Server svr;
  20340. svr.Get("/big", [](const Request &, Response &res) {
  20341. res.set_content(std::string(100000, 'b'), "text/plain");
  20342. });
  20343. auto port = svr.bind_to_any_port(HOST);
  20344. std::thread t([&]() { svr.listen_after_bind(); });
  20345. auto se = detail::scope_exit([&] {
  20346. svr.stop();
  20347. t.join();
  20348. });
  20349. svr.wait_until_ready();
  20350. Client cli(HOST, port);
  20351. std::vector<std::string> log;
  20352. cli.set_error_logger(record_errors(log));
  20353. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20354. cli.Get("/big", [](const char *, size_t) { return false; });
  20355. EXPECT_EQ(expected, log);
  20356. log.clear();
  20357. cli.Get("/big", [](size_t, size_t) { return false; });
  20358. EXPECT_EQ(expected, log);
  20359. }
  20360. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20361. // Fails while the body is read
  20362. auto broken = [](const Request &, Response &res) {
  20363. res.set_content_provider(10, "text/plain",
  20364. [](size_t, size_t, DataSink &) { return false; });
  20365. };
  20366. Server other;
  20367. other.Get("/broken", broken);
  20368. auto other_port = other.bind_to_any_port(HOST);
  20369. std::thread other_t([&]() { other.listen_after_bind(); });
  20370. auto other_se = detail::scope_exit([&] {
  20371. other.stop();
  20372. other_t.join();
  20373. });
  20374. other.wait_until_ready();
  20375. Server svr;
  20376. svr.Get("/broken", broken);
  20377. svr.Get("/same-origin",
  20378. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20379. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20380. res.set_redirect("http://" + std::string(HOST) + ":" +
  20381. std::to_string(other_port) + "/broken");
  20382. });
  20383. auto port = svr.bind_to_any_port(HOST);
  20384. std::thread t([&]() { svr.listen_after_bind(); });
  20385. auto se = detail::scope_exit([&] {
  20386. svr.stop();
  20387. t.join();
  20388. });
  20389. svr.wait_until_ready();
  20390. Client cli(HOST, port);
  20391. cli.set_follow_location(true);
  20392. std::vector<std::string> log;
  20393. cli.set_error_logger(record_errors(log));
  20394. for (auto path : {"/same-origin", "/cross-origin"}) {
  20395. log.clear();
  20396. auto res = cli.Get(path);
  20397. ASSERT_FALSE(res);
  20398. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20399. log);
  20400. }
  20401. }
  20402. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20403. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20404. std::vector<std::string> log;
  20405. cli.set_error_logger(record_errors(log));
  20406. auto handle = cli.open_stream("GET", "/x");
  20407. EXPECT_FALSE(handle.is_valid());
  20408. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20409. log);
  20410. });
  20411. }
  20412. #ifdef CPPHTTPLIB_SSL_ENABLED
  20413. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20414. // Not a TLS server, so the handshake fails. It waits for a request line in
  20415. // the handshake bytes, so a short read timeout lets it close quickly.
  20416. Server svr;
  20417. svr.set_read_timeout(0, 100000);
  20418. svr.Get("/x", [](const Request &, Response &res) {
  20419. res.set_content("x", "text/plain");
  20420. });
  20421. auto port = svr.bind_to_any_port(HOST);
  20422. std::thread t([&]() { svr.listen_after_bind(); });
  20423. auto se = detail::scope_exit([&] {
  20424. svr.stop();
  20425. t.join();
  20426. });
  20427. svr.wait_until_ready();
  20428. std::vector<std::string> log;
  20429. SSLClient cli(HOST, port);
  20430. cli.enable_server_certificate_verification(false);
  20431. cli.set_error_logger(record_errors(log));
  20432. auto res = cli.Get("/x");
  20433. ASSERT_FALSE(res);
  20434. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20435. log.clear();
  20436. auto handle = cli.open_stream("GET", "/x");
  20437. EXPECT_FALSE(handle.is_valid());
  20438. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20439. log.clear();
  20440. SSLClient no_ca(HOST, port);
  20441. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20442. no_ca.set_error_logger(record_errors(log));
  20443. res = no_ca.Get("/x");
  20444. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20445. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20446. }
  20447. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20448. #ifndef _WIN32
  20449. signal(SIGPIPE, SIG_IGN);
  20450. #endif
  20451. // Refused, answered with a challenge, or closed without an answer
  20452. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20453. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20454. "Content-Length: 0\r\n\r\n",
  20455. ""}) {
  20456. std::promise<int> port_promise;
  20457. auto server_thread = serve_single_response(port_promise, response);
  20458. SSLClient cli("example.com", 443);
  20459. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20460. std::vector<std::string> log;
  20461. cli.set_error_logger(record_errors(log));
  20462. auto res = cli.Get("/");
  20463. server_thread.join();
  20464. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20465. << response;
  20466. }
  20467. }
  20468. #endif
  20469. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20470. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20471. // the chunked coding and drop Content-Length, so a front-end that trusts
  20472. // Content-Length would disagree about where the body ends (response
  20473. // smuggling). The client must reject such a response.
  20474. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20475. for (const char *te : {"chunked", "gzip, chunked"}) {
  20476. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20477. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20478. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20479. "5\r\nhello\r\n0\r\n\r\n";
  20480. with_single_response(response, [&](Client &cli) {
  20481. auto res = cli.Get("/");
  20482. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20483. EXPECT_EQ(Error::Read, res.error()) << te;
  20484. });
  20485. with_single_response(response, [&](Client &cli) {
  20486. auto handle = cli.open_stream("GET", "/");
  20487. EXPECT_FALSE(handle.is_valid()) << te;
  20488. EXPECT_EQ(Error::Read, handle.error) << te;
  20489. });
  20490. }
  20491. }
  20492. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20493. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20494. // closing the connection (unlike a request, which must be rejected).
  20495. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20496. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20497. "Transfer-Encoding: chunked\r\n"
  20498. "Connection: close\r\n"
  20499. "\r\n"
  20500. "5\r\nhello\r\n0\r\n\r\n",
  20501. "HTTP/1.1 200 OK\r\n"
  20502. "Transfer-Encoding: gzip\r\n"
  20503. "Connection: close\r\n"
  20504. "\r\n"
  20505. "hello"}) {
  20506. with_single_response(response, [&](Client &cli) {
  20507. auto res = cli.Get("/");
  20508. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20509. EXPECT_EQ("hello", res->body);
  20510. });
  20511. with_single_response(response, [&](Client &cli) {
  20512. auto handle = cli.open_stream("GET", "/");
  20513. ASSERT_TRUE(handle.is_valid()) << response;
  20514. EXPECT_EQ("hello", read_all(handle));
  20515. });
  20516. }
  20517. }
  20518. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20519. // framing headers describe nothing to read and must not be rejected.
  20520. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20521. const std::string framing = "Content-Length: 5\r\n"
  20522. "Transfer-Encoding: chunked\r\n"
  20523. "Connection: close\r\n"
  20524. "\r\n";
  20525. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20526. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20527. });
  20528. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20529. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20530. });
  20531. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20532. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20533. with_single_response(response, [&](Client &cli) {
  20534. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20535. });
  20536. with_single_response(response, [&](Client &cli) {
  20537. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20538. });
  20539. }
  20540. }
  20541. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20542. // header section, so a stream opened on one has nothing to read, whatever
  20543. // framing or coding headers it carries.
  20544. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20545. struct Case {
  20546. const char *method;
  20547. const char *status;
  20548. };
  20549. // A reader of the declared body reports an early close when nothing
  20550. // follows, and hands back what does.
  20551. struct Framing {
  20552. const char *headers;
  20553. const char *after;
  20554. };
  20555. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20556. Case{"GET", "304 Not Modified"}}) {
  20557. for (const auto &f :
  20558. {Framing{"Content-Length: 5\r\n", ""},
  20559. Framing{"Content-Length: 5\r\n", "hello"},
  20560. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20561. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20562. // Not decoded, so a build without Brotli opens it too
  20563. Framing{"Content-Encoding: br\r\n", ""}}) {
  20564. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20565. "Connection: close\r\n"
  20566. "\r\n" +
  20567. f.after;
  20568. with_single_response(response, [&](Client &cli) {
  20569. auto handle = cli.open_stream(c.method, "/");
  20570. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20571. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20572. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20573. });
  20574. }
  20575. }
  20576. }
  20577. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20578. // response, is faulty framing, so the connection is not reused after it.
  20579. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20580. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20581. "Content-Length: 0\r\n"
  20582. "Transfer-Encoding: chunked\r\n"
  20583. "\r\n"
  20584. "5\r\nhello\r\n0\r\n\r\n",
  20585. "HTTP/1.0 200 Connection established\r\n"
  20586. "Connection: keep-alive\r\n"
  20587. "Transfer-Encoding: chunked\r\n"
  20588. "\r\n"
  20589. "5\r\nhello\r\n0\r\n\r\n"}) {
  20590. with_single_response(response, [&](Client &cli) {
  20591. cli.set_keep_alive(true);
  20592. auto res = cli.Get("/");
  20593. ASSERT_TRUE(res) << response;
  20594. EXPECT_EQ("hello", res->body);
  20595. EXPECT_FALSE(cli.is_socket_open()) << response;
  20596. });
  20597. }
  20598. }
  20599. // A payload max length of 0 means no limit, however the body is framed.
  20600. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20601. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20602. "Transfer-Encoding: chunked\r\n"
  20603. "\r\n"
  20604. "5\r\nhello\r\n0\r\n\r\n",
  20605. "HTTP/1.1 200 OK\r\n"
  20606. "Connection: close\r\n"
  20607. "\r\n"
  20608. "hello"}) {
  20609. with_single_response(response, [&](Client &cli) {
  20610. cli.set_payload_max_length(0);
  20611. auto res = cli.Get("/");
  20612. ASSERT_TRUE(res) << response;
  20613. EXPECT_EQ("hello", res->body) << response;
  20614. });
  20615. }
  20616. }
  20617. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20618. Server svr;
  20619. svr.set_payload_max_length(0);
  20620. svr.Post("/echo", [](const Request &req, Response &res) {
  20621. res.set_content(req.body, "text/plain");
  20622. });
  20623. auto port = svr.bind_to_any_port(HOST);
  20624. thread t = thread([&] { svr.listen_after_bind(); });
  20625. auto se = detail::scope_exit([&] {
  20626. svr.stop();
  20627. t.join();
  20628. ASSERT_FALSE(svr.is_running());
  20629. });
  20630. svr.wait_until_ready();
  20631. Client cli(HOST, port);
  20632. auto res = cli.Post(
  20633. "/echo",
  20634. [](size_t /*offset*/, DataSink &sink) {
  20635. sink.write("hello", 5);
  20636. sink.done();
  20637. return true;
  20638. },
  20639. "text/plain");
  20640. ASSERT_TRUE(res);
  20641. EXPECT_EQ(StatusCode::OK_200, res->status);
  20642. EXPECT_EQ("hello", res->body);
  20643. }
  20644. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20645. TEST_F(OpenStreamTest, Gzip) {
  20646. Client cli("127.0.0.1", port_);
  20647. auto handle = cli.open_stream("GET", "/compressible", {},
  20648. {{"Accept-Encoding", "gzip"}});
  20649. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20650. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20651. }
  20652. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20653. Client cli("127.0.0.1", port_);
  20654. auto handle =
  20655. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20656. {{"Accept-Encoding", "gzip"}});
  20657. ASSERT_TRUE(handle.is_valid());
  20658. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20659. EXPECT_EQ("123456789", read_all(handle));
  20660. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20661. }
  20662. #endif
  20663. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20664. TEST_F(OpenStreamTest, Brotli) {
  20665. Client cli("127.0.0.1", port_);
  20666. auto handle =
  20667. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20668. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20669. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20670. }
  20671. #endif
  20672. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20673. TEST_F(OpenStreamTest, Zstd) {
  20674. Client cli("127.0.0.1", port_);
  20675. auto handle = cli.open_stream("GET", "/compressible", {},
  20676. {{"Accept-Encoding", "zstd"}});
  20677. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20678. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20679. }
  20680. #endif
  20681. #ifdef CPPHTTPLIB_SSL_ENABLED
  20682. class SSLOpenStreamTest : public ::testing::Test {
  20683. protected:
  20684. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20685. void SetUp() override {
  20686. svr_.Get("/hello", [](const Request &, Response &res) {
  20687. res.set_content("Hello SSL World!", "text/plain");
  20688. });
  20689. svr_.Get("/chunked", [](const Request &, Response &res) {
  20690. res.set_chunked_content_provider("text/plain",
  20691. [](size_t offset, DataSink &sink) {
  20692. if (offset < 15) {
  20693. sink.write("chunk", 5);
  20694. return true;
  20695. }
  20696. sink.done();
  20697. return true;
  20698. });
  20699. });
  20700. svr_.Post("/echo", [](const Request &req, Response &res) {
  20701. res.set_content(req.body, req.get_header_value("Content-Type"));
  20702. });
  20703. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20704. std::string body = req.body;
  20705. res.set_chunked_content_provider(
  20706. "text/plain", [body](size_t offset, DataSink &sink) {
  20707. if (offset < body.size()) {
  20708. sink.write(body.data() + offset, body.size() - offset);
  20709. }
  20710. sink.done();
  20711. return true;
  20712. });
  20713. });
  20714. port_ = svr_.bind_to_any_port("127.0.0.1");
  20715. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20716. svr_.wait_until_ready();
  20717. }
  20718. void TearDown() override {
  20719. svr_.stop();
  20720. if (thread_.joinable()) thread_.join();
  20721. }
  20722. SSLServer svr_;
  20723. std::thread thread_;
  20724. int port_ = 0;
  20725. };
  20726. TEST_F(SSLOpenStreamTest, Basic) {
  20727. SSLClient cli("127.0.0.1", port_);
  20728. cli.enable_server_certificate_verification(false);
  20729. auto handle = cli.open_stream("GET", "/hello");
  20730. ASSERT_TRUE(handle.is_valid());
  20731. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20732. }
  20733. TEST_F(SSLOpenStreamTest, Chunked) {
  20734. SSLClient cli("127.0.0.1", port_);
  20735. cli.enable_server_certificate_verification(false);
  20736. auto handle = cli.open_stream("GET", "/chunked");
  20737. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20738. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20739. "Transfer-Encoding") == "chunked");
  20740. auto body = read_all(handle);
  20741. EXPECT_EQ("chunkchunkchunk", body);
  20742. }
  20743. TEST_F(SSLOpenStreamTest, Post) {
  20744. SSLClient cli("127.0.0.1", port_);
  20745. cli.enable_server_certificate_verification(false);
  20746. auto handle =
  20747. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20748. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20749. EXPECT_EQ(200, handle.response->status);
  20750. auto body = read_all(handle);
  20751. EXPECT_EQ("Hello SSL POST", body);
  20752. }
  20753. TEST_F(SSLOpenStreamTest, PostChunked) {
  20754. SSLClient cli("127.0.0.1", port_);
  20755. cli.enable_server_certificate_verification(false);
  20756. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20757. "Chunked SSL Data", "text/plain");
  20758. ASSERT_TRUE(handle.is_valid());
  20759. EXPECT_EQ(200, handle.response->status);
  20760. auto body = read_all(handle);
  20761. EXPECT_EQ("Chunked SSL Data", body);
  20762. }
  20763. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20764. // Content-Length is terminated by the server closing the connection. When the
  20765. // SSL peer sends a close_notify after the body, the client must treat it as a
  20766. // clean EOF and return a successful response rather than an error.
  20767. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20769. ASSERT_TRUE(svr.is_valid());
  20770. svr.set_keep_alive_max_count(1);
  20771. const std::string expected_body = "Hello from connection-close response!";
  20772. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20773. res.set_content_provider("text/plain",
  20774. [&](size_t offset, DataSink &sink) -> bool {
  20775. if (offset < expected_body.size()) {
  20776. sink.write(expected_body.data() + offset,
  20777. expected_body.size() - offset);
  20778. }
  20779. sink.done();
  20780. return true;
  20781. });
  20782. });
  20783. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20784. auto se = detail::scope_exit([&] {
  20785. svr.stop();
  20786. listen_thread.join();
  20787. ASSERT_FALSE(svr.is_running());
  20788. });
  20789. svr.wait_until_ready();
  20790. SSLClient cli(HOST, PORT);
  20791. cli.enable_server_certificate_verification(false);
  20792. auto res = cli.Get("/no-content-length");
  20793. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20794. EXPECT_EQ(StatusCode::OK_200, res->status);
  20795. EXPECT_EQ(expected_body, res->body);
  20796. }
  20797. #endif // CPPHTTPLIB_SSL_ENABLED
  20798. //==============================================================================
  20799. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20800. // results for various scenarios.
  20801. //==============================================================================
  20802. TEST(ParityTest, GetVsOpenStream) {
  20803. Server svr;
  20804. const std::string path = "/parity";
  20805. const std::string content = "Parity test content: hello world";
  20806. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20807. res.set_content(content, "text/plain");
  20808. });
  20809. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20810. auto se = detail::scope_exit([&] {
  20811. svr.stop();
  20812. t.join();
  20813. ASSERT_FALSE(svr.is_running());
  20814. });
  20815. svr.wait_until_ready();
  20816. Client cli(HOST, PORT);
  20817. // Non-stream path
  20818. auto r1 = cli.Get(path);
  20819. ASSERT_TRUE(r1);
  20820. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20821. // Stream path
  20822. auto h = cli.open_stream("GET", path);
  20823. ASSERT_TRUE(h.is_valid());
  20824. EXPECT_EQ(r1->body, read_all(h));
  20825. }
  20826. // Helper to compress data with provided compressor type T
  20827. template <typename Compressor>
  20828. static std::string compress_payload_for_parity(const std::string &in) {
  20829. std::string out;
  20830. Compressor compressor;
  20831. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20832. [&](const char *data, size_t n) {
  20833. out.append(data, n);
  20834. return true;
  20835. });
  20836. EXPECT_TRUE(ok);
  20837. return out;
  20838. }
  20839. // Helper function for compression parity tests
  20840. template <typename Compressor>
  20841. static void test_compression_parity(const std::string &original,
  20842. const std::string &path,
  20843. const std::string &encoding) {
  20844. const std::string compressed =
  20845. compress_payload_for_parity<Compressor>(original);
  20846. Server svr;
  20847. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20848. res.set_content(compressed, "application/octet-stream");
  20849. res.set_header("Content-Encoding", encoding);
  20850. });
  20851. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20852. auto se = detail::scope_exit([&] {
  20853. svr.stop();
  20854. t.join();
  20855. ASSERT_FALSE(svr.is_running());
  20856. });
  20857. svr.wait_until_ready();
  20858. Client cli(HOST, PORT);
  20859. // Non-streaming
  20860. {
  20861. auto res = cli.Get(path);
  20862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20863. EXPECT_EQ(StatusCode::OK_200, res->status);
  20864. EXPECT_EQ(original, res->body);
  20865. }
  20866. // Streaming
  20867. {
  20868. auto h = cli.open_stream("GET", path);
  20869. ASSERT_TRUE(h.is_valid());
  20870. EXPECT_EQ(original, read_all(h));
  20871. }
  20872. }
  20873. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20874. TEST(ParityTest, Gzip) {
  20875. test_compression_parity<detail::gzip_compressor>(
  20876. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20877. }
  20878. #endif
  20879. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20880. TEST(ParityTest, Brotli) {
  20881. test_compression_parity<detail::brotli_compressor>(
  20882. "Hello, brotli parity test payload", "/parity-br", "br");
  20883. }
  20884. #endif
  20885. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20886. TEST(ParityTest, Zstd) {
  20887. test_compression_parity<detail::zstd_compressor>(
  20888. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20889. }
  20890. #endif
  20891. //==============================================================================
  20892. // New Stream API Tests
  20893. //==============================================================================
  20894. inline std::string read_body(httplib::stream::Result &result) {
  20895. std::string body;
  20896. while (result.next()) {
  20897. body.append(result.data(), result.size());
  20898. }
  20899. return body;
  20900. }
  20901. TEST(ClientConnectionTest, Basic) {
  20902. httplib::ClientConnection conn;
  20903. EXPECT_FALSE(conn.is_open());
  20904. conn.sock = 1;
  20905. EXPECT_TRUE(conn.is_open());
  20906. httplib::ClientConnection conn2(std::move(conn));
  20907. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20908. conn2.sock = INVALID_SOCKET;
  20909. }
  20910. // Unified test server for all stream::* tests
  20911. class StreamApiTest : public ::testing::Test {
  20912. protected:
  20913. void SetUp() override {
  20914. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20915. res.set_content("Hello World!", "text/plain");
  20916. });
  20917. svr_.Get("/echo-params",
  20918. [](const httplib::Request &req, httplib::Response &res) {
  20919. std::string r;
  20920. for (const auto &p : req.params) {
  20921. if (!r.empty()) r += "&";
  20922. r += p.first + "=" + p.second;
  20923. }
  20924. res.set_content(r, "text/plain");
  20925. });
  20926. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20927. res.set_content(req.body, req.get_header_value("Content-Type"));
  20928. });
  20929. svr_.Post("/echo-headers",
  20930. [](const httplib::Request &req, httplib::Response &res) {
  20931. std::string r;
  20932. for (const auto &h : req.headers)
  20933. r += h.first + ": " + h.second + "\n";
  20934. res.set_content(r, "text/plain");
  20935. });
  20936. svr_.Post("/echo-params",
  20937. [](const httplib::Request &req, httplib::Response &res) {
  20938. std::string r = "params:";
  20939. for (const auto &p : req.params)
  20940. r += p.first + "=" + p.second + ";";
  20941. res.set_content(r + " body:" + req.body, "text/plain");
  20942. });
  20943. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20944. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20945. });
  20946. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20947. res.set_content("PUT:" + req.body, "text/plain");
  20948. });
  20949. svr_.Patch("/echo",
  20950. [](const httplib::Request &req, httplib::Response &res) {
  20951. res.set_content("PATCH:" + req.body, "text/plain");
  20952. });
  20953. svr_.Delete(
  20954. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20955. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20956. "text/plain");
  20957. });
  20958. svr_.Get("/head-test",
  20959. [](const httplib::Request &, httplib::Response &res) {
  20960. res.set_content("body for HEAD", "text/plain");
  20961. });
  20962. svr_.Options("/options",
  20963. [](const httplib::Request &, httplib::Response &res) {
  20964. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20965. });
  20966. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20967. svr_.wait_until_ready();
  20968. }
  20969. void TearDown() override {
  20970. svr_.stop();
  20971. if (thread_.joinable()) thread_.join();
  20972. }
  20973. httplib::Server svr_;
  20974. std::thread thread_;
  20975. };
  20976. // stream::Get tests
  20977. TEST_F(StreamApiTest, GetBasic) {
  20978. httplib::Client cli(HOST, PORT);
  20979. auto result = httplib::stream::Get(cli, "/hello");
  20980. ASSERT_TRUE(result.is_valid());
  20981. EXPECT_EQ(200, result.status());
  20982. EXPECT_EQ("Hello World!", read_body(result));
  20983. }
  20984. TEST_F(StreamApiTest, GetWithParams) {
  20985. httplib::Client cli(HOST, PORT);
  20986. httplib::Params params{{"foo", "bar"}};
  20987. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20988. ASSERT_TRUE(result.is_valid());
  20989. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20990. }
  20991. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20992. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20993. httplib::Client cli(HOST, PORT);
  20994. cli.set_payload_max_length(0);
  20995. auto result = httplib::stream::Get(cli, "/hello");
  20996. ASSERT_TRUE(result.is_valid());
  20997. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20998. EXPECT_EQ("Hello World!", read_body(result));
  20999. }
  21000. #endif
  21001. TEST_F(StreamApiTest, GetConnectionError) {
  21002. httplib::Client cli(HOST, 9999);
  21003. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21004. }
  21005. TEST_F(StreamApiTest, Get404) {
  21006. httplib::Client cli(HOST, PORT);
  21007. auto result = httplib::stream::Get(cli, "/nonexistent");
  21008. EXPECT_TRUE(result.is_valid());
  21009. EXPECT_EQ(404, result.status());
  21010. }
  21011. // stream::Post tests
  21012. TEST_F(StreamApiTest, PostBasic) {
  21013. httplib::Client cli(HOST, PORT);
  21014. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21015. "application/json");
  21016. ASSERT_TRUE(result.is_valid());
  21017. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21018. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21019. }
  21020. TEST_F(StreamApiTest, PostWithHeaders) {
  21021. httplib::Client cli(HOST, PORT);
  21022. httplib::Headers headers{{"X-Custom", "value"}};
  21023. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21024. "text/plain");
  21025. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21026. }
  21027. TEST_F(StreamApiTest, PostWithParams) {
  21028. httplib::Client cli(HOST, PORT);
  21029. httplib::Params params{{"k", "v"}};
  21030. auto result =
  21031. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21032. auto body = read_body(result);
  21033. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21034. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21035. }
  21036. TEST_F(StreamApiTest, PostLarge) {
  21037. httplib::Client cli(HOST, PORT);
  21038. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21039. size_t total = 0;
  21040. while (result.next()) {
  21041. total += result.size();
  21042. }
  21043. EXPECT_EQ(100u * 1024u, total);
  21044. }
  21045. // stream::Put/Patch tests
  21046. TEST_F(StreamApiTest, PutAndPatch) {
  21047. httplib::Client cli(HOST, PORT);
  21048. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21049. EXPECT_EQ("PUT:test", read_body(put));
  21050. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21051. EXPECT_EQ("PATCH:test", read_body(patch));
  21052. }
  21053. // stream::Delete tests
  21054. TEST_F(StreamApiTest, Delete) {
  21055. httplib::Client cli(HOST, PORT);
  21056. auto del1 = httplib::stream::Delete(cli, "/resource");
  21057. EXPECT_EQ("Deleted", read_body(del1));
  21058. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21059. EXPECT_EQ("Deleted:data", read_body(del2));
  21060. }
  21061. // stream::Head/Options tests
  21062. TEST_F(StreamApiTest, HeadAndOptions) {
  21063. httplib::Client cli(HOST, PORT);
  21064. auto head = httplib::stream::Head(cli, "/head-test");
  21065. EXPECT_TRUE(head.is_valid());
  21066. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21067. auto opts = httplib::stream::Options(cli, "/options");
  21068. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21069. }
  21070. // SSL stream::* tests
  21071. #ifdef CPPHTTPLIB_SSL_ENABLED
  21072. class SSLStreamApiTest : public ::testing::Test {
  21073. protected:
  21074. void SetUp() override {
  21075. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21076. res.set_content("Hello SSL!", "text/plain");
  21077. });
  21078. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21079. res.set_content(req.body, "text/plain");
  21080. });
  21081. port_ = svr_.bind_to_any_port("127.0.0.1");
  21082. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21083. svr_.wait_until_ready();
  21084. }
  21085. void TearDown() override {
  21086. svr_.stop();
  21087. if (thread_.joinable()) thread_.join();
  21088. }
  21089. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21090. std::thread thread_;
  21091. int port_ = 0;
  21092. };
  21093. TEST_F(SSLStreamApiTest, GetAndPost) {
  21094. httplib::SSLClient cli("127.0.0.1", port_);
  21095. cli.enable_server_certificate_verification(false);
  21096. auto get = httplib::stream::Get(cli, "/hello");
  21097. EXPECT_EQ("Hello SSL!", read_body(get));
  21098. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21099. EXPECT_EQ("test", read_body(post));
  21100. }
  21101. #endif
  21102. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21103. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21104. // BodyReader
  21105. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21106. // Test that read timeout during streaming is detected
  21107. // Use a large content-length response where server delays mid-stream
  21108. Server svr;
  21109. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21110. // Send a large response with delay in the middle
  21111. res.set_content_provider(
  21112. 1000, // content_length
  21113. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21114. if (offset < 100) {
  21115. // Send first 100 bytes immediately
  21116. std::string data(100, 'A');
  21117. sink.write(data.c_str(), data.size());
  21118. return true;
  21119. }
  21120. // Then delay longer than client timeout
  21121. std::this_thread::sleep_for(std::chrono::seconds(3));
  21122. std::string data(900, 'B');
  21123. sink.write(data.c_str(), data.size());
  21124. return true;
  21125. });
  21126. });
  21127. auto port = 8091;
  21128. std::thread t([&]() { svr.listen("localhost", port); });
  21129. svr.wait_until_ready();
  21130. Client cli("localhost", port);
  21131. cli.set_read_timeout(1, 0); // 1 second timeout
  21132. auto handle = cli.open_stream("GET", "/slow-stream");
  21133. ASSERT_TRUE(handle.is_valid());
  21134. char buf[256];
  21135. ssize_t total = 0;
  21136. ssize_t n;
  21137. bool got_error = false;
  21138. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21139. total += n;
  21140. }
  21141. if (n < 0) {
  21142. got_error = true;
  21143. // Should be timeout or read error
  21144. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21145. handle.get_read_error() == Error::Read)
  21146. << "Actual error: " << to_string(handle.get_read_error());
  21147. }
  21148. // Either we got an error, or we got less data than expected
  21149. EXPECT_TRUE(got_error || total < 1000)
  21150. << "Expected timeout but got all " << total << " bytes";
  21151. svr.stop();
  21152. t.join();
  21153. }
  21154. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21155. // Test connection closed detection via BodyReader
  21156. Server svr;
  21157. std::atomic<bool> close_now{false};
  21158. svr.Get("/will-close", [&](const Request &, Response &res) {
  21159. res.set_content_provider(
  21160. 10000, // Large content_length that we won't fully send
  21161. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21162. if (offset < 100) {
  21163. std::string data(100, 'X');
  21164. sink.write(data.c_str(), data.size());
  21165. return true;
  21166. }
  21167. // Wait for signal then abort
  21168. while (!close_now) {
  21169. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21170. }
  21171. return false; // Abort - server will close connection
  21172. });
  21173. });
  21174. auto port = 8092;
  21175. std::thread t([&]() { svr.listen("localhost", port); });
  21176. svr.wait_until_ready();
  21177. Client cli("localhost", port);
  21178. auto handle = cli.open_stream("GET", "/will-close");
  21179. ASSERT_TRUE(handle.is_valid());
  21180. char buf[256];
  21181. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21182. EXPECT_GT(n, 0) << "First read should succeed";
  21183. // Signal server to close
  21184. close_now = true;
  21185. // Keep reading until error or EOF
  21186. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21187. // Keep reading
  21188. }
  21189. // Should get an error since content_length wasn't satisfied
  21190. if (n < 0) {
  21191. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21192. handle.get_read_error() == Error::Read)
  21193. << "Actual error: " << to_string(handle.get_read_error());
  21194. }
  21195. svr.stop();
  21196. t.join();
  21197. }
  21198. #ifdef CPPHTTPLIB_SSL_ENABLED
  21199. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21200. // Test that read timeout during SSL streaming is detected
  21201. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21202. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21203. res.set_content_provider(
  21204. 1000, "text/plain",
  21205. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21206. if (offset < 100) {
  21207. std::string data(100, 'A');
  21208. sink.write(data.c_str(), data.size());
  21209. return true;
  21210. }
  21211. std::this_thread::sleep_for(std::chrono::seconds(3));
  21212. std::string data(900, 'B');
  21213. sink.write(data.c_str(), data.size());
  21214. return true;
  21215. });
  21216. });
  21217. auto port = 8093;
  21218. std::thread t([&]() { svr.listen("localhost", port); });
  21219. svr.wait_until_ready();
  21220. SSLClient cli("localhost", port);
  21221. cli.enable_server_certificate_verification(false);
  21222. cli.set_read_timeout(1, 0); // 1 second timeout
  21223. auto handle = cli.open_stream("GET", "/slow-stream");
  21224. ASSERT_TRUE(handle.is_valid());
  21225. char buf[256];
  21226. ssize_t total = 0;
  21227. ssize_t n;
  21228. bool got_error = false;
  21229. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21230. total += n;
  21231. }
  21232. if (n < 0) {
  21233. got_error = true;
  21234. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21235. handle.get_read_error() == Error::Read)
  21236. << "Actual error: " << to_string(handle.get_read_error());
  21237. }
  21238. EXPECT_TRUE(got_error || total < 1000)
  21239. << "Expected timeout but got all " << total << " bytes";
  21240. svr.stop();
  21241. t.join();
  21242. }
  21243. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21244. // Test SSL connection closed detection
  21245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21246. std::atomic<bool> close_now{false};
  21247. svr.Get("/will-close", [&](const Request &, Response &res) {
  21248. res.set_content_provider(
  21249. 10000, "text/plain",
  21250. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21251. if (offset < 100) {
  21252. std::string data(100, 'X');
  21253. sink.write(data.c_str(), data.size());
  21254. return true;
  21255. }
  21256. while (!close_now) {
  21257. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21258. }
  21259. return false;
  21260. });
  21261. });
  21262. auto port = 8094;
  21263. std::thread t([&]() { svr.listen("localhost", port); });
  21264. svr.wait_until_ready();
  21265. SSLClient cli("localhost", port);
  21266. cli.enable_server_certificate_verification(false);
  21267. auto handle = cli.open_stream("GET", "/will-close");
  21268. ASSERT_TRUE(handle.is_valid());
  21269. char buf[256];
  21270. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21271. EXPECT_GT(n, 0);
  21272. // Signal server to close
  21273. close_now = true;
  21274. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21275. // Keep reading
  21276. }
  21277. if (n < 0) {
  21278. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21279. handle.get_read_error() == Error::Read)
  21280. << "Actual error: " << to_string(handle.get_read_error());
  21281. }
  21282. svr.stop();
  21283. t.join();
  21284. }
  21285. #endif
  21286. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21287. using namespace httplib;
  21288. // Create a test file
  21289. const char *fname = "etag_testfile.txt";
  21290. const char *content = "etag-content";
  21291. {
  21292. std::ofstream ofs(fname);
  21293. ofs << content;
  21294. ASSERT_TRUE(ofs.good());
  21295. }
  21296. Server svr;
  21297. svr.set_mount_point("/static", ".");
  21298. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21299. svr.wait_until_ready();
  21300. Client cli(HOST, PORT);
  21301. // First request: should get 200 with ETag header
  21302. auto res1 = cli.Get("/static/etag_testfile.txt");
  21303. ASSERT_TRUE(res1);
  21304. ASSERT_EQ(200, res1->status);
  21305. ASSERT_TRUE(res1->has_header("ETag"));
  21306. std::string etag = res1->get_header_value("ETag");
  21307. EXPECT_FALSE(etag.empty());
  21308. // Verify ETag format: W/"hex-hex"
  21309. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21310. EXPECT_EQ('W', etag[0]);
  21311. EXPECT_EQ('/', etag[1]);
  21312. EXPECT_EQ('"', etag[2]);
  21313. EXPECT_EQ('"', etag.back());
  21314. // Exact match: expect 304 Not Modified
  21315. Headers h2 = {{"If-None-Match", etag}};
  21316. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21317. ASSERT_TRUE(res2);
  21318. EXPECT_EQ(304, res2->status);
  21319. // Wildcard match: expect 304 Not Modified
  21320. Headers h3 = {{"If-None-Match", "*"}};
  21321. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21322. ASSERT_TRUE(res3);
  21323. EXPECT_EQ(304, res3->status);
  21324. // Non-matching ETag: expect 200
  21325. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21326. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21327. ASSERT_TRUE(res4);
  21328. EXPECT_EQ(200, res4->status);
  21329. // Multiple ETags with one matching: expect 304
  21330. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21331. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21332. ASSERT_TRUE(res5);
  21333. EXPECT_EQ(304, res5->status);
  21334. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21335. // that equivalent to the single comma-separated list above, so the match on
  21336. // the second line must still be found.
  21337. Headers h6;
  21338. h6.emplace("If-None-Match", "W/\"other\"");
  21339. h6.emplace("If-None-Match", etag);
  21340. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21341. ASSERT_TRUE(res6);
  21342. EXPECT_EQ(304, res6->status);
  21343. svr.stop();
  21344. t.join();
  21345. std::remove(fname);
  21346. }
  21347. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21348. using namespace httplib;
  21349. Server svr;
  21350. svr.set_mount_point("/static", ".");
  21351. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21352. svr.wait_until_ready();
  21353. Client cli(HOST, PORT);
  21354. // Send If-None-Match: * to a non-existent file
  21355. Headers h = {{"If-None-Match", "*"}};
  21356. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21358. EXPECT_EQ(404, res->status);
  21359. svr.stop();
  21360. t.join();
  21361. }
  21362. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21363. using namespace httplib;
  21364. // Create a test file
  21365. const char *fname = "etag_boundary_testfile.txt";
  21366. const char *content = "boundary-test";
  21367. {
  21368. std::ofstream ofs(fname);
  21369. ofs << content;
  21370. ASSERT_TRUE(ofs.good());
  21371. }
  21372. Server svr;
  21373. svr.set_mount_point("/static", ".");
  21374. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21375. svr.wait_until_ready();
  21376. Client cli(HOST, PORT);
  21377. // Get the actual ETag
  21378. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21379. ASSERT_TRUE(res1);
  21380. ASSERT_EQ(200, res1->status);
  21381. ASSERT_TRUE(res1->has_header("ETag"));
  21382. std::string etag = res1->get_header_value("ETag");
  21383. // Test 1: Very long ETag value (longer than actual ETag)
  21384. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21385. Headers h1 = {{"If-None-Match", "W/"
  21386. "\"very-long-etag-value-that-is-much-longer-"
  21387. "than-the-actual-etag-value\""}};
  21388. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21389. ASSERT_TRUE(res2);
  21390. EXPECT_EQ(200, res2->status); // Should not match
  21391. // Test 2: Long string followed by wildcard
  21392. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21393. // string)
  21394. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21395. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21396. ASSERT_TRUE(res3);
  21397. EXPECT_EQ(304, res3->status); // Should match on "*"
  21398. // Test 3: Wildcard followed by long string
  21399. // Should match on "*" immediately and return 304
  21400. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21401. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21402. ASSERT_TRUE(res4);
  21403. EXPECT_EQ(304, res4->status); // Should match on "*"
  21404. // Test 4: Multiple long non-matching values
  21405. // Should NOT match and return 200 (test that all comparisons are safe)
  21406. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21407. "W/\"second-long-non-matching-value\", "
  21408. "W/\"third-long-non-matching-value\""}};
  21409. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21410. ASSERT_TRUE(res5);
  21411. EXPECT_EQ(200, res5->status); // Should not match
  21412. // Test 5: Single character that is not "*" (edge case)
  21413. Headers h5 = {{"If-None-Match", "X"}};
  21414. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21415. ASSERT_TRUE(res6);
  21416. EXPECT_EQ(200, res6->status); // Should not match
  21417. svr.stop();
  21418. t.join();
  21419. std::remove(fname);
  21420. }
  21421. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21422. using namespace httplib;
  21423. // Create a test file
  21424. const char *fname = "ims_testfile.txt";
  21425. const char *content = "if-modified-since-test";
  21426. {
  21427. std::ofstream ofs(fname);
  21428. ofs << content;
  21429. ASSERT_TRUE(ofs.good());
  21430. }
  21431. Server svr;
  21432. svr.set_mount_point("/static", ".");
  21433. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21434. svr.wait_until_ready();
  21435. Client cli(HOST, PORT);
  21436. // First request: should get 200 with Last-Modified header
  21437. auto res1 = cli.Get("/static/ims_testfile.txt");
  21438. ASSERT_TRUE(res1);
  21439. ASSERT_EQ(200, res1->status);
  21440. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21441. std::string last_modified = res1->get_header_value("Last-Modified");
  21442. EXPECT_FALSE(last_modified.empty());
  21443. // If-Modified-Since with same time: expect 304
  21444. Headers h2 = {{"If-Modified-Since", last_modified}};
  21445. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21446. ASSERT_TRUE(res2);
  21447. EXPECT_EQ(304, res2->status);
  21448. // If-Modified-Since with future time: expect 304
  21449. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21450. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21451. ASSERT_TRUE(res3);
  21452. EXPECT_EQ(304, res3->status);
  21453. // If-Modified-Since with past time: expect 200
  21454. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21455. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21456. ASSERT_TRUE(res4);
  21457. EXPECT_EQ(200, res4->status);
  21458. // If-None-Match takes precedence over If-Modified-Since
  21459. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21460. ASSERT_TRUE(res1->has_header("ETag"));
  21461. std::string etag = res1->get_header_value("ETag");
  21462. Headers h5 = {{"If-None-Match", etag},
  21463. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21464. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21465. ASSERT_TRUE(res5);
  21466. EXPECT_EQ(304, res5->status);
  21467. svr.stop();
  21468. t.join();
  21469. std::remove(fname);
  21470. }
  21471. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21472. using namespace httplib;
  21473. Server svr;
  21474. // Endpoint that returns compressible content
  21475. svr.Get("/compressible", [](const Request &, Response &res) {
  21476. // Return a large enough body to trigger compression
  21477. std::string body(1000, 'a');
  21478. res.set_content(body, "text/plain");
  21479. });
  21480. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21481. svr.wait_until_ready();
  21482. Client cli(HOST, PORT);
  21483. // Request with gzip support: should get Vary header when compressed
  21484. cli.set_compress(true);
  21485. auto res1 = cli.Get("/compressible");
  21486. ASSERT_TRUE(res1);
  21487. EXPECT_EQ(200, res1->status);
  21488. // If Content-Encoding is set, Vary should also be set
  21489. if (res1->has_header("Content-Encoding")) {
  21490. EXPECT_TRUE(res1->has_header("Vary"));
  21491. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21492. }
  21493. // Request without Accept-Encoding header: should not have compression
  21494. Headers h_no_compress;
  21495. auto res2 = cli.Get("/compressible", h_no_compress);
  21496. ASSERT_TRUE(res2);
  21497. EXPECT_EQ(200, res2->status);
  21498. // Verify Vary header is present when compression is applied
  21499. // (the exact behavior depends on server configuration)
  21500. svr.stop();
  21501. t.join();
  21502. }
  21503. TEST(ETagTest, IfRangeWithETag) {
  21504. using namespace httplib;
  21505. // Create a test file with known content
  21506. const char *fname = "if_range_testfile.txt";
  21507. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21508. {
  21509. std::ofstream ofs(fname);
  21510. ofs << content;
  21511. ASSERT_TRUE(ofs.good());
  21512. }
  21513. Server svr;
  21514. svr.set_mount_point("/static", ".");
  21515. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21516. svr.wait_until_ready();
  21517. Client cli(HOST, PORT);
  21518. // First request: get ETag
  21519. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21520. ASSERT_TRUE(res1);
  21521. ASSERT_EQ(200, res1->status);
  21522. ASSERT_TRUE(res1->has_header("ETag"));
  21523. std::string etag = res1->get_header_value("ETag");
  21524. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21525. // Since our server generates weak ETags (W/"..."), If-Range with our
  21526. // ETag should NOT result in partial content - it should return full content.
  21527. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21528. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21529. ASSERT_TRUE(res2);
  21530. // Weak ETag in If-Range -> full content (200), not partial (206)
  21531. EXPECT_EQ(200, res2->status);
  21532. EXPECT_EQ(content, res2->body);
  21533. EXPECT_FALSE(res2->has_header("Content-Range"));
  21534. // Range request with non-matching If-Range (ETag): should get 200 (full
  21535. // content)
  21536. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21537. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21538. ASSERT_TRUE(res3);
  21539. EXPECT_EQ(200, res3->status);
  21540. EXPECT_EQ(content, res3->body);
  21541. EXPECT_FALSE(res3->has_header("Content-Range"));
  21542. // Range request with strong ETag (hypothetical - our server doesn't generate
  21543. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21544. // should return full content)
  21545. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21546. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21547. ASSERT_TRUE(res4);
  21548. EXPECT_EQ(200, res4->status);
  21549. EXPECT_EQ(content, res4->body);
  21550. EXPECT_FALSE(res4->has_header("Content-Range"));
  21551. svr.stop();
  21552. t.join();
  21553. std::remove(fname);
  21554. }
  21555. TEST(ETagTest, IfRangeWithDate) {
  21556. using namespace httplib;
  21557. // Create a test file
  21558. const char *fname = "if_range_date_testfile.txt";
  21559. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21560. {
  21561. std::ofstream ofs(fname);
  21562. ofs << content;
  21563. ASSERT_TRUE(ofs.good());
  21564. }
  21565. Server svr;
  21566. svr.set_mount_point("/static", ".");
  21567. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21568. svr.wait_until_ready();
  21569. Client cli(HOST, PORT);
  21570. // First request: get Last-Modified
  21571. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21572. ASSERT_TRUE(res1);
  21573. ASSERT_EQ(200, res1->status);
  21574. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21575. std::string last_modified = res1->get_header_value("Last-Modified");
  21576. // Range request with matching If-Range (date): should get 206
  21577. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21578. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21579. ASSERT_TRUE(res2);
  21580. EXPECT_EQ(206, res2->status);
  21581. EXPECT_EQ("FGHIJ", res2->body);
  21582. // Range request with old If-Range date: should get 200 (full content)
  21583. Headers h3 = {{"Range", "bytes=5-9"},
  21584. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21585. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21586. ASSERT_TRUE(res3);
  21587. EXPECT_EQ(200, res3->status);
  21588. EXPECT_EQ(content, res3->body);
  21589. // Range request with future If-Range date: should get 206
  21590. Headers h4 = {{"Range", "bytes=0-4"},
  21591. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21592. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21593. ASSERT_TRUE(res4);
  21594. EXPECT_EQ(206, res4->status);
  21595. EXPECT_EQ("ABCDE", res4->body);
  21596. svr.stop();
  21597. t.join();
  21598. std::remove(fname);
  21599. }
  21600. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21601. using namespace httplib;
  21602. const char *fname = "etag_malformed.txt";
  21603. const char *content = "malformed-etag";
  21604. {
  21605. std::ofstream ofs(fname);
  21606. ofs << content;
  21607. ASSERT_TRUE(ofs.good());
  21608. }
  21609. Server svr;
  21610. svr.set_mount_point("/static", ".");
  21611. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21612. svr.wait_until_ready();
  21613. Client cli(HOST, PORT);
  21614. // baseline: should get 200 and an ETag
  21615. auto res1 = cli.Get("/static/etag_malformed.txt");
  21616. ASSERT_TRUE(res1);
  21617. ASSERT_EQ(200, res1->status);
  21618. ASSERT_TRUE(res1->has_header("ETag"));
  21619. // Malformed ETag value (missing quotes) should be treated as non-matching
  21620. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21621. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21622. ASSERT_TRUE(res_bad);
  21623. EXPECT_EQ(200, res_bad->status);
  21624. // Whitespace-only header value should be considered invalid / non-matching
  21625. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21626. "Host: localhost\r\n"
  21627. "If-None-Match: \r\n"
  21628. "Connection: close\r\n"
  21629. "\r\n";
  21630. std::string out;
  21631. ASSERT_TRUE(send_request(5, raw_req, &out));
  21632. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21633. svr.stop();
  21634. t.join();
  21635. std::remove(fname);
  21636. }
  21637. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21638. using namespace httplib;
  21639. const char *fname = "ims_invalid_format.txt";
  21640. const char *content = "ims-bad-format";
  21641. {
  21642. std::ofstream ofs(fname);
  21643. ofs << content;
  21644. ASSERT_TRUE(ofs.good());
  21645. }
  21646. Server svr;
  21647. svr.set_mount_point("/static", ".");
  21648. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21649. svr.wait_until_ready();
  21650. Client cli(HOST, PORT);
  21651. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21652. ASSERT_TRUE(res1);
  21653. ASSERT_EQ(200, res1->status);
  21654. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21655. // If-Modified-Since with invalid format should not result in 304
  21656. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21657. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21658. ASSERT_TRUE(res_bad);
  21659. EXPECT_EQ(200, res_bad->status);
  21660. // If-Range with invalid date format should be treated as mismatch -> full
  21661. // content (200)
  21662. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21663. {"If-Range", "invalid-date"}};
  21664. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21665. ASSERT_TRUE(res_ifrange);
  21666. EXPECT_EQ(200, res_ifrange->status);
  21667. svr.stop();
  21668. t.join();
  21669. std::remove(fname);
  21670. }
  21671. TEST(ETagTest, IfRangeWithMalformedETag) {
  21672. using namespace httplib;
  21673. const char *fname = "ifrange_malformed.txt";
  21674. const std::string content = "0123456789";
  21675. {
  21676. std::ofstream ofs(fname);
  21677. ofs << content;
  21678. ASSERT_TRUE(ofs.good());
  21679. }
  21680. Server svr;
  21681. svr.set_mount_point("/static", ".");
  21682. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21683. svr.wait_until_ready();
  21684. Client cli(HOST, PORT);
  21685. // First request: get ETag
  21686. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21687. ASSERT_TRUE(res1);
  21688. ASSERT_EQ(200, res1->status);
  21689. ASSERT_TRUE(res1->has_header("ETag"));
  21690. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21691. // full content (200)
  21692. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21693. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21694. ASSERT_TRUE(res2);
  21695. EXPECT_EQ(200, res2->status);
  21696. EXPECT_EQ(content, res2->body);
  21697. svr.stop();
  21698. t.join();
  21699. std::remove(fname);
  21700. }
  21701. TEST(ETagTest, ExtremeLargeDateValues) {
  21702. using namespace httplib;
  21703. const char *fname = "ims_extreme_date.txt";
  21704. const char *content = "ims-extreme-date";
  21705. {
  21706. std::ofstream ofs(fname);
  21707. ofs << content;
  21708. ASSERT_TRUE(ofs.good());
  21709. }
  21710. Server svr;
  21711. svr.set_mount_point("/static", ".");
  21712. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21713. svr.wait_until_ready();
  21714. Client cli(HOST, PORT);
  21715. auto res1 = cli.Get(std::string("/static/") + fname);
  21716. ASSERT_TRUE(res1);
  21717. ASSERT_EQ(200, res1->status);
  21718. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21719. // Extremely large year that may overflow date parsing routines.
  21720. Headers h_large_date = {
  21721. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21722. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21723. ASSERT_TRUE(res_bad);
  21724. // Expect server to treat this as invalid/mismatch and return full content
  21725. EXPECT_EQ(200, res_bad->status);
  21726. // If-Range with extremely large date should be treated as mismatch -> full
  21727. // content (200)
  21728. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21729. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21730. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21731. ASSERT_TRUE(res_ifrange);
  21732. EXPECT_EQ(200, res_ifrange->status);
  21733. svr.stop();
  21734. t.join();
  21735. std::remove(fname);
  21736. }
  21737. TEST(ETagTest, NegativeFileModificationTime) {
  21738. using namespace httplib;
  21739. const char *fname = "ims_negative_mtime.txt";
  21740. const std::string content = "negative-mtime";
  21741. {
  21742. std::ofstream ofs(fname);
  21743. ofs << content;
  21744. ASSERT_TRUE(ofs.good());
  21745. }
  21746. // Try to set file mtime to a negative value. This may fail on some
  21747. // platforms/filesystems; if it fails, the test will still verify server
  21748. // behaves safely by performing a regular conditional request.
  21749. #if defined(__APPLE__) || defined(__linux__)
  21750. bool set_negative = false;
  21751. do {
  21752. struct timeval times[2];
  21753. // access time: now
  21754. times[0].tv_sec = time(nullptr);
  21755. times[0].tv_usec = 0;
  21756. // modification time: negative (e.g., -1)
  21757. times[1].tv_sec = -1;
  21758. times[1].tv_usec = 0;
  21759. if (utimes(fname, times) == 0) { set_negative = true; }
  21760. } while (0);
  21761. #else
  21762. bool set_negative = false;
  21763. #endif
  21764. Server svr;
  21765. svr.set_mount_point("/static", ".");
  21766. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21767. svr.wait_until_ready();
  21768. Client cli(HOST, PORT);
  21769. auto res1 = cli.Get(std::string("/static/") + fname);
  21770. ASSERT_TRUE(res1);
  21771. ASSERT_EQ(200, res1->status);
  21772. bool has_last_modified = res1->has_header("Last-Modified");
  21773. std::string last_modified;
  21774. if (has_last_modified) {
  21775. last_modified = res1->get_header_value("Last-Modified");
  21776. }
  21777. if (set_negative) {
  21778. // If we successfully set a negative mtime, ensure server returns a
  21779. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21780. // with an old date and ensure server handles it without crash.
  21781. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21782. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21783. ASSERT_TRUE(res2);
  21784. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21785. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21786. } else {
  21787. // Could not set negative mtime on this platform; fall back to verifying
  21788. // that normal invalid/malformed dates are treated safely (non-304).
  21789. Headers h_bad_date = {
  21790. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21791. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21792. ASSERT_TRUE(res_bad);
  21793. EXPECT_EQ(200, res_bad->status);
  21794. }
  21795. svr.stop();
  21796. t.join();
  21797. std::remove(fname);
  21798. }
  21799. //==============================================================================
  21800. // Integration Tests with Server
  21801. //==============================================================================
  21802. class SSEIntegrationTest : public ::testing::Test {
  21803. protected:
  21804. void SetUp() override {
  21805. stop_server_.store(false);
  21806. events_.clear();
  21807. server_ = httplib::detail::make_unique<Server>();
  21808. setup_server();
  21809. start_server();
  21810. }
  21811. void TearDown() override {
  21812. stop_server_.store(true);
  21813. event_cv_.notify_all();
  21814. server_->stop();
  21815. if (server_thread_.joinable()) { server_thread_.join(); }
  21816. }
  21817. void setup_server() {
  21818. // Simple SSE endpoint
  21819. server_->Get("/events", [this](const Request &req, Response &res) {
  21820. auto last_id = req.get_header_value("Last-Event-ID");
  21821. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21822. res.set_chunked_content_provider(
  21823. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21824. std::unique_lock<std::mutex> lock(event_mutex_);
  21825. if (event_cv_.wait_for(
  21826. lock, std::chrono::milliseconds(200), [this] {
  21827. return !events_.empty() || stop_server_.load();
  21828. })) {
  21829. if (stop_server_.load()) { return false; }
  21830. if (!events_.empty()) {
  21831. std::string event = events_.front();
  21832. events_.erase(events_.begin());
  21833. sink.write(event.data(), event.size());
  21834. return true;
  21835. }
  21836. }
  21837. return !stop_server_.load();
  21838. });
  21839. });
  21840. // Endpoint that returns error
  21841. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21842. res.status = 500;
  21843. res.set_content("Internal Server Error", "text/plain");
  21844. });
  21845. // Endpoint for custom event types
  21846. server_->Get("/custom-events", [](const Request &, Response &res) {
  21847. res.set_chunked_content_provider(
  21848. "text/event-stream", [](size_t offset, DataSink &sink) {
  21849. if (offset == 0) {
  21850. std::string event = "event: update\ndata: updated\n\n"
  21851. "event: delete\ndata: deleted\n\n";
  21852. sink.write(event.data(), event.size());
  21853. }
  21854. return false; // End stream after sending
  21855. });
  21856. });
  21857. }
  21858. void start_server() {
  21859. port_ = server_->bind_to_any_port(HOST);
  21860. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21861. // Wait for server to start
  21862. while (!server_->is_running()) {
  21863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21864. }
  21865. }
  21866. int get_port() const { return port_; }
  21867. void send_event(const std::string &event) {
  21868. std::lock_guard<std::mutex> lock(event_mutex_);
  21869. events_.push_back(event);
  21870. event_cv_.notify_all();
  21871. }
  21872. std::unique_ptr<Server> server_;
  21873. std::thread server_thread_;
  21874. std::mutex event_mutex_;
  21875. std::condition_variable event_cv_;
  21876. std::vector<std::string> events_;
  21877. std::atomic<bool> stop_server_{false};
  21878. std::string last_received_event_id_;
  21879. int port_ = 0;
  21880. };
  21881. //==============================================================================
  21882. // SSE Parsing Tests
  21883. //==============================================================================
  21884. class SSEParsingTest : public SSEIntegrationTest {
  21885. protected:
  21886. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21887. // A trailing sentinel event tells when the whole stream has been parsed.
  21888. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21889. auto body = stream + "event: end\ndata: end\n\n";
  21890. server_->Get("/parse", [body](const Request &, Response &res) {
  21891. res.set_content(body, "text/event-stream");
  21892. });
  21893. return collect("/parse");
  21894. }
  21895. // Runs SSEClient against path until an "end" event arrives and returns the
  21896. // messages dispatched before it
  21897. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21898. Client client(HOST, get_port());
  21899. sse::SSEClient sse(client, path);
  21900. std::mutex mutex;
  21901. std::condition_variable cv;
  21902. std::vector<sse::SSEMessage> messages;
  21903. auto done = false;
  21904. sse.on_message([&](const sse::SSEMessage &msg) {
  21905. std::lock_guard<std::mutex> lock(mutex);
  21906. // Ignore a replay from a reconnect that races with stop()
  21907. if (!done) { messages.push_back(msg); }
  21908. });
  21909. sse.on_event("end", [&](const sse::SSEMessage &) {
  21910. std::lock_guard<std::mutex> lock(mutex);
  21911. done = true;
  21912. cv.notify_all();
  21913. });
  21914. sse.set_reconnect_interval(100);
  21915. sse.start_async();
  21916. {
  21917. std::unique_lock<std::mutex> lock(mutex);
  21918. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21919. }
  21920. sse.stop();
  21921. EXPECT_TRUE(done);
  21922. return messages;
  21923. }
  21924. };
  21925. TEST_F(SSEParsingTest, SingleLineData) {
  21926. auto msgs = parse("data: hello\n\n");
  21927. ASSERT_EQ(msgs.size(), 1u);
  21928. EXPECT_EQ(msgs[0].data, "hello");
  21929. EXPECT_EQ(msgs[0].event, "message");
  21930. }
  21931. TEST_F(SSEParsingTest, MultiLineData) {
  21932. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21933. ASSERT_EQ(msgs.size(), 1u);
  21934. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21935. }
  21936. TEST_F(SSEParsingTest, CustomEventType) {
  21937. auto msgs = parse("event: update\ndata: payload\n\n");
  21938. ASSERT_EQ(msgs.size(), 1u);
  21939. EXPECT_EQ(msgs[0].event, "update");
  21940. EXPECT_EQ(msgs[0].data, "payload");
  21941. }
  21942. TEST_F(SSEParsingTest, EventIdHandling) {
  21943. auto msgs = parse("id: 12345\ndata: test\n\n");
  21944. ASSERT_EQ(msgs.size(), 1u);
  21945. EXPECT_EQ(msgs[0].id, "12345");
  21946. }
  21947. TEST_F(SSEParsingTest, EmptyEventId) {
  21948. auto msgs = parse("id:\ndata: test\n\n");
  21949. ASSERT_EQ(msgs.size(), 1u);
  21950. EXPECT_EQ(msgs[0].id, "");
  21951. }
  21952. TEST_F(SSEParsingTest, CommentsIgnored) {
  21953. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21954. ASSERT_EQ(msgs.size(), 1u);
  21955. EXPECT_EQ(msgs[0].data, "hello");
  21956. EXPECT_EQ(msgs[0].event, "message");
  21957. }
  21958. TEST_F(SSEParsingTest, ColonInValue) {
  21959. auto msgs = parse("data: hello:world:test\n\n");
  21960. ASSERT_EQ(msgs.size(), 1u);
  21961. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21962. }
  21963. TEST_F(SSEParsingTest, FieldNameOnly) {
  21964. // A line without a colon is a field name with an empty value
  21965. auto msgs = parse("data\n\n");
  21966. ASSERT_EQ(msgs.size(), 1u);
  21967. EXPECT_EQ(msgs[0].data, "");
  21968. }
  21969. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21970. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21971. ASSERT_EQ(msgs.size(), 1u);
  21972. EXPECT_EQ(msgs[0].event, "update");
  21973. EXPECT_EQ(msgs[0].data, "hello");
  21974. }
  21975. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21976. auto msgs = parse("data\r\n\r\n");
  21977. ASSERT_EQ(msgs.size(), 1u);
  21978. EXPECT_EQ(msgs[0].data, "");
  21979. }
  21980. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21981. auto msgs = parse("event: update\rdata: hello\r\r");
  21982. ASSERT_EQ(msgs.size(), 1u);
  21983. EXPECT_EQ(msgs[0].event, "update");
  21984. EXPECT_EQ(msgs[0].data, "hello");
  21985. }
  21986. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21987. // Chunk boundaries fall inside every \r\n and right before the first one
  21988. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21989. "\n\r", "\nevent: end\ndata: end\n\n"};
  21990. server_->Get("/split", [chunks](const Request &, Response &res) {
  21991. auto i = std::make_shared<size_t>(0);
  21992. res.set_chunked_content_provider(
  21993. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21994. if (*i == chunks.size()) {
  21995. sink.done();
  21996. } else {
  21997. sink.write(chunks[*i].data(), chunks[*i].size());
  21998. (*i)++;
  21999. }
  22000. return true;
  22001. });
  22002. });
  22003. auto msgs = collect("/split");
  22004. ASSERT_EQ(msgs.size(), 1u);
  22005. EXPECT_EQ(msgs[0].event, "update");
  22006. EXPECT_EQ(msgs[0].data, "hello");
  22007. }
  22008. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22009. // Only a BOM at the start of the stream is ignored
  22010. auto msgs = parse("\xEF\xBB\xBF"
  22011. "data: first\n\n"
  22012. "\xEF\xBB\xBF"
  22013. "data: second\n\n");
  22014. ASSERT_EQ(msgs.size(), 1u);
  22015. EXPECT_EQ(msgs[0].data, "first");
  22016. }
  22017. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22018. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22019. ASSERT_EQ(msgs.size(), 1u);
  22020. EXPECT_EQ(msgs[0].data, "hello");
  22021. EXPECT_EQ(msgs[0].event, "message");
  22022. }
  22023. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22024. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22025. ASSERT_EQ(msgs.size(), 2u);
  22026. EXPECT_EQ(msgs[0].data, "hello");
  22027. EXPECT_EQ(msgs[1].data, "hello");
  22028. }
  22029. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22030. // An event without data is not dispatched, and its type must not leak
  22031. // into the next event
  22032. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22033. ASSERT_EQ(msgs.size(), 1u);
  22034. EXPECT_EQ(msgs[0].event, "message");
  22035. EXPECT_EQ(msgs[0].data, "hello");
  22036. }
  22037. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22038. // Also when the empty field replaces an earlier type
  22039. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22040. ASSERT_EQ(msgs.size(), 2u);
  22041. EXPECT_EQ(msgs[0].event, "message");
  22042. EXPECT_EQ(msgs[1].event, "message");
  22043. }
  22044. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22045. // The first connection sends only an id; the second echoes back the
  22046. // Last-Event-ID it was reconnected with
  22047. std::atomic<int> connection_count{0};
  22048. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22049. if (connection_count++ == 0) {
  22050. res.set_content("id: 42\n\n", "text/event-stream");
  22051. } else {
  22052. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22053. "\n\nevent: end\ndata: end\n\n",
  22054. "text/event-stream");
  22055. }
  22056. });
  22057. auto msgs = collect("/id-only");
  22058. ASSERT_EQ(msgs.size(), 1u);
  22059. EXPECT_EQ(msgs[0].data, "42");
  22060. }
  22061. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22062. // The first connection sets an id and then clears it with an empty one; the
  22063. // second reports whether it was reconnected with a Last-Event-ID
  22064. std::atomic<int> connection_count{0};
  22065. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22066. if (connection_count++ == 0) {
  22067. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22068. "text/event-stream");
  22069. } else {
  22070. res.set_content(
  22071. std::string("data: ") +
  22072. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22073. "\n\nevent: end\ndata: end\n\n",
  22074. "text/event-stream");
  22075. }
  22076. });
  22077. auto msgs = collect("/id-clear");
  22078. ASSERT_EQ(msgs.size(), 3u);
  22079. EXPECT_EQ(msgs[0].id, "1");
  22080. EXPECT_EQ(msgs[1].id, "");
  22081. EXPECT_EQ(msgs[2].data, "not sent");
  22082. }
  22083. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22084. // The first connection sets an id and then sends ids that cannot be carried
  22085. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22086. // with
  22087. std::atomic<int> connection_count{0};
  22088. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22089. if (connection_count++ == 0) {
  22090. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22091. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22092. "text/event-stream");
  22093. } else {
  22094. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22095. "\n\nevent: end\ndata: end\n\n",
  22096. "text/event-stream");
  22097. }
  22098. });
  22099. auto msgs = collect("/id-unsendable");
  22100. ASSERT_EQ(msgs.size(), 1u);
  22101. EXPECT_EQ(msgs[0].data, "42");
  22102. }
  22103. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22104. auto msgs = parse("event: notification\nid: evt-42\n"
  22105. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22106. ASSERT_EQ(msgs.size(), 1u);
  22107. EXPECT_EQ(msgs[0].event, "notification");
  22108. EXPECT_EQ(msgs[0].id, "evt-42");
  22109. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22110. }
  22111. TEST(SSEMessageTest, Clear) {
  22112. sse::SSEMessage msg;
  22113. msg.event = "custom";
  22114. msg.data = "some data";
  22115. msg.id = "123";
  22116. msg.clear();
  22117. EXPECT_EQ(msg.event, "message");
  22118. EXPECT_EQ(msg.data, "");
  22119. EXPECT_EQ(msg.id, "");
  22120. }
  22121. //==============================================================================
  22122. // SSE Integration Tests
  22123. //==============================================================================
  22124. // Test: Successful connection and on_open callback
  22125. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22126. // Add a simple endpoint that sends one event and closes
  22127. server_->Get("/simple-event", [](const Request &, Response &res) {
  22128. res.set_chunked_content_provider(
  22129. "text/event-stream", [](size_t offset, DataSink &sink) {
  22130. if (offset == 0) {
  22131. std::string event = "data: hello\n\n";
  22132. sink.write(event.data(), event.size());
  22133. }
  22134. return false; // Close stream after sending
  22135. });
  22136. });
  22137. Client client("localhost", get_port());
  22138. sse::SSEClient sse(client, "/simple-event");
  22139. std::atomic<bool> open_called{false};
  22140. std::atomic<bool> message_received{false};
  22141. sse.on_open([&open_called]() { open_called.store(true); });
  22142. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22143. if (msg.data == "hello") { message_received.store(true); }
  22144. });
  22145. sse.set_reconnect_interval(100);
  22146. sse.set_max_reconnect_attempts(1);
  22147. // Start async
  22148. sse.start_async();
  22149. // Wait for message to be processed
  22150. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22151. sse.stop();
  22152. EXPECT_TRUE(open_called.load());
  22153. EXPECT_TRUE(message_received.load());
  22154. }
  22155. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22156. // A data line that never ends.
  22157. server_->Get("/endless-line", [](const Request &, Response &res) {
  22158. res.set_chunked_content_provider(
  22159. "text/event-stream", [](size_t offset, DataSink &sink) {
  22160. if (offset == 0) { sink.write("data: ", 6); }
  22161. std::string chunk(64 * 1024, 'A');
  22162. return sink.write(chunk.data(), chunk.size());
  22163. });
  22164. });
  22165. Client client("localhost", get_port());
  22166. sse::SSEClient sse(client, "/endless-line");
  22167. std::atomic<bool> too_long{false};
  22168. sse.on_error([&](Error err) {
  22169. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22170. });
  22171. sse.set_max_reconnect_attempts(1);
  22172. sse.start_async();
  22173. for (int i = 0; i < 500 && !too_long; i++) {
  22174. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22175. }
  22176. sse.stop();
  22177. EXPECT_TRUE(too_long);
  22178. }
  22179. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22180. // Far more in all than the client's payload limit below.
  22181. server_->Get("/many-events", [](const Request &, Response &res) {
  22182. res.set_chunked_content_provider(
  22183. "text/event-stream", [](size_t offset, DataSink &sink) {
  22184. if (offset == 0) {
  22185. std::string events;
  22186. for (int i = 0; i < 1000; i++) {
  22187. events += "data: message\n\n";
  22188. }
  22189. sink.write(events.data(), events.size());
  22190. }
  22191. return false;
  22192. });
  22193. });
  22194. Client client("localhost", get_port());
  22195. client.set_payload_max_length(1024);
  22196. sse::SSEClient sse(client, "/many-events");
  22197. std::atomic<int> messages{0};
  22198. std::atomic<bool> too_large{false};
  22199. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22200. sse.on_error([&](Error err) {
  22201. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22202. });
  22203. sse.set_max_reconnect_attempts(1);
  22204. sse.start_async();
  22205. for (int i = 0; i < 500 && messages < 1000; i++) {
  22206. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22207. }
  22208. sse.stop();
  22209. EXPECT_GE(messages.load(), 1000);
  22210. EXPECT_FALSE(too_large);
  22211. }
  22212. // Test: on_message callback
  22213. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22214. // Endpoint that sends multiple events then closes
  22215. server_->Get("/multi-event", [](const Request &, Response &res) {
  22216. res.set_chunked_content_provider(
  22217. "text/event-stream", [](size_t offset, DataSink &sink) {
  22218. if (offset == 0) {
  22219. std::string events = "data: message1\n\ndata: message2\n\n";
  22220. sink.write(events.data(), events.size());
  22221. }
  22222. return false;
  22223. });
  22224. });
  22225. Client client("localhost", get_port());
  22226. sse::SSEClient sse(client, "/multi-event");
  22227. std::vector<std::string> received_messages;
  22228. std::mutex messages_mutex;
  22229. sse.on_message([&](const sse::SSEMessage &msg) {
  22230. std::lock_guard<std::mutex> lock(messages_mutex);
  22231. received_messages.push_back(msg.data);
  22232. });
  22233. sse.set_reconnect_interval(100);
  22234. sse.set_max_reconnect_attempts(1);
  22235. sse.start_async();
  22236. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22237. sse.stop();
  22238. std::lock_guard<std::mutex> lock(messages_mutex);
  22239. EXPECT_GE(received_messages.size(), 2u);
  22240. if (received_messages.size() >= 2) {
  22241. EXPECT_EQ(received_messages[0], "message1");
  22242. EXPECT_EQ(received_messages[1], "message2");
  22243. }
  22244. }
  22245. // Test: on_event for specific types
  22246. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22247. Client client("localhost", get_port());
  22248. sse::SSEClient sse(client, "/custom-events");
  22249. std::atomic<bool> update_received{false};
  22250. std::atomic<bool> delete_received{false};
  22251. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22252. if (msg.data == "updated") { update_received.store(true); }
  22253. });
  22254. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22255. if (msg.data == "deleted") { delete_received.store(true); }
  22256. });
  22257. sse.set_max_reconnect_attempts(1);
  22258. sse.start_async();
  22259. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22260. sse.stop();
  22261. EXPECT_TRUE(update_received.load());
  22262. EXPECT_TRUE(delete_received.load());
  22263. }
  22264. // Test: on_error callback on connection failure
  22265. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22266. // Connect to a non-existent port
  22267. Client client("localhost", 59999);
  22268. sse::SSEClient sse(client, "/events");
  22269. std::atomic<bool> error_called{false};
  22270. Error received_error = Error::Success;
  22271. sse.on_error([&](Error err) {
  22272. error_called.store(true);
  22273. received_error = err;
  22274. });
  22275. sse.set_reconnect_interval(50);
  22276. sse.set_max_reconnect_attempts(1);
  22277. sse.start_async();
  22278. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22279. sse.stop();
  22280. EXPECT_TRUE(error_called.load());
  22281. EXPECT_NE(received_error, Error::Success);
  22282. }
  22283. // Test: Last-Event-ID header sent on reconnect
  22284. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22285. // Endpoint that sends event with ID
  22286. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22287. res.set_chunked_content_provider(
  22288. "text/event-stream", [](size_t offset, DataSink &sink) {
  22289. if (offset == 0) {
  22290. std::string event = "id: evt-123\ndata: test\n\n";
  22291. sink.write(event.data(), event.size());
  22292. }
  22293. return false;
  22294. });
  22295. });
  22296. Client client("localhost", get_port());
  22297. sse::SSEClient sse(client, "/event-with-id");
  22298. std::atomic<bool> id_received{false};
  22299. sse.on_message([&](const sse::SSEMessage &msg) {
  22300. if (!msg.id.empty()) { id_received.store(true); }
  22301. });
  22302. sse.set_reconnect_interval(100);
  22303. sse.set_max_reconnect_attempts(1);
  22304. sse.start_async();
  22305. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22306. sse.stop();
  22307. EXPECT_TRUE(id_received.load());
  22308. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22309. }
  22310. // Test: last_event_id() read from another thread while start_async() runs
  22311. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22312. // Ids of every length up to 200, so the stored id keeps changing size
  22313. server_->Get("/many-ids", [](const Request &, Response &res) {
  22314. res.set_chunked_content_provider(
  22315. "text/event-stream", [](size_t offset, DataSink &sink) {
  22316. if (offset == 0) {
  22317. std::string events;
  22318. for (size_t i = 0; i < 2000; i++) {
  22319. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22320. events += "data: x\n\n";
  22321. }
  22322. events += "id: end\ndata: x\n\n";
  22323. sink.write(events.data(), events.size());
  22324. }
  22325. return false;
  22326. });
  22327. });
  22328. Client client("localhost", get_port());
  22329. sse::SSEClient sse(client, "/many-ids");
  22330. // Wait out the rest of the test rather than replay the stream
  22331. sse.set_reconnect_interval(10000);
  22332. sse.set_max_reconnect_attempts(1);
  22333. sse.start_async();
  22334. auto well_formed = true;
  22335. std::string id;
  22336. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22337. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22338. id = sse.last_event_id();
  22339. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22340. well_formed = false;
  22341. }
  22342. }
  22343. sse.stop();
  22344. EXPECT_TRUE(well_formed);
  22345. EXPECT_EQ(sse.last_event_id(), "end");
  22346. }
  22347. // Test: Manual stop
  22348. TEST_F(SSEIntegrationTest, ManualStop) {
  22349. // Endpoint that sends one event and stays open briefly. The server outlives
  22350. // this test body, so the provider uses the fixture's flag, not a local.
  22351. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22352. res.set_chunked_content_provider(
  22353. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22354. if (offset == 0) {
  22355. std::string event = "data: connected\n\n";
  22356. sink.write(event.data(), event.size());
  22357. }
  22358. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22359. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22360. }
  22361. return false;
  22362. });
  22363. });
  22364. Client client("localhost", get_port());
  22365. sse::SSEClient sse(client, "/stay-open");
  22366. std::atomic<bool> connected{false};
  22367. sse.on_open([&connected]() { connected.store(true); });
  22368. sse.set_reconnect_interval(100);
  22369. sse.set_max_reconnect_attempts(1);
  22370. sse.start_async();
  22371. // Wait for connection to establish
  22372. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22373. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22374. }
  22375. EXPECT_TRUE(connected.load());
  22376. EXPECT_TRUE(sse.is_connected());
  22377. // Signal handler to stop
  22378. stop_server_.store(true);
  22379. // Stop SSE client
  22380. sse.stop();
  22381. EXPECT_FALSE(sse.is_connected());
  22382. }
  22383. // Sends one event, then nothing until stop is set
  22384. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22385. return [&stop](const Request &, Response &res) {
  22386. res.set_chunked_content_provider(
  22387. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22388. if (offset == 0) {
  22389. std::string event = "data: hello\n\n";
  22390. sink.write(event.data(), event.size());
  22391. }
  22392. while (!stop.load()) {
  22393. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22394. }
  22395. return false;
  22396. });
  22397. };
  22398. }
  22399. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22400. static void check_stop_interrupts_blocked_read(Client &client) {
  22401. client.set_read_timeout(30, 0);
  22402. for (auto by_destructor : {false, true}) {
  22403. std::atomic<bool> received{false};
  22404. std::chrono::steady_clock::time_point start;
  22405. {
  22406. sse::SSEClient sse(client, "/idle-stream");
  22407. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22408. sse.start_async();
  22409. for (int i = 0; i < 500 && !received.load(); ++i) {
  22410. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22411. }
  22412. ASSERT_TRUE(received.load());
  22413. // Let the client block in the next read
  22414. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22415. start = std::chrono::steady_clock::now();
  22416. if (!by_destructor) { sse.stop(); }
  22417. }
  22418. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22419. std::chrono::seconds(2));
  22420. }
  22421. }
  22422. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22423. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22424. Client client("localhost", get_port());
  22425. check_stop_interrupts_blocked_read(client);
  22426. }
  22427. #ifdef CPPHTTPLIB_SSL_ENABLED
  22428. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22430. std::atomic<bool> done{false};
  22431. svr.Get("/idle-stream", idle_event_stream(done));
  22432. auto port = svr.bind_to_any_port(HOST);
  22433. std::thread t([&] { svr.listen_after_bind(); });
  22434. auto se = detail::scope_exit([&] {
  22435. done.store(true);
  22436. svr.stop();
  22437. t.join();
  22438. });
  22439. svr.wait_until_ready();
  22440. Client client("https://localhost:" + std::to_string(port));
  22441. client.enable_server_certificate_verification(false);
  22442. check_stop_interrupts_blocked_read(client);
  22443. }
  22444. #endif
  22445. // Test: SSEClient with custom headers
  22446. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22447. // Setup a server endpoint that checks for custom header
  22448. std::atomic<bool> header_received{false};
  22449. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22450. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22451. header_received.store(true);
  22452. }
  22453. res.set_chunked_content_provider("text/event-stream",
  22454. [](size_t, DataSink &) { return false; });
  22455. });
  22456. Client client("localhost", get_port());
  22457. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22458. sse::SSEClient sse(client, "/header-check", headers);
  22459. sse.set_max_reconnect_attempts(1);
  22460. sse.start_async();
  22461. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22462. sse.stop();
  22463. EXPECT_TRUE(header_received.load());
  22464. }
  22465. // Test: Reconnect interval configuration
  22466. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22467. Client client("localhost", get_port());
  22468. sse::SSEClient sse(client, "/events");
  22469. auto &result = sse.set_reconnect_interval(500);
  22470. // Builder pattern should return reference to self
  22471. EXPECT_EQ(&result, &sse);
  22472. }
  22473. // Test: Max reconnect attempts
  22474. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22475. // Connect to non-existent port to force reconnects
  22476. Client client("localhost", 59998);
  22477. sse::SSEClient sse(client, "/events");
  22478. std::atomic<int> error_count{0};
  22479. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22480. sse.set_reconnect_interval(50);
  22481. sse.set_max_reconnect_attempts(2);
  22482. auto start = std::chrono::steady_clock::now();
  22483. sse.start(); // Blocking call
  22484. auto end = std::chrono::steady_clock::now();
  22485. // Should have stopped after 2 failed attempts
  22486. EXPECT_GE(error_count.load(), 2);
  22487. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22488. auto duration =
  22489. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22490. #ifdef _WIN32
  22491. // Windows is much slower for socket connection failures
  22492. EXPECT_LT(duration.count(), 7000);
  22493. #else
  22494. EXPECT_LT(duration.count(), 1000);
  22495. #endif
  22496. }
  22497. // Test: Multi-line data in integration
  22498. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22499. // Endpoint with multi-line data
  22500. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22501. res.set_chunked_content_provider(
  22502. "text/event-stream", [](size_t offset, DataSink &sink) {
  22503. if (offset == 0) {
  22504. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22505. sink.write(event.data(), event.size());
  22506. }
  22507. return false;
  22508. });
  22509. });
  22510. Client client("localhost", get_port());
  22511. sse::SSEClient sse(client, "/multiline-data");
  22512. std::string received_data;
  22513. std::mutex data_mutex;
  22514. sse.on_message([&](const sse::SSEMessage &msg) {
  22515. std::lock_guard<std::mutex> lock(data_mutex);
  22516. received_data = msg.data;
  22517. });
  22518. sse.set_reconnect_interval(100);
  22519. sse.set_max_reconnect_attempts(1);
  22520. sse.start_async();
  22521. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22522. sse.stop();
  22523. std::lock_guard<std::mutex> lock(data_mutex);
  22524. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22525. }
  22526. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22527. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22528. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22529. DataSink &sink) {
  22530. if (offset == 0) {
  22531. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22532. sink.write(events.data(), events.size());
  22533. }
  22534. return false;
  22535. });
  22536. });
  22537. Client client("localhost", get_port());
  22538. sse::SSEClient sse(client, "/empty-data-lines");
  22539. std::mutex mutex;
  22540. std::condition_variable cv;
  22541. std::vector<std::string> received;
  22542. sse.on_message([&](const sse::SSEMessage &msg) {
  22543. std::lock_guard<std::mutex> lock(mutex);
  22544. received.push_back(msg.data);
  22545. cv.notify_all();
  22546. });
  22547. sse.set_max_reconnect_attempts(1);
  22548. sse.start_async();
  22549. {
  22550. std::unique_lock<std::mutex> lock(mutex);
  22551. cv.wait_for(lock, std::chrono::seconds(2),
  22552. [&] { return received.size() >= 3; });
  22553. }
  22554. sse.stop();
  22555. ASSERT_GE(received.size(), 3u);
  22556. EXPECT_EQ(received[0], "");
  22557. EXPECT_EQ(received[1], "\nhello");
  22558. EXPECT_EQ(received[2], "");
  22559. }
  22560. // Test: Auto-reconnect after server disconnection
  22561. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22562. std::atomic<int> connection_count{0};
  22563. std::atomic<int> message_count{0};
  22564. // Endpoint that sends one event and closes, forcing reconnect
  22565. server_->Get("/reconnect-test",
  22566. [&connection_count](const Request &, Response &res) {
  22567. connection_count.fetch_add(1);
  22568. res.set_chunked_content_provider(
  22569. "text/event-stream", [](size_t offset, DataSink &sink) {
  22570. if (offset == 0) {
  22571. std::string event = "data: hello\n\n";
  22572. sink.write(event.data(), event.size());
  22573. }
  22574. return false; // Close connection after sending
  22575. });
  22576. });
  22577. Client client("localhost", get_port());
  22578. sse::SSEClient sse(client, "/reconnect-test");
  22579. sse.on_message([&message_count](const sse::SSEMessage &) {
  22580. message_count.fetch_add(1);
  22581. });
  22582. sse.set_reconnect_interval(100);
  22583. sse.set_max_reconnect_attempts(3);
  22584. sse.start_async();
  22585. // Wait long enough for multiple reconnects
  22586. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22587. sse.stop();
  22588. // Should have connected multiple times (initial + reconnects)
  22589. EXPECT_GE(connection_count.load(), 2);
  22590. // Should have received messages from multiple connections
  22591. EXPECT_GE(message_count.load(), 2);
  22592. }
  22593. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22594. std::atomic<int> connection_count{0};
  22595. // Neither Content-Length nor chunked: the close ends the stream
  22596. server_->Get("/close-delimited",
  22597. [&connection_count](const Request &, Response &res) {
  22598. connection_count.fetch_add(1);
  22599. res.set_content_provider(
  22600. "text/event-stream", [](size_t offset, DataSink &sink) {
  22601. if (offset == 0) {
  22602. std::string event = "data: hello\n\n";
  22603. sink.write(event.data(), event.size());
  22604. } else {
  22605. sink.done();
  22606. }
  22607. return true;
  22608. });
  22609. });
  22610. Client client("localhost", get_port());
  22611. sse::SSEClient sse(client, "/close-delimited");
  22612. std::atomic<int> error_count{0};
  22613. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22614. sse.set_reconnect_interval(100);
  22615. sse.start_async();
  22616. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22617. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22618. }
  22619. sse.stop();
  22620. // Reconnects as after any end of the stream, but reports no error
  22621. EXPECT_GE(connection_count.load(), 2);
  22622. EXPECT_EQ(0, error_count.load());
  22623. }
  22624. // Test: A retry field that is not all ASCII digits is ignored
  22625. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22626. std::atomic<int> connection_count{0};
  22627. server_->Get("/bad-retry",
  22628. [&connection_count](const Request &, Response &res) {
  22629. connection_count.fetch_add(1);
  22630. res.set_chunked_content_provider(
  22631. "text/event-stream", [](size_t offset, DataSink &sink) {
  22632. if (offset == 0) {
  22633. std::string event = "retry: -1\ndata: hello\n\n";
  22634. sink.write(event.data(), event.size());
  22635. }
  22636. return false;
  22637. });
  22638. });
  22639. Client client("localhost", get_port());
  22640. sse::SSEClient sse(client, "/bad-retry");
  22641. sse.set_reconnect_interval(10000);
  22642. sse.start_async();
  22643. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22644. sse.stop();
  22645. EXPECT_EQ(connection_count.load(), 1);
  22646. }
  22647. // Test: A retry field of all ASCII digits sets the reconnection time
  22648. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22649. std::mutex mutex;
  22650. std::condition_variable cv;
  22651. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22652. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22653. {
  22654. std::lock_guard<std::mutex> lock(mutex);
  22655. connected_at.push_back(std::chrono::steady_clock::now());
  22656. cv.notify_all();
  22657. }
  22658. res.set_chunked_content_provider(
  22659. "text/event-stream", [](size_t offset, DataSink &sink) {
  22660. if (offset == 0) {
  22661. std::string event = "retry: 0\ndata: hello\n\n";
  22662. sink.write(event.data(), event.size());
  22663. }
  22664. return false;
  22665. });
  22666. });
  22667. Client client("localhost", get_port());
  22668. sse::SSEClient sse(client, "/zero-retry");
  22669. sse.set_reconnect_interval(10000);
  22670. sse.start_async();
  22671. {
  22672. std::unique_lock<std::mutex> lock(mutex);
  22673. cv.wait_for(lock, std::chrono::seconds(5),
  22674. [&] { return connected_at.size() >= 2; });
  22675. }
  22676. sse.stop();
  22677. // The server-supplied interval is applied, but never below 100ms, so
  22678. // "retry: 0" does not cause a busy reconnect loop
  22679. std::lock_guard<std::mutex> lock(mutex);
  22680. ASSERT_GE(connected_at.size(), 2u);
  22681. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22682. connected_at[1] - connected_at[0])
  22683. .count();
  22684. EXPECT_GE(interval_ms, 100);
  22685. }
  22686. // Test: Last-Event-ID sent on reconnect
  22687. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22688. std::atomic<int> connection_count{0};
  22689. std::vector<std::string> received_last_event_ids;
  22690. std::mutex id_mutex;
  22691. // Endpoint that checks Last-Event-ID header and sends event with ID
  22692. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22693. int conn = connection_count.fetch_add(1);
  22694. // Capture the Last-Event-ID header from each connection
  22695. {
  22696. std::lock_guard<std::mutex> lock(id_mutex);
  22697. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22698. }
  22699. res.set_chunked_content_provider(
  22700. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22701. if (offset == 0) {
  22702. std::string event =
  22703. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22704. sink.write(event.data(), event.size());
  22705. }
  22706. return false;
  22707. });
  22708. });
  22709. Client client("localhost", get_port());
  22710. sse::SSEClient sse(client, "/reconnect-with-id");
  22711. sse.set_reconnect_interval(100);
  22712. sse.set_max_reconnect_attempts(3);
  22713. sse.start_async();
  22714. // Wait for at least 2 connections
  22715. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22716. sse.stop();
  22717. // Verify behavior
  22718. std::lock_guard<std::mutex> lock(id_mutex);
  22719. EXPECT_GE(received_last_event_ids.size(), 2u);
  22720. // First connection should have no Last-Event-ID
  22721. if (!received_last_event_ids.empty()) {
  22722. EXPECT_EQ(received_last_event_ids[0], "");
  22723. }
  22724. // Second connection should have Last-Event-ID from first connection
  22725. if (received_last_event_ids.size() >= 2) {
  22726. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22727. }
  22728. }
  22729. // Test: set_headers updates headers used on reconnect
  22730. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22731. std::vector<std::string> received_tokens;
  22732. std::mutex token_mutex;
  22733. // Endpoint that captures Authorization header
  22734. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22735. {
  22736. std::lock_guard<std::mutex> lock(token_mutex);
  22737. received_tokens.push_back(req.get_header_value("Authorization"));
  22738. }
  22739. res.set_chunked_content_provider(
  22740. "text/event-stream", [](size_t offset, DataSink &sink) {
  22741. if (offset == 0) {
  22742. std::string event = "data: hello\n\n";
  22743. sink.write(event.data(), event.size());
  22744. }
  22745. return false; // Close connection to trigger reconnect
  22746. });
  22747. });
  22748. Client client("localhost", get_port());
  22749. Headers headers = {{"Authorization", "Bearer old-token"}};
  22750. sse::SSEClient sse(client, "/auth-check", headers);
  22751. // Update headers on each successful connection
  22752. sse.on_open(
  22753. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22754. sse.set_reconnect_interval(100);
  22755. sse.set_max_reconnect_attempts(3);
  22756. sse.start_async();
  22757. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22758. sse.stop();
  22759. std::lock_guard<std::mutex> lock(token_mutex);
  22760. ASSERT_GE(received_tokens.size(), 2u);
  22761. // First connection uses original header
  22762. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22763. // Second connection uses updated header from set_headers
  22764. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22765. }
  22766. // Test: 401 allows reconnection (so on_error can refresh headers)
  22767. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22768. std::atomic<int> connection_count{0};
  22769. // Endpoint: returns 401 on first attempt, 200 on second
  22770. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22771. int conn = connection_count.fetch_add(1);
  22772. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22773. res.status = StatusCode::Unauthorized_401;
  22774. res.set_content("Unauthorized", "text/plain");
  22775. return;
  22776. }
  22777. res.set_chunked_content_provider(
  22778. "text/event-stream", [](size_t offset, DataSink &sink) {
  22779. if (offset == 0) {
  22780. std::string event = "data: authenticated\n\n";
  22781. sink.write(event.data(), event.size());
  22782. }
  22783. return false;
  22784. });
  22785. });
  22786. Client client("localhost", get_port());
  22787. Headers headers = {{"Authorization", "Bearer expired"}};
  22788. sse::SSEClient sse(client, "/auth-retry", headers);
  22789. std::atomic<bool> message_received{false};
  22790. // Refresh token on error
  22791. sse.on_error(
  22792. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22793. sse.on_message([&](const sse::SSEMessage &msg) {
  22794. if (msg.data == "authenticated") { message_received.store(true); }
  22795. });
  22796. sse.set_reconnect_interval(100);
  22797. sse.set_max_reconnect_attempts(3);
  22798. sse.start_async();
  22799. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22800. sse.stop();
  22801. // Should have reconnected after 401 and succeeded with new token
  22802. EXPECT_GE(connection_count.load(), 2);
  22803. EXPECT_TRUE(message_received.load());
  22804. }
  22805. TEST(Issue2318Test, EmptyHostString) {
  22806. {
  22807. httplib::Client cli_empty("", PORT);
  22808. auto res = cli_empty.Get("/");
  22809. ASSERT_FALSE(res);
  22810. EXPECT_EQ(httplib::Error::Connection, res.error());
  22811. }
  22812. {
  22813. httplib::Client cli(" ", PORT);
  22814. auto res = cli.Get("/");
  22815. ASSERT_FALSE(res);
  22816. EXPECT_EQ(httplib::Error::Connection, res.error());
  22817. }
  22818. }
  22819. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22820. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22821. Server svr;
  22822. // Set a small payload limit (1KB)
  22823. svr.set_payload_max_length(1024);
  22824. svr.Post("/test", [&](const Request &req, Response &res) {
  22825. res.set_content("Body size: " + std::to_string(req.body.size()),
  22826. "text/plain");
  22827. });
  22828. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22829. auto se = detail::scope_exit([&] {
  22830. svr.stop();
  22831. listen_thread.join();
  22832. });
  22833. svr.wait_until_ready();
  22834. // Create data that compresses well but exceeds limit when decompressed
  22835. // 8KB of repeated null bytes compresses to a very small size
  22836. std::string original_data(8 * 1024, '\0');
  22837. // Compress the data using gzip
  22838. std::string compressed_data;
  22839. detail::gzip_compressor compressor;
  22840. compressor.compress(original_data.data(), original_data.size(), true,
  22841. [&](const char *data, size_t size) {
  22842. compressed_data.append(data, size);
  22843. return true;
  22844. });
  22845. // Verify compression worked (compressed should be much smaller)
  22846. ASSERT_LT(compressed_data.size(), original_data.size());
  22847. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22848. // Send compressed data with Content-Encoding: gzip
  22849. Client cli(HOST, PORT);
  22850. Headers headers = {{"Content-Encoding", "gzip"}};
  22851. auto res =
  22852. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22853. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22855. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22856. }
  22857. #endif
  22858. // ============================================================================
  22859. // OpenSSL-Specific Tests
  22860. // ============================================================================
  22861. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22862. X509 *readCertificate(const std::string &strFileName) {
  22863. std::ifstream inStream(strFileName);
  22864. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22865. std::istreambuf_iterator<char>());
  22866. if (strCertPEM.empty()) return (nullptr);
  22867. BIO *pbCert = BIO_new(BIO_s_mem());
  22868. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22869. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22870. BIO_free(pbCert);
  22871. return (pCert);
  22872. }
  22873. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22874. std::ifstream inStream(strFileName);
  22875. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22876. std::istreambuf_iterator<char>());
  22877. if (strPrivateKeyPEM.empty()) return (nullptr);
  22878. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22879. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22880. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22881. BIO_free(pbPrivKey);
  22882. return (pPrivateKey);
  22883. }
  22884. TEST(BindServerTest, UpdateCerts) {
  22885. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22886. int port = svr.bind_to_any_port("0.0.0.0");
  22887. ASSERT_TRUE(svr.is_valid());
  22888. ASSERT_TRUE(port > 0);
  22889. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22890. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22891. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22892. ASSERT_TRUE(cert != nullptr);
  22893. ASSERT_TRUE(ca_cert != nullptr);
  22894. ASSERT_TRUE(key != nullptr);
  22895. X509_STORE *cert_store = X509_STORE_new();
  22896. X509_STORE_add_cert(cert_store, ca_cert);
  22897. // svr.update_certs(cert, key, cert_store); // deprecated
  22898. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22899. CLIENT_CA_CERT_FILE);
  22900. ASSERT_TRUE(svr.is_valid());
  22901. svr.stop();
  22902. X509_STORE_free(cert_store);
  22903. X509_free(cert);
  22904. X509_free(ca_cert);
  22905. EVP_PKEY_free(key);
  22906. }
  22907. // Test that update_certs() updates client CA list correctly
  22908. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22909. // Start with file-based constructor
  22910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22911. ASSERT_TRUE(svr.is_valid());
  22912. // Initially no client CA list should be set
  22913. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22914. ASSERT_TRUE(ssl_ctx != nullptr);
  22915. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22916. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22917. // Now update with client CA (PEM string)
  22918. std::string cert_pem, key_pem, ca_pem;
  22919. read_file(SERVER_CERT_FILE, cert_pem);
  22920. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22921. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22922. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22923. ASSERT_TRUE(svr.is_valid());
  22924. // Now client CA list should be set
  22925. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22926. ASSERT_TRUE(ca_list_after != nullptr);
  22927. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22928. }
  22929. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22930. // Test that the file-path SSLServer constructor properly sets the client CA
  22931. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22932. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22933. ASSERT_TRUE(svr.is_valid());
  22934. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22935. ASSERT_TRUE(ssl_ctx != nullptr);
  22936. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22937. ASSERT_TRUE(ca_list != nullptr);
  22938. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22939. }
  22940. #endif
  22941. // ============================================================================
  22942. // MbedTLS-Specific Tests
  22943. // ============================================================================
  22944. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22945. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22946. using namespace httplib::tls;
  22947. // Track if callback was invoked
  22948. bool callback_invoked = false;
  22949. // The callback receives void* ctx which is actually MbedTlsContext*
  22950. // We can access the mbedtls_ssl_config via the context
  22951. auto setup_callback = [&callback_invoked](void *ctx) {
  22952. callback_invoked = true;
  22953. // Cast to MbedTlsContext* to access the ssl config
  22954. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22955. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22956. // Use static variables to hold certificate data (simplified for test)
  22957. static mbedtls_x509_crt own_cert;
  22958. static mbedtls_pk_context own_key;
  22959. static mbedtls_x509_crt ca_chain;
  22960. static bool initialized = false;
  22961. if (!initialized) {
  22962. mbedtls_x509_crt_init(&own_cert);
  22963. mbedtls_pk_init(&own_key);
  22964. mbedtls_x509_crt_init(&ca_chain);
  22965. // Load server certificate
  22966. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22967. return false;
  22968. }
  22969. // Load server private key.
  22970. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22971. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22972. #if MBEDTLS_VERSION_MAJOR == 3
  22973. ,
  22974. mbedtls_ctr_drbg_random, nullptr
  22975. #endif
  22976. ) != 0) {
  22977. return false;
  22978. }
  22979. // Load CA chain for client verification
  22980. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22981. return false;
  22982. }
  22983. initialized = true;
  22984. }
  22985. // Configure the SSL config
  22986. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22987. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22988. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22989. // Set minimum TLS version using mbedTLS native API
  22990. #if MBEDTLS_VERSION_MAJOR >= 3
  22991. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22992. #else
  22993. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22994. MBEDTLS_SSL_MINOR_VERSION_3);
  22995. #endif
  22996. return true;
  22997. };
  22998. SSLServer svr(setup_callback);
  22999. ASSERT_TRUE(svr.is_valid());
  23000. ASSERT_TRUE(callback_invoked);
  23001. svr.Get("/test", [&](const Request &req, Response &res) {
  23002. res.set_content("test", "text/plain");
  23003. auto cert = req.peer_cert();
  23004. ASSERT_TRUE(static_cast<bool>(cert));
  23005. auto common_name = cert.subject_cn();
  23006. EXPECT_EQ("Common Name", common_name);
  23007. });
  23008. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23009. auto se = detail::scope_exit([&] {
  23010. svr.stop();
  23011. t.join();
  23012. ASSERT_FALSE(svr.is_running());
  23013. });
  23014. svr.wait_until_ready();
  23015. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23016. cli.enable_server_certificate_verification(false);
  23017. cli.set_connection_timeout(30);
  23018. auto res = cli.Get("/test");
  23019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23020. ASSERT_EQ(StatusCode::OK_200, res->status);
  23021. }
  23022. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23023. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23024. // keep-alive SSL session, which reads through that config in
  23025. // mbedtls_ssl_close_notify.
  23026. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23028. ASSERT_TRUE(svr.is_valid());
  23029. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23030. res.set_content("test", "text/plain");
  23031. });
  23032. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23033. auto se = detail::scope_exit([&] {
  23034. svr.stop();
  23035. t.join();
  23036. ASSERT_FALSE(svr.is_running());
  23037. });
  23038. svr.wait_until_ready();
  23039. {
  23040. SSLClient cli(HOST, PORT);
  23041. cli.enable_server_certificate_verification(false);
  23042. cli.set_keep_alive(true);
  23043. auto res = cli.Get("/test");
  23044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23045. ASSERT_EQ(StatusCode::OK_200, res->status);
  23046. // cli is destructed here with the keep-alive SSL session still open.
  23047. }
  23048. }
  23049. #endif
  23050. // WebSocket Tests
  23051. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23052. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23053. // defining the meaning of these bits has been negotiated.
  23054. auto make_frame = [](uint8_t first_byte) {
  23055. std::string frame;
  23056. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23057. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23058. frame += "Hello";
  23059. return frame;
  23060. };
  23061. // RSV1 set (0x40)
  23062. {
  23063. detail::BufferStream strm;
  23064. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23065. ws::Opcode opcode;
  23066. std::string payload;
  23067. bool fin;
  23068. EXPECT_EQ(
  23069. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23070. ws::impl::FrameRead::Fail);
  23071. }
  23072. // RSV2 set (0x20)
  23073. {
  23074. detail::BufferStream strm;
  23075. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23076. ws::Opcode opcode;
  23077. std::string payload;
  23078. bool fin;
  23079. EXPECT_EQ(
  23080. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23081. ws::impl::FrameRead::Fail);
  23082. }
  23083. // RSV3 set (0x10)
  23084. {
  23085. detail::BufferStream strm;
  23086. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23087. ws::Opcode opcode;
  23088. std::string payload;
  23089. bool fin;
  23090. EXPECT_EQ(
  23091. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23092. ws::impl::FrameRead::Fail);
  23093. }
  23094. // No RSV bits set - should succeed
  23095. {
  23096. detail::BufferStream strm;
  23097. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23098. ws::Opcode opcode;
  23099. std::string payload;
  23100. bool fin;
  23101. EXPECT_EQ(
  23102. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23103. ws::impl::FrameRead::Ok);
  23104. EXPECT_EQ(ws::Opcode::Text, opcode);
  23105. EXPECT_EQ("Hello", payload);
  23106. EXPECT_TRUE(fin);
  23107. }
  23108. }
  23109. TEST(WebSocketTest, ControlFrameValidation) {
  23110. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23111. // payload length <= 125.
  23112. // Ping with FIN=0 - must be rejected
  23113. {
  23114. detail::BufferStream strm;
  23115. std::string frame;
  23116. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23117. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23118. strm.write(frame.data(), frame.size());
  23119. ws::Opcode opcode;
  23120. std::string payload;
  23121. bool fin;
  23122. EXPECT_EQ(
  23123. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23124. ws::impl::FrameRead::Fail);
  23125. }
  23126. // Close with FIN=0 - must be rejected
  23127. {
  23128. detail::BufferStream strm;
  23129. std::string frame;
  23130. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23131. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23132. strm.write(frame.data(), frame.size());
  23133. ws::Opcode opcode;
  23134. std::string payload;
  23135. bool fin;
  23136. EXPECT_EQ(
  23137. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23138. ws::impl::FrameRead::Fail);
  23139. }
  23140. // Ping with payload_len=126 (extended length) - must be rejected
  23141. {
  23142. detail::BufferStream strm;
  23143. std::string frame;
  23144. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23145. frame += static_cast<char>(126); // payload_len=126 (>125)
  23146. frame += static_cast<char>(0x00); // extended length high byte
  23147. frame += static_cast<char>(126); // extended length low byte
  23148. frame += std::string(126, 'x');
  23149. strm.write(frame.data(), frame.size());
  23150. ws::Opcode opcode;
  23151. std::string payload;
  23152. bool fin;
  23153. EXPECT_EQ(
  23154. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23155. ws::impl::FrameRead::Fail);
  23156. }
  23157. // Ping with FIN=1 and payload_len=125 - should succeed
  23158. {
  23159. detail::BufferStream strm;
  23160. std::string frame;
  23161. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23162. frame += static_cast<char>(125); // payload_len=125
  23163. frame += std::string(125, 'x');
  23164. strm.write(frame.data(), frame.size());
  23165. ws::Opcode opcode;
  23166. std::string payload;
  23167. bool fin;
  23168. EXPECT_EQ(
  23169. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23170. ws::impl::FrameRead::Ok);
  23171. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23172. EXPECT_EQ(125u, payload.size());
  23173. EXPECT_TRUE(fin);
  23174. }
  23175. }
  23176. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23177. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23178. // length MUST be 0.
  23179. // MSB set - must be rejected
  23180. {
  23181. detail::BufferStream strm;
  23182. std::string frame;
  23183. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23184. frame += static_cast<char>(127); // 64-bit extended length
  23185. frame += static_cast<char>(0x80); // MSB set (invalid)
  23186. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23187. strm.write(frame.data(), frame.size());
  23188. ws::Opcode opcode;
  23189. std::string payload;
  23190. bool fin;
  23191. EXPECT_EQ(
  23192. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23193. ws::impl::FrameRead::Fail);
  23194. }
  23195. // MSB clear - should pass length parsing (will be rejected by max_len,
  23196. // but that's a different check; use a small length to verify)
  23197. {
  23198. detail::BufferStream strm;
  23199. std::string frame;
  23200. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23201. frame += static_cast<char>(127); // 64-bit extended length
  23202. frame += std::string(7, '\0'); // high bytes = 0
  23203. frame += static_cast<char>(0x03); // length = 3
  23204. frame += "abc";
  23205. strm.write(frame.data(), frame.size());
  23206. ws::Opcode opcode;
  23207. std::string payload;
  23208. bool fin;
  23209. EXPECT_EQ(
  23210. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23211. ws::impl::FrameRead::Ok);
  23212. EXPECT_EQ(ws::Opcode::Text, opcode);
  23213. EXPECT_EQ("abc", payload);
  23214. }
  23215. }
  23216. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23217. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23218. // Valid UTF-8
  23219. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23220. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23221. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23222. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23223. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23224. // Invalid UTF-8
  23225. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23226. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23227. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23228. EXPECT_FALSE(
  23229. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23230. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23231. }
  23232. TEST(WebSocketTest, ConnectAndDisconnect) {
  23233. Server svr;
  23234. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23235. std::string msg;
  23236. while (ws.read(msg)) {}
  23237. });
  23238. auto port = svr.bind_to_any_port(HOST);
  23239. std::thread t([&]() { svr.listen_after_bind(); });
  23240. svr.wait_until_ready();
  23241. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23242. auto res = client.connect();
  23243. ASSERT_TRUE(res);
  23244. EXPECT_EQ(Error::Success, res.error());
  23245. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23246. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23247. EXPECT_TRUE(client.is_open());
  23248. client.close();
  23249. EXPECT_FALSE(client.is_open());
  23250. svr.stop();
  23251. t.join();
  23252. }
  23253. TEST(WebSocketTest, ValidURL) {
  23254. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23255. EXPECT_TRUE(ws1.is_valid());
  23256. ws::WebSocketClient ws2("ws://example.com/path");
  23257. EXPECT_TRUE(ws2.is_valid());
  23258. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23259. EXPECT_TRUE(ws3.is_valid());
  23260. #ifdef CPPHTTPLIB_SSL_ENABLED
  23261. ws::WebSocketClient wss1("wss://example.com/path");
  23262. EXPECT_TRUE(wss1.is_valid());
  23263. ws::WebSocketClient wss2("wss://example.com:443/path");
  23264. EXPECT_TRUE(wss2.is_valid());
  23265. #endif
  23266. }
  23267. TEST(WebSocketTest, InvalidURL) {
  23268. // No scheme
  23269. ws::WebSocketClient ws1("localhost:8080/path");
  23270. EXPECT_FALSE(ws1.is_valid());
  23271. // No path
  23272. ws::WebSocketClient ws2("ws://localhost:8080");
  23273. EXPECT_FALSE(ws2.is_valid());
  23274. // Empty string
  23275. ws::WebSocketClient ws3("");
  23276. EXPECT_FALSE(ws3.is_valid());
  23277. // Missing host
  23278. ws::WebSocketClient ws4("ws://:8080/path");
  23279. EXPECT_FALSE(ws4.is_valid());
  23280. // Port number overflow — should not crash
  23281. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23282. EXPECT_FALSE(ws5.is_valid());
  23283. // Port out of range
  23284. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23285. EXPECT_FALSE(ws6.is_valid());
  23286. }
  23287. TEST(WebSocketTest, UnsupportedScheme) {
  23288. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23289. ws::WebSocketClient ws1("http://localhost:8080/path");
  23290. EXPECT_FALSE(ws1.is_valid());
  23291. ws::WebSocketClient ws2("https://localhost:8080/path");
  23292. EXPECT_FALSE(ws2.is_valid());
  23293. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23294. EXPECT_FALSE(ws3.is_valid());
  23295. #else
  23296. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23297. std::invalid_argument);
  23298. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23299. std::invalid_argument);
  23300. #endif
  23301. }
  23302. TEST(WebSocketTest, ConnectWhenInvalid) {
  23303. ws::WebSocketClient ws("not a valid url");
  23304. EXPECT_FALSE(ws.is_valid());
  23305. auto res = ws.connect();
  23306. EXPECT_FALSE(res);
  23307. EXPECT_EQ(Error::Connection, res.error());
  23308. EXPECT_EQ(-1, res.status());
  23309. }
  23310. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23311. // Grab a port that is free, then close it again so nothing listens there
  23312. Server svr;
  23313. auto port = svr.bind_to_any_port(HOST);
  23314. svr.stop();
  23315. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23316. auto res = client.connect();
  23317. ASSERT_FALSE(res);
  23318. EXPECT_EQ(Error::Connection, res.error());
  23319. EXPECT_EQ(-1, res.status());
  23320. }
  23321. TEST(WebSocketTest, DefaultPort) {
  23322. ws::WebSocketClient ws1("ws://example.com/path");
  23323. EXPECT_TRUE(ws1.is_valid());
  23324. // ws:// defaults to port 80 (verified by successful parse)
  23325. #ifdef CPPHTTPLIB_SSL_ENABLED
  23326. ws::WebSocketClient ws2("wss://example.com/path");
  23327. EXPECT_TRUE(ws2.is_valid());
  23328. // wss:// defaults to port 443 (verified by successful parse)
  23329. #endif
  23330. }
  23331. TEST(WebSocketTest, IPv6LiteralAddress) {
  23332. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23333. EXPECT_TRUE(ws1.is_valid());
  23334. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23335. EXPECT_TRUE(ws2.is_valid());
  23336. }
  23337. TEST(WebSocketTest, ComplexPath) {
  23338. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23339. EXPECT_TRUE(ws1.is_valid());
  23340. ws::WebSocketClient ws2("ws://localhost:8080/");
  23341. EXPECT_TRUE(ws2.is_valid());
  23342. }
  23343. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23344. Server svr;
  23345. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23346. std::string msg;
  23347. while (ws.read(msg)) {}
  23348. });
  23349. auto port = svr.bind_to_any_port(HOST);
  23350. std::thread t([&]() { svr.listen_after_bind(); });
  23351. svr.wait_until_ready();
  23352. auto another_host = "example.com";
  23353. auto wrong_ip = "192.0.2.1";
  23354. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23355. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23356. ASSERT_TRUE(client.connect());
  23357. EXPECT_TRUE(client.is_open());
  23358. client.close();
  23359. svr.stop();
  23360. t.join();
  23361. }
  23362. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23363. Server svr;
  23364. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23365. std::string msg;
  23366. while (ws.read(msg)) {}
  23367. });
  23368. auto port = svr.bind_to_any_port(HOST);
  23369. std::thread t([&]() { svr.listen_after_bind(); });
  23370. svr.wait_until_ready();
  23371. auto wrong_ip = "192.0.2.1";
  23372. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23373. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23374. client.set_connection_timeout(1);
  23375. client.set_read_timeout(1);
  23376. client.set_write_timeout(1);
  23377. EXPECT_FALSE(client.connect());
  23378. EXPECT_FALSE(client.is_open());
  23379. svr.stop();
  23380. t.join();
  23381. }
  23382. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23383. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23384. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23385. // (RFC 6761) is only a map key and the Host header value.
  23386. auto host = "target.invalid";
  23387. Server svr;
  23388. std::string received_host;
  23389. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23390. received_host = req.get_header_value("Host");
  23391. std::string msg;
  23392. while (ws.read(msg)) {}
  23393. });
  23394. auto port = svr.bind_to_any_port(HOST);
  23395. std::thread t([&]() { svr.listen_after_bind(); });
  23396. // ASSERT_* below returns from the test body, which would leave t joinable
  23397. // and make ~thread call std::terminate.
  23398. auto se = detail::scope_exit([&] {
  23399. svr.stop();
  23400. if (t.joinable()) { t.join(); }
  23401. });
  23402. svr.wait_until_ready();
  23403. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23404. std::to_string(port) + "/ws");
  23405. client.set_hostname_addr_map({{host, HOST}});
  23406. ASSERT_TRUE(client.connect());
  23407. EXPECT_TRUE(client.is_open());
  23408. client.close();
  23409. svr.stop();
  23410. t.join();
  23411. // The mapping only redirects the connection; the identity stays host_.
  23412. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23413. }
  23414. class WebSocketIntegrationTest : public ::testing::Test {
  23415. protected:
  23416. void SetUp() override {
  23417. server_ = httplib::detail::make_unique<Server>();
  23418. setup_server();
  23419. start_server();
  23420. }
  23421. void TearDown() override {
  23422. server_->stop();
  23423. if (server_thread_.joinable()) { server_thread_.join(); }
  23424. }
  23425. void setup_server() {
  23426. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23427. std::string msg;
  23428. ws::ReadResult ret;
  23429. while ((ret = ws.read(msg))) {
  23430. if (ret == ws::Binary) {
  23431. ws.send(msg.data(), msg.size());
  23432. } else {
  23433. ws.send(msg);
  23434. }
  23435. }
  23436. });
  23437. server_->WebSocket("/ws-echo-string",
  23438. [](const Request &, ws::WebSocket &ws) {
  23439. std::string msg;
  23440. while (ws.read(msg)) {
  23441. ws.send("echo: " + msg);
  23442. }
  23443. });
  23444. server_->WebSocket(
  23445. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23446. // Echo back request metadata
  23447. ws.send("path:" + req.path);
  23448. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23449. std::string msg;
  23450. while (ws.read(msg)) {}
  23451. });
  23452. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23453. std::string msg;
  23454. ws.read(msg); // wait for a message
  23455. ws.close();
  23456. });
  23457. server_->WebSocket("/ws-close-status",
  23458. [](const Request &, ws::WebSocket &ws) {
  23459. std::string msg;
  23460. ws.read(msg); // wait for a message
  23461. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23462. });
  23463. server_->WebSocket(
  23464. "/ws-subprotocol",
  23465. [](const Request &, ws::WebSocket &ws) {
  23466. std::string msg;
  23467. while (ws.read(msg)) {
  23468. ws.send(msg);
  23469. }
  23470. },
  23471. [](const std::vector<std::string> &protocols) -> std::string {
  23472. for (const auto &p : protocols) {
  23473. if (p == "graphql-ws") { return p; }
  23474. }
  23475. return "";
  23476. });
  23477. server_->WebSocket(
  23478. "/ws-subprotocol-unoffered",
  23479. [](const Request &, ws::WebSocket &ws) {
  23480. std::string msg;
  23481. while (ws.read(msg)) {
  23482. ws.send(msg);
  23483. }
  23484. },
  23485. [](const std::vector<std::string> &) -> std::string {
  23486. return "admin";
  23487. });
  23488. }
  23489. void start_server() {
  23490. port_ = server_->bind_to_any_port(HOST);
  23491. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23492. server_->wait_until_ready();
  23493. }
  23494. std::unique_ptr<Server> server_;
  23495. std::thread server_thread_;
  23496. int port_ = 0;
  23497. };
  23498. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23499. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23500. "/ws-echo");
  23501. ASSERT_TRUE(client.connect());
  23502. ASSERT_TRUE(client.is_open());
  23503. ASSERT_TRUE(client.send("Hello WebSocket"));
  23504. std::string msg;
  23505. EXPECT_EQ(ws::Text, client.read(msg));
  23506. EXPECT_EQ("Hello WebSocket", msg);
  23507. client.close();
  23508. }
  23509. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23510. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23511. "/ws-echo");
  23512. ASSERT_TRUE(client.connect());
  23513. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23514. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23515. std::string msg;
  23516. EXPECT_EQ(ws::Binary, client.read(msg));
  23517. EXPECT_EQ(binary_data, msg);
  23518. client.close();
  23519. }
  23520. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23521. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23522. "/ws-echo");
  23523. ASSERT_TRUE(client.connect());
  23524. for (int i = 0; i < 10; i++) {
  23525. auto text = "message " + std::to_string(i);
  23526. ASSERT_TRUE(client.send(text));
  23527. std::string msg;
  23528. ASSERT_TRUE(client.read(msg));
  23529. EXPECT_EQ(text, msg);
  23530. }
  23531. client.close();
  23532. }
  23533. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23534. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23535. "/ws-close");
  23536. ASSERT_TRUE(client.connect());
  23537. // Send a message to trigger the server to close
  23538. ASSERT_TRUE(client.send("trigger close"));
  23539. // The server will close, so read should return false
  23540. std::string msg;
  23541. EXPECT_FALSE(client.read(msg));
  23542. EXPECT_FALSE(client.is_open());
  23543. }
  23544. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23545. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23546. "/ws-echo");
  23547. ASSERT_TRUE(client.connect());
  23548. // 128KB message
  23549. std::string large_data(128 * 1024, 'X');
  23550. ASSERT_TRUE(client.send(large_data));
  23551. std::string msg;
  23552. ASSERT_TRUE(client.read(msg));
  23553. EXPECT_EQ(large_data, msg);
  23554. client.close();
  23555. }
  23556. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23557. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23558. "/ws-echo");
  23559. ASSERT_TRUE(client.connect());
  23560. const int num_threads = 4;
  23561. std::vector<std::thread> threads;
  23562. std::atomic<int> send_count{0};
  23563. for (int t = 0; t < num_threads; t++) {
  23564. threads.emplace_back([&client, &send_count, t]() {
  23565. for (int i = 0; i < 5; i++) {
  23566. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23567. if (client.send(text)) { send_count++; }
  23568. }
  23569. });
  23570. }
  23571. for (auto &th : threads) {
  23572. th.join();
  23573. }
  23574. int received = 0;
  23575. std::string msg;
  23576. while (received < send_count.load()) {
  23577. if (!client.read(msg)) { break; }
  23578. received++;
  23579. }
  23580. EXPECT_EQ(send_count.load(), received);
  23581. client.close();
  23582. }
  23583. TEST_F(WebSocketIntegrationTest, ReadString) {
  23584. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23585. "/ws-echo-string");
  23586. ASSERT_TRUE(client.connect());
  23587. ASSERT_TRUE(client.send("hello"));
  23588. std::string msg;
  23589. ASSERT_TRUE(client.read(msg));
  23590. EXPECT_EQ("echo: hello", msg);
  23591. ASSERT_TRUE(client.send("world"));
  23592. ASSERT_TRUE(client.read(msg));
  23593. EXPECT_EQ("echo: world", msg);
  23594. client.close();
  23595. }
  23596. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23597. Headers headers = {{"X-Test-Header", "test-value"}};
  23598. ws::WebSocketClient client(
  23599. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23600. ASSERT_TRUE(client.connect());
  23601. std::string msg;
  23602. ASSERT_TRUE(client.read(msg));
  23603. EXPECT_EQ("path:/ws-request-info", msg);
  23604. ASSERT_TRUE(client.read(msg));
  23605. EXPECT_EQ("header:test-value", msg);
  23606. client.close();
  23607. }
  23608. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23609. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23610. "/ws-echo");
  23611. client.set_read_timeout(1, 0); // 1 second
  23612. ASSERT_TRUE(client.connect());
  23613. // Don't send anything — server echo handler waits for a message, so read()
  23614. // should time out. The connection survives it: nothing was consumed.
  23615. std::string msg;
  23616. EXPECT_EQ(client.read(msg), ws::Timeout);
  23617. EXPECT_TRUE(client.is_open());
  23618. // And it is still usable afterwards.
  23619. EXPECT_TRUE(client.send("after timeout"));
  23620. EXPECT_EQ(client.read(msg), ws::Text);
  23621. EXPECT_EQ(msg, "after timeout");
  23622. }
  23623. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23624. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23625. "/ws-echo");
  23626. client.set_read_timeout(1, 0);
  23627. ASSERT_TRUE(client.connect());
  23628. ASSERT_TRUE(client.send("first"));
  23629. std::string msg;
  23630. ASSERT_EQ(client.read(msg), ws::Text);
  23631. ASSERT_EQ(msg, "first");
  23632. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23633. // not be used with a read timeout: it would reprocess the previous message.
  23634. EXPECT_EQ(client.read(msg), ws::Timeout);
  23635. EXPECT_EQ(msg, "first");
  23636. }
  23637. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23638. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23639. "/ws-echo");
  23640. ASSERT_TRUE(client.connect());
  23641. // Setting it once the connection is open reaches the live stream, not just
  23642. // the seed for the next connect().
  23643. client.set_read_timeout(1, 0);
  23644. std::string msg;
  23645. EXPECT_EQ(client.read(msg), ws::Timeout);
  23646. EXPECT_TRUE(client.is_open());
  23647. }
  23648. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23649. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23650. "/ws-echo");
  23651. client.set_read_timeout(5, 0);
  23652. ASSERT_TRUE(client.connect());
  23653. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23654. // The server should reject it and close the connection.
  23655. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23656. client.send(oversized);
  23657. // The server's read() should have failed due to payload limit,
  23658. // so our read() should return false (connection closed).
  23659. std::string msg;
  23660. EXPECT_FALSE(client.read(msg));
  23661. }
  23662. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23663. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23664. "/ws-echo");
  23665. client.set_read_timeout(10, 0);
  23666. ASSERT_TRUE(client.connect());
  23667. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23668. // This should succeed.
  23669. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23670. ASSERT_TRUE(client.send(at_limit));
  23671. std::string msg;
  23672. ASSERT_TRUE(client.read(msg));
  23673. EXPECT_EQ(at_limit.size(), msg.size());
  23674. client.close();
  23675. }
  23676. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23677. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23678. "/nonexistent");
  23679. auto res = client.connect();
  23680. EXPECT_FALSE(res);
  23681. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23682. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23683. EXPECT_FALSE(client.is_open());
  23684. }
  23685. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23686. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23687. "/ws-echo");
  23688. ASSERT_TRUE(client.connect());
  23689. ASSERT_TRUE(client.send(""));
  23690. std::string msg;
  23691. EXPECT_EQ(ws::Text, client.read(msg));
  23692. EXPECT_EQ("", msg);
  23693. client.close();
  23694. }
  23695. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23696. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23697. "/ws-echo");
  23698. // First connection
  23699. ASSERT_TRUE(client.connect());
  23700. ASSERT_TRUE(client.send("first"));
  23701. std::string msg;
  23702. ASSERT_TRUE(client.read(msg));
  23703. EXPECT_EQ("first", msg);
  23704. client.close();
  23705. EXPECT_FALSE(client.is_open());
  23706. // Reconnect using the same client object
  23707. ASSERT_TRUE(client.connect());
  23708. ASSERT_TRUE(client.is_open());
  23709. ASSERT_TRUE(client.send("second"));
  23710. ASSERT_TRUE(client.read(msg));
  23711. EXPECT_EQ("second", msg);
  23712. client.close();
  23713. }
  23714. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23715. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23716. "/ws-close-status");
  23717. ASSERT_TRUE(client.connect());
  23718. // Trigger the server to close with GoingAway status
  23719. ASSERT_TRUE(client.send("trigger"));
  23720. // read() should return false after receiving the close frame
  23721. std::string msg;
  23722. EXPECT_FALSE(client.read(msg));
  23723. EXPECT_FALSE(client.is_open());
  23724. }
  23725. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23726. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23727. "/ws-echo");
  23728. ASSERT_TRUE(client.connect());
  23729. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23730. EXPECT_FALSE(client.is_open());
  23731. }
  23732. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23733. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23734. ws::WebSocketClient client(
  23735. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23736. ASSERT_TRUE(client.connect());
  23737. // Server should have selected graphql-ws
  23738. EXPECT_EQ("graphql-ws", client.subprotocol());
  23739. client.close();
  23740. }
  23741. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23742. Headers headers;
  23743. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23744. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23745. ws::WebSocketClient client(
  23746. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23747. ASSERT_TRUE(client.connect());
  23748. // The offer on the second field line counts too, so graphql-ws is selected
  23749. EXPECT_EQ("graphql-ws", client.subprotocol());
  23750. client.close();
  23751. }
  23752. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23753. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23754. ws::WebSocketClient client(
  23755. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23756. ASSERT_TRUE(client.connect());
  23757. // Server should not have selected any subprotocol
  23758. EXPECT_TRUE(client.subprotocol().empty());
  23759. client.close();
  23760. }
  23761. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23762. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23764. "/ws-subprotocol-unoffered",
  23765. headers);
  23766. ASSERT_TRUE(client.connect());
  23767. EXPECT_TRUE(client.subprotocol().empty());
  23768. client.close();
  23769. }
  23770. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23771. // Connect without requesting any subprotocol
  23772. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23773. "/ws-subprotocol");
  23774. ASSERT_TRUE(client.connect());
  23775. EXPECT_TRUE(client.subprotocol().empty());
  23776. client.close();
  23777. }
  23778. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23779. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23780. "/ws-echo");
  23781. client.set_tcp_nodelay(true);
  23782. client.set_connection_timeout(3, 0);
  23783. bool socket_options_called = false;
  23784. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23785. ASSERT_TRUE(client.connect());
  23786. ASSERT_TRUE(client.is_open());
  23787. EXPECT_TRUE(socket_options_called);
  23788. ASSERT_TRUE(client.send("hello"));
  23789. std::string msg;
  23790. auto result = client.read(msg);
  23791. EXPECT_EQ(result, ws::ReadResult::Text);
  23792. EXPECT_EQ(msg, "hello");
  23793. client.close();
  23794. }
  23795. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23796. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23797. "/ws-echo");
  23798. client.set_connection_timeout(std::chrono::seconds(3));
  23799. client.set_write_timeout(std::chrono::seconds(3));
  23800. // A sub-second remainder exercises the seconds/microseconds split.
  23801. client.set_read_timeout(std::chrono::milliseconds(1500));
  23802. ASSERT_TRUE(client.connect());
  23803. auto start = std::chrono::steady_clock::now();
  23804. std::string msg;
  23805. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23806. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23807. std::chrono::steady_clock::now() - start)
  23808. .count();
  23809. // Above 1s so that dropping the microseconds half of the split fails here.
  23810. // Ignoring the setter altogether would not reach this line at all: a client
  23811. // waits forever by default.
  23812. EXPECT_GE(elapsed, 1400);
  23813. EXPECT_LT(elapsed, 30000);
  23814. }
  23815. #ifndef _WIN32
  23816. // A send() that times out after part of the data went out returns the count
  23817. // written so far. Every byte of the frame must still be sent, or the peer reads
  23818. // the next frame's header and payload as the rest of this one.
  23819. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  23820. signal(SIGPIPE, SIG_IGN);
  23821. const std::string large(4 * 1024 * 1024, 'A');
  23822. std::atomic<bool> large_sent{false};
  23823. std::atomic<bool> small_sent{false};
  23824. Server svr;
  23825. svr.set_write_timeout(0, 500000);
  23826. svr.set_socket_options([](socket_t sock) {
  23827. int size = 8192;
  23828. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  23829. reinterpret_cast<const char *>(&size), sizeof(size));
  23830. });
  23831. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23832. large_sent = ws.send(large.data(), large.size());
  23833. small_sent = ws.send("after");
  23834. std::string msg;
  23835. while (ws.read(msg)) {}
  23836. });
  23837. auto port = svr.bind_to_any_port(HOST);
  23838. std::thread t([&]() { svr.listen_after_bind(); });
  23839. auto se = detail::scope_exit([&] {
  23840. svr.stop();
  23841. t.join();
  23842. });
  23843. svr.wait_until_ready();
  23844. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  23845. std::to_string(port) + "/ws");
  23846. client.set_read_timeout(5);
  23847. client.set_socket_options([](socket_t sock) {
  23848. int size = 8192;
  23849. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  23850. reinterpret_cast<const char *>(&size), sizeof(size));
  23851. });
  23852. ASSERT_TRUE(client.connect());
  23853. // Outlast the server's write timeout, then drain.
  23854. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  23855. std::string msg;
  23856. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  23857. EXPECT_TRUE(msg == large);
  23858. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  23859. EXPECT_EQ("after", msg);
  23860. EXPECT_TRUE(large_sent);
  23861. EXPECT_TRUE(small_sent);
  23862. client.close();
  23863. }
  23864. #endif
  23865. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23866. Server svr;
  23867. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23868. if (!req.has_header("Authorization")) {
  23869. res.status = StatusCode::Unauthorized_401;
  23870. res.set_content("Unauthorized", "text/plain");
  23871. return Server::HandlerResponse::Handled;
  23872. }
  23873. return Server::HandlerResponse::Unhandled;
  23874. });
  23875. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23876. std::string msg;
  23877. while (ws.read(msg)) {
  23878. ws.send(msg);
  23879. }
  23880. });
  23881. auto port = svr.bind_to_any_port("localhost");
  23882. std::thread t([&]() { svr.listen_after_bind(); });
  23883. svr.wait_until_ready();
  23884. // Without Authorization header - should be rejected before upgrade
  23885. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23886. EXPECT_FALSE(client1.connect());
  23887. // The rejection is framed like any other HTTP response
  23888. {
  23889. Client cli("localhost", port);
  23890. Headers headers = {{"Upgrade", "websocket"},
  23891. {"Connection", "Upgrade"},
  23892. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23893. {"Sec-WebSocket-Version", "13"}};
  23894. auto res = cli.Get("/ws", headers);
  23895. ASSERT_TRUE(res);
  23896. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23897. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23898. EXPECT_EQ("Unauthorized", res->body);
  23899. }
  23900. // With Authorization header - should succeed
  23901. Headers headers = {{"Authorization", "Bearer token123"}};
  23902. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23903. headers);
  23904. ASSERT_TRUE(client2.connect());
  23905. ASSERT_TRUE(client2.send("hello"));
  23906. std::string msg;
  23907. ASSERT_TRUE(client2.read(msg));
  23908. EXPECT_EQ("hello", msg);
  23909. client2.close();
  23910. svr.stop();
  23911. t.join();
  23912. }
  23913. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23914. Server svr;
  23915. std::atomic<int> pre_routing_calls{0};
  23916. std::atomic<int> pre_request_calls{0};
  23917. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23918. pre_routing_calls++;
  23919. if (req.path == "/handled") {
  23920. res.set_content("handled", "text/plain");
  23921. return Server::HandlerResponse::Handled;
  23922. }
  23923. return Server::HandlerResponse::Unhandled;
  23924. });
  23925. svr.set_pre_request_handler([&](const Request &, Response &) {
  23926. pre_request_calls++;
  23927. return Server::HandlerResponse::Unhandled;
  23928. });
  23929. svr.Get("/http", [](const Request &, Response &res) {
  23930. res.set_content("http", "text/plain");
  23931. });
  23932. svr.WebSocket("/ws",
  23933. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23934. auto port = svr.bind_to_any_port("localhost");
  23935. std::thread t([&]() { svr.listen_after_bind(); });
  23936. auto se = detail::scope_exit([&] {
  23937. svr.stop();
  23938. t.join();
  23939. });
  23940. svr.wait_until_ready();
  23941. Headers upgrade = {{"Upgrade", "websocket"},
  23942. {"Connection", "Upgrade"},
  23943. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23944. {"Sec-WebSocket-Version", "13"}};
  23945. auto get = [&](const char *path) {
  23946. pre_routing_calls = 0;
  23947. return Client("localhost", port).Get(path, upgrade);
  23948. };
  23949. // No WebSocket route, but an HTTP one
  23950. auto res = get("/http");
  23951. ASSERT_TRUE(res);
  23952. EXPECT_EQ(StatusCode::OK_200, res->status);
  23953. EXPECT_EQ("http", res->body);
  23954. EXPECT_EQ(1, pre_routing_calls);
  23955. EXPECT_EQ(1, pre_request_calls);
  23956. // No route at all
  23957. res = get("/none");
  23958. ASSERT_TRUE(res);
  23959. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23960. EXPECT_EQ(1, pre_routing_calls);
  23961. // Answered by the pre-routing handler
  23962. res = get("/handled");
  23963. ASSERT_TRUE(res);
  23964. EXPECT_EQ(StatusCode::OK_200, res->status);
  23965. EXPECT_EQ("handled", res->body);
  23966. EXPECT_EQ(1, pre_routing_calls);
  23967. // A WebSocket route
  23968. pre_routing_calls = 0;
  23969. pre_request_calls = 0;
  23970. {
  23971. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23972. "/ws");
  23973. ASSERT_TRUE(client.connect());
  23974. std::string msg;
  23975. ASSERT_TRUE(client.read(msg));
  23976. EXPECT_EQ("ws", msg);
  23977. client.close();
  23978. }
  23979. EXPECT_EQ(1, pre_routing_calls);
  23980. EXPECT_EQ(1, pre_request_calls);
  23981. }
  23982. // An upgrade request answered by a hook leaves its body unread, so that body
  23983. // must not be served as the next request on the connection.
  23984. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23985. Server svr;
  23986. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23987. if (req.path == "/pre-routing") {
  23988. res.set_content("pre-routing", "text/plain");
  23989. return Server::HandlerResponse::Handled;
  23990. }
  23991. return Server::HandlerResponse::Unhandled;
  23992. });
  23993. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23994. if (req.matched_route == "/pre-request") {
  23995. res.set_content("pre-request", "text/plain");
  23996. return Server::HandlerResponse::Handled;
  23997. }
  23998. return Server::HandlerResponse::Unhandled;
  23999. });
  24000. svr.Get("/smuggled", [](const Request &, Response &res) {
  24001. res.set_content("smuggled", "text/plain");
  24002. });
  24003. svr.WebSocket("/pre-request",
  24004. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24005. auto port = svr.bind_to_any_port(HOST);
  24006. std::thread t([&]() { svr.listen_after_bind(); });
  24007. auto se = detail::scope_exit([&] {
  24008. svr.stop();
  24009. t.join();
  24010. });
  24011. svr.wait_until_ready();
  24012. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24013. for (auto path : {"/pre-routing", "/pre-request"}) {
  24014. std::string req = std::string("GET ") + path +
  24015. " HTTP/1.1\r\n"
  24016. "Host: localhost\r\n"
  24017. "Upgrade: websocket\r\n"
  24018. "Connection: Upgrade\r\n"
  24019. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24020. "Sec-WebSocket-Version: 13\r\n"
  24021. "Content-Length: " +
  24022. std::to_string(body.size()) + "\r\n\r\n" + body;
  24023. std::string res;
  24024. ASSERT_TRUE(send_request(5, req, &res, port));
  24025. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24026. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24027. // Only one response, and the body was not served as a request
  24028. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24029. }
  24030. }
  24031. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24032. Server svr;
  24033. std::atomic<int> pre_request_calls{0};
  24034. std::atomic<bool> route_matched{false};
  24035. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24036. pre_request_calls++;
  24037. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24038. if (req.get_header_value("Authorization") != "Bearer token123") {
  24039. res.status = StatusCode::Unauthorized_401;
  24040. res.set_content("Unauthorized", "text/plain");
  24041. return Server::HandlerResponse::Handled;
  24042. }
  24043. return Server::HandlerResponse::Unhandled;
  24044. });
  24045. std::atomic<bool> handler_called{false};
  24046. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24047. handler_called = true;
  24048. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24049. });
  24050. auto port = svr.bind_to_any_port("localhost");
  24051. std::thread t([&]() { svr.listen_after_bind(); });
  24052. svr.wait_until_ready();
  24053. // Without Authorization header - should be rejected before upgrade
  24054. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24055. "/ws/1");
  24056. EXPECT_FALSE(client1.connect());
  24057. EXPECT_FALSE(handler_called);
  24058. EXPECT_EQ(1, pre_request_calls);
  24059. EXPECT_TRUE(route_matched);
  24060. // The rejection is an ordinary HTTP response, not a protocol switch
  24061. {
  24062. Client cli("localhost", port);
  24063. Headers headers = {{"Upgrade", "websocket"},
  24064. {"Connection", "Upgrade"},
  24065. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24066. {"Sec-WebSocket-Version", "13"}};
  24067. auto res = cli.Get("/ws/1", headers);
  24068. ASSERT_TRUE(res);
  24069. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24070. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24071. EXPECT_EQ("Unauthorized", res->body);
  24072. }
  24073. EXPECT_FALSE(handler_called);
  24074. // With Authorization header - should succeed
  24075. Headers headers = {{"Authorization", "Bearer token123"}};
  24076. ws::WebSocketClient client2(
  24077. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24078. ASSERT_TRUE(client2.connect());
  24079. std::string msg;
  24080. ASSERT_TRUE(client2.read(msg));
  24081. EXPECT_EQ("/ws/:id 2", msg);
  24082. EXPECT_TRUE(handler_called);
  24083. client2.close();
  24084. svr.stop();
  24085. t.join();
  24086. }
  24087. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24088. static Headers websocket_upgrade_headers() {
  24089. return {{"Upgrade", "websocket"},
  24090. {"Connection", "Upgrade"},
  24091. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24092. {"Sec-WebSocket-Version", "13"},
  24093. {"Sec-WebSocket-Protocol", "chat"}};
  24094. }
  24095. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24096. Server svr;
  24097. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24098. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24099. return Server::HandlerResponse::Unhandled;
  24100. });
  24101. svr.set_pre_request_handler([](const Request &req, Response &) {
  24102. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24103. return Server::HandlerResponse::Unhandled;
  24104. });
  24105. svr.set_exception_handler(
  24106. [](const Request &, Response &res, std::exception_ptr ep) {
  24107. try {
  24108. std::rethrow_exception(ep);
  24109. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24110. });
  24111. auto handler = [](const Request &, ws::WebSocket &) {};
  24112. svr.WebSocket("/pre-routing", handler);
  24113. svr.WebSocket("/pre-request", handler);
  24114. svr.WebSocket("/sub-protocol", handler,
  24115. [](const std::vector<std::string> &) -> std::string {
  24116. throw std::runtime_error("/sub-protocol");
  24117. });
  24118. auto port = svr.bind_to_any_port(HOST);
  24119. ASSERT_GT(port, 0);
  24120. thread t = thread([&] { svr.listen_after_bind(); });
  24121. auto se = detail::scope_exit([&] {
  24122. svr.stop();
  24123. t.join();
  24124. ASSERT_FALSE(svr.is_running());
  24125. });
  24126. svr.wait_until_ready();
  24127. Client cli(HOST, port);
  24128. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24129. auto res = cli.Get(path, websocket_upgrade_headers());
  24130. if (!res) {
  24131. ADD_FAILURE() << path << ": " << to_string(res.error());
  24132. continue;
  24133. }
  24134. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24135. EXPECT_EQ(path, res->body);
  24136. }
  24137. }
  24138. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24139. Server svr;
  24140. svr.set_pre_routing_handler(
  24141. [](const Request &, Response &) -> Server::HandlerResponse {
  24142. throw std::runtime_error("pre-routing");
  24143. });
  24144. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24145. auto port = svr.bind_to_any_port(HOST);
  24146. ASSERT_GT(port, 0);
  24147. thread t = thread([&] { svr.listen_after_bind(); });
  24148. auto se = detail::scope_exit([&] {
  24149. svr.stop();
  24150. t.join();
  24151. ASSERT_FALSE(svr.is_running());
  24152. });
  24153. svr.wait_until_ready();
  24154. Client cli(HOST, port);
  24155. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24156. ASSERT_TRUE(res) << to_string(res.error());
  24157. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24158. }
  24159. #endif
  24160. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24161. Server svr;
  24162. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24163. // A read timeout is how a handler gets control back. Without it, a handler
  24164. // parked in read() can never write on the connection it is reading.
  24165. ws.set_read_timeout(std::chrono::milliseconds(100));
  24166. std::string msg;
  24167. while (ws.is_open()) {
  24168. auto r = ws.read(msg);
  24169. if (r == httplib::ws::Timeout) {
  24170. ws.send("tick");
  24171. continue;
  24172. }
  24173. if (r == httplib::ws::Fail) { break; }
  24174. ws.send(msg);
  24175. }
  24176. });
  24177. auto port = svr.bind_to_any_port("localhost");
  24178. std::thread t([&]() { svr.listen_after_bind(); });
  24179. svr.wait_until_ready();
  24180. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24181. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24182. ASSERT_TRUE(client.connect());
  24183. // The client sends nothing, so anything it receives came out of the
  24184. // handler's timeout path.
  24185. std::string msg;
  24186. ASSERT_EQ(client.read(msg), ws::Text);
  24187. EXPECT_EQ("tick", msg);
  24188. client.close();
  24189. svr.stop();
  24190. t.join();
  24191. }
  24192. // Stream::read may return fewer bytes than asked for. This is that contract at
  24193. // its worst -- one byte per call -- which is what a frame header straddling a
  24194. // read buffer's boundary looks like to the frame parser.
  24195. class WsByteAtATimeStream : public Stream {
  24196. public:
  24197. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24198. bool is_readable() const override { return true; }
  24199. bool wait_readable() const override { return true; }
  24200. bool wait_writable() const override { return true; }
  24201. ssize_t read(char *ptr, size_t size) override {
  24202. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24203. *ptr = data_[pos_++];
  24204. return 1;
  24205. }
  24206. ssize_t write(const char *, size_t size) override {
  24207. return static_cast<ssize_t>(size);
  24208. }
  24209. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24210. ip = "127.0.0.1";
  24211. port = 0;
  24212. }
  24213. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24214. ip = "127.0.0.1";
  24215. port = 0;
  24216. }
  24217. socket_t socket() const override { return INVALID_SOCKET; }
  24218. time_t duration() const override { return 0; }
  24219. private:
  24220. std::string data_;
  24221. size_t pos_ = 0;
  24222. };
  24223. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24224. // The payload uses the 16-bit extended length, so the header, the length
  24225. // and the mask key are all multi-byte fields here. Each used to be read
  24226. // with a single read() call, which fails as soon as one is split. The
  24227. // payload is also a little over one read chunk, so it is read in two.
  24228. std::string body;
  24229. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24230. body += static_cast<char>(i % 251);
  24231. }
  24232. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24233. std::string frame;
  24234. frame += static_cast<char>(0x81); // FIN + Text
  24235. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24236. frame += static_cast<char>(body.size() >> 8);
  24237. frame += static_cast<char>(body.size() & 0xff);
  24238. for (size_t i = 0; i < 4; i++) {
  24239. frame += static_cast<char>(mask[i]);
  24240. }
  24241. for (size_t i = 0; i < body.size(); i++) {
  24242. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24243. }
  24244. WsByteAtATimeStream strm(frame);
  24245. ws::Opcode opcode;
  24246. std::string payload;
  24247. bool fin = false;
  24248. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24249. /*expect_masked=*/true, body.size()),
  24250. ws::impl::FrameRead::Ok);
  24251. EXPECT_TRUE(fin);
  24252. EXPECT_EQ(opcode, ws::Opcode::Text);
  24253. EXPECT_EQ(payload, body);
  24254. }
  24255. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24256. std::string body(2000, 'x');
  24257. std::string frame;
  24258. frame += static_cast<char>(0x82); // FIN + Binary
  24259. frame += static_cast<char>(126); // 16-bit length follows
  24260. frame += static_cast<char>(body.size() >> 8);
  24261. frame += static_cast<char>(body.size() & 0xff);
  24262. frame += body;
  24263. detail::BufferStream strm;
  24264. strm.write(frame.data(), frame.size());
  24265. ws::Opcode opcode;
  24266. std::string payload;
  24267. bool fin;
  24268. EXPECT_EQ(
  24269. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24270. ws::impl::FrameRead::Ok);
  24271. EXPECT_EQ(body, payload);
  24272. }
  24273. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24274. // The header announces the largest payload allowed, and only 3 bytes of it
  24275. // ever arrive.
  24276. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24277. std::string frame;
  24278. frame += static_cast<char>(0x82); // FIN + Binary
  24279. frame += static_cast<char>(127); // 64-bit length follows
  24280. for (int shift = 56; shift >= 0; shift -= 8) {
  24281. frame += static_cast<char>((len >> shift) & 0xff);
  24282. }
  24283. frame += "abc";
  24284. detail::BufferStream strm;
  24285. strm.write(frame.data(), frame.size());
  24286. ws::Opcode opcode;
  24287. std::string payload;
  24288. bool fin;
  24289. EXPECT_EQ(
  24290. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24291. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24292. ws::impl::FrameRead::Fail);
  24293. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24294. }
  24295. TEST(WebSocketTest, QueryStringInHandshake) {
  24296. Server svr;
  24297. std::mutex mtx;
  24298. std::string received_target;
  24299. std::string received_token;
  24300. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24301. {
  24302. std::lock_guard<std::mutex> lock(mtx);
  24303. received_target = req.target;
  24304. if (req.has_param("token")) {
  24305. received_token = req.get_param_value("token");
  24306. }
  24307. }
  24308. std::string msg;
  24309. while (ws.read(msg)) {
  24310. ws.send(msg);
  24311. }
  24312. });
  24313. auto port = svr.bind_to_any_port("localhost");
  24314. std::thread t([&]() { svr.listen_after_bind(); });
  24315. svr.wait_until_ready();
  24316. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24317. "/ws?token=ABC&session=123");
  24318. ASSERT_TRUE(client.connect());
  24319. // Round-trip ensures the handler has run and captured the request.
  24320. ASSERT_TRUE(client.send("hello"));
  24321. std::string msg;
  24322. ASSERT_TRUE(client.read(msg));
  24323. EXPECT_EQ("hello", msg);
  24324. client.close();
  24325. {
  24326. std::lock_guard<std::mutex> lock(mtx);
  24327. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24328. EXPECT_EQ("ABC", received_token);
  24329. }
  24330. svr.stop();
  24331. t.join();
  24332. }
  24333. // Run a handshake against a throwaway server and hand the request the server
  24334. // received back to the caller, so tests can assert on the headers the client
  24335. // actually put on the wire.
  24336. static void capture_websocket_handshake_request(
  24337. const Headers &client_headers,
  24338. std::function<void(const Request &, int port)> verify) {
  24339. Server svr;
  24340. std::mutex mtx;
  24341. Request received;
  24342. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24343. {
  24344. std::lock_guard<std::mutex> lock(mtx);
  24345. received = req;
  24346. }
  24347. std::string msg;
  24348. while (ws.read(msg)) {
  24349. ws.send(msg);
  24350. }
  24351. });
  24352. auto port = svr.bind_to_any_port("localhost");
  24353. std::thread t([&]() { svr.listen_after_bind(); });
  24354. auto se = detail::scope_exit([&] {
  24355. svr.stop();
  24356. t.join();
  24357. });
  24358. svr.wait_until_ready();
  24359. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24360. client_headers);
  24361. ASSERT_TRUE(client.connect());
  24362. ASSERT_TRUE(client.send("hello"));
  24363. std::string msg;
  24364. ASSERT_TRUE(client.read(msg));
  24365. client.close();
  24366. {
  24367. std::lock_guard<std::mutex> lock(mtx);
  24368. verify(received, port);
  24369. }
  24370. }
  24371. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24372. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24373. // Non-default port must be present in the Host header. Default ports
  24374. // (80/443) are omitted; that logic is covered by
  24375. // MakeHostAndPortStringTest.
  24376. EXPECT_EQ("localhost:" + std::to_string(port),
  24377. req.get_header_value("Host"));
  24378. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24379. req.get_header_value("User-Agent"));
  24380. EXPECT_FALSE(req.has_header("Accept"));
  24381. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24382. EXPECT_FALSE(req.has_header("Content-Length"));
  24383. });
  24384. }
  24385. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24386. capture_websocket_handshake_request(
  24387. {{"Host", "example.com"},
  24388. {"User-Agent", "custom-agent"},
  24389. {"X-Custom", "value"}},
  24390. [](const Request &req, int) {
  24391. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24392. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24393. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24394. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24395. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24396. });
  24397. }
  24398. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24399. capture_websocket_handshake_request(
  24400. {{"Upgrade", "bogus"},
  24401. {"Connection", "close"},
  24402. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24403. {"Sec-WebSocket-Version", "8"}},
  24404. [](const Request &req, int) {
  24405. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24406. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24407. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24408. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24409. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24410. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24411. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24412. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24413. req.get_header_value("Sec-WebSocket-Key"));
  24414. });
  24415. }
  24416. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24417. // A header the client refuses to send must abort the handshake before any
  24418. // part of it reaches the wire; a lone request line would otherwise sit in
  24419. // the peer's buffer as a truncated request.
  24420. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24421. ASSERT_NE(INVALID_SOCKET, srv);
  24422. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24423. sockaddr_in addr{};
  24424. addr.sin_family = AF_INET;
  24425. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24426. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24427. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24428. ASSERT_EQ(0, ::listen(srv, 1));
  24429. sockaddr_in bound{};
  24430. socklen_t bound_len = sizeof(bound);
  24431. ASSERT_EQ(
  24432. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24433. auto port = ntohs(bound.sin_port);
  24434. ssize_t received = -1;
  24435. std::thread t([&] {
  24436. // Bound every blocking call so a regression fails the test with a bad
  24437. // value instead of hanging the suite.
  24438. fd_set rfds;
  24439. FD_ZERO(&rfds);
  24440. FD_SET(srv, &rfds);
  24441. timeval tv{5, 0};
  24442. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24443. 0) {
  24444. return;
  24445. }
  24446. sockaddr_in cli_addr{};
  24447. socklen_t cli_len = sizeof(cli_addr);
  24448. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24449. if (cli == INVALID_SOCKET) { return; }
  24450. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24451. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24452. char buf[4096];
  24453. received = ::recv(cli, buf, sizeof(buf), 0);
  24454. });
  24455. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24456. // connect() has already shut the socket down by the time it returns false,
  24457. // so the peer sees EOF without waiting for the client to be destroyed.
  24458. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24459. {{"X-Bad", "a\r\nInjected: 1"}});
  24460. EXPECT_FALSE(client.connect());
  24461. t.join();
  24462. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24463. EXPECT_EQ(0, received);
  24464. }
  24465. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24466. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24467. // contains "upgrade" as a substring is a different token and must not
  24468. // start a WebSocket handshake.
  24469. auto make_request = [](const std::vector<std::string> &connection_values) {
  24470. Request req;
  24471. req.method = "GET";
  24472. req.headers.emplace("Upgrade", "websocket");
  24473. for (const auto &value : connection_values) {
  24474. req.headers.emplace("Connection", value);
  24475. }
  24476. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24477. req.headers.emplace("Sec-WebSocket-Version", "13");
  24478. return req;
  24479. };
  24480. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24481. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24482. EXPECT_TRUE(
  24483. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24484. EXPECT_TRUE(
  24485. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24486. EXPECT_TRUE(
  24487. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24488. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24489. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24490. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24491. EXPECT_FALSE(
  24492. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24493. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24494. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24495. }
  24496. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24497. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24498. // asks recipients to match each protocol-name case-insensitively, and RFC
  24499. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24500. // client naming websocket alongside another protocol, or on a second field
  24501. // line, is offering websocket; a value that merely contains "websocket" as a
  24502. // substring is a different protocol name and is not.
  24503. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24504. Request req;
  24505. req.method = "GET";
  24506. for (const auto &value : upgrade_values) {
  24507. req.headers.emplace("Upgrade", value);
  24508. }
  24509. req.headers.emplace("Connection", "Upgrade");
  24510. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24511. req.headers.emplace("Sec-WebSocket-Version", "13");
  24512. return req;
  24513. };
  24514. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24515. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24516. EXPECT_TRUE(
  24517. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24518. EXPECT_TRUE(
  24519. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24520. EXPECT_TRUE(
  24521. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24522. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24523. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24524. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24525. EXPECT_FALSE(
  24526. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24527. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24528. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24529. }
  24530. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24531. Server svr;
  24532. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24533. auto port = svr.bind_to_any_port("localhost");
  24534. std::thread t([&]() { svr.listen_after_bind(); });
  24535. auto se = detail::scope_exit([&] {
  24536. svr.stop();
  24537. t.join();
  24538. });
  24539. svr.wait_until_ready();
  24540. Headers headers = {{"Upgrade", "websocket"},
  24541. {"Connection", "notupgrade"},
  24542. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24543. {"Sec-WebSocket-Version", "13"}};
  24544. Client cli("localhost", port);
  24545. auto res = cli.Get("/ws", headers);
  24546. // The route exists only as a WebSocket route, so a request that fails the
  24547. // handshake check falls through to ordinary routing.
  24548. ASSERT_TRUE(res);
  24549. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24550. }
  24551. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24552. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24553. // Connection value is the only thing left for the client to reject.
  24554. Server svr;
  24555. svr.Get("/ws", [](const Request &req, Response &res) {
  24556. res.status = StatusCode::SwitchingProtocol_101;
  24557. res.set_header("Upgrade", "websocket");
  24558. res.set_header("Connection", "notupgrade");
  24559. res.set_header("Sec-WebSocket-Accept",
  24560. detail::websocket_accept_key(
  24561. req.get_header_value("Sec-WebSocket-Key")));
  24562. });
  24563. auto port = svr.bind_to_any_port("localhost");
  24564. std::thread t([&]() { svr.listen_after_bind(); });
  24565. auto se = detail::scope_exit([&] {
  24566. svr.stop();
  24567. t.join();
  24568. });
  24569. svr.wait_until_ready();
  24570. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24571. auto res = client.connect();
  24572. EXPECT_FALSE(res);
  24573. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24574. EXPECT_FALSE(client.is_open());
  24575. }
  24576. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24577. Server svr;
  24578. svr.Get("/ws", [](const Request &req, Response &res) {
  24579. res.status = StatusCode::SwitchingProtocol_101;
  24580. res.set_header("Upgrade", "websocket");
  24581. res.set_header("Connection", "Upgrade");
  24582. res.set_header("Sec-WebSocket-Accept",
  24583. detail::websocket_accept_key(
  24584. req.get_header_value("Sec-WebSocket-Key")));
  24585. res.set_header("Sec-WebSocket-Protocol", "admin");
  24586. });
  24587. auto port = svr.bind_to_any_port("localhost");
  24588. std::thread t([&]() { svr.listen_after_bind(); });
  24589. auto se = detail::scope_exit([&] {
  24590. svr.stop();
  24591. t.join();
  24592. });
  24593. svr.wait_until_ready();
  24594. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24595. // Server selects a subprotocol the client never offered
  24596. {
  24597. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24598. ws::WebSocketClient client(url, headers);
  24599. auto res = client.connect();
  24600. EXPECT_FALSE(res);
  24601. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24602. EXPECT_FALSE(client.is_open());
  24603. EXPECT_TRUE(client.subprotocol().empty());
  24604. }
  24605. // Client offered none but the server named one anyway
  24606. {
  24607. ws::WebSocketClient client(url);
  24608. auto res = client.connect();
  24609. EXPECT_FALSE(res);
  24610. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24611. EXPECT_FALSE(client.is_open());
  24612. EXPECT_TRUE(client.subprotocol().empty());
  24613. }
  24614. }
  24615. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24616. // The socket path doubles as the URL host, so it must not contain '/'.
  24617. const char *shard = getenv("GTEST_SHARD_INDEX");
  24618. const std::string sock_path =
  24619. shard ? std::string("httplib-ws-") + shard + ".sock"
  24620. : std::string("httplib-ws.sock");
  24621. std::remove(sock_path.c_str());
  24622. Server svr;
  24623. std::mutex mtx;
  24624. std::string received_host;
  24625. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24626. {
  24627. std::lock_guard<std::mutex> lock(mtx);
  24628. received_host = req.get_header_value("Host");
  24629. }
  24630. std::string msg;
  24631. while (ws.read(msg)) {
  24632. ws.send(msg);
  24633. }
  24634. });
  24635. svr.set_address_family(AF_UNIX);
  24636. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24637. auto se = detail::scope_exit([&] {
  24638. svr.stop();
  24639. t.join();
  24640. std::remove(sock_path.c_str());
  24641. });
  24642. svr.wait_until_ready();
  24643. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24644. client.set_address_family(AF_UNIX);
  24645. ASSERT_TRUE(client.connect());
  24646. ASSERT_TRUE(client.send("hello"));
  24647. std::string msg;
  24648. ASSERT_TRUE(client.read(msg));
  24649. client.close();
  24650. {
  24651. std::lock_guard<std::mutex> lock(mtx);
  24652. // There is no host:port for a Unix socket, so the same "localhost"
  24653. // placeholder the HTTP client uses is expected.
  24654. EXPECT_EQ("localhost", received_host);
  24655. }
  24656. }
  24657. // Two threads must never parse WebSocket frames from the same stream.
  24658. // close() used to read the peer's Close reply with its own frame read, so it
  24659. // raced a reader thread that was in the middle of a payload: the payload loop
  24660. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24661. // so bytes taken by close() were replaced with bytes from further along the
  24662. // stream. The message kept its length and silently changed content.
  24663. //
  24664. // The raw peer below sends a frame header plus part of the payload, waits for
  24665. // the handler to call close(), and only then sends the rest. Whichever thread
  24666. // would win the race for those bytes, the message must arrive intact, because
  24667. // close() must not touch the stream while read() owns it.
  24668. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24669. #ifndef _WIN32
  24670. signal(SIGPIPE, SIG_IGN);
  24671. #endif
  24672. const size_t payload_len = 120; // fits the 7-bit length field
  24673. const size_t prefix_len = 8;
  24674. const int attempts = 8;
  24675. std::string expected(payload_len, '\0');
  24676. for (size_t i = 0; i < payload_len; i++) {
  24677. expected[i] = static_cast<char>('a' + i % 26);
  24678. }
  24679. std::atomic<bool> peer_stalled{false};
  24680. std::atomic<bool> handler_done{false};
  24681. std::mutex received_mutex;
  24682. std::vector<std::string> received;
  24683. // Bound every wait, so a regression fails the test instead of hanging the
  24684. // suite.
  24685. auto wait_for = [](const std::atomic<bool> &flag) {
  24686. for (int i = 0; i < 500 && !flag; i++) {
  24687. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24688. }
  24689. };
  24690. Server svr;
  24691. svr.set_websocket_ping_interval(0);
  24692. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24693. std::thread reader([&]() {
  24694. std::string msg;
  24695. while (ws.read(msg)) {
  24696. std::lock_guard<std::mutex> guard(received_mutex);
  24697. received.push_back(msg);
  24698. }
  24699. });
  24700. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24701. // inside read_websocket_frame() when close() runs.
  24702. wait_for(peer_stalled);
  24703. ws.close();
  24704. reader.join();
  24705. handler_done = true;
  24706. });
  24707. auto port = svr.bind_to_any_port("127.0.0.1");
  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. auto send_bytes = [](socket_t s, const std::string &data) {
  24715. #ifdef _WIN32
  24716. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24717. #else
  24718. auto n = ::send(s, data.data(), data.size(), 0);
  24719. #endif
  24720. return n == static_cast<decltype(n)>(data.size());
  24721. };
  24722. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24723. // Every length used here fits the 7-bit length field.
  24724. auto masked_header = [](uint8_t first_byte, size_t len) {
  24725. std::string h;
  24726. h += static_cast<char>(first_byte);
  24727. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24728. h.append(4, '\0'); // mask key
  24729. return h;
  24730. };
  24731. for (int attempt = 0; attempt < attempts; attempt++) {
  24732. peer_stalled = false;
  24733. handler_done = false;
  24734. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24735. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24736. auto se_sock = detail::scope_exit([&] {
  24737. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24738. });
  24739. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24740. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24741. sockaddr_in addr{};
  24742. addr.sin_family = AF_INET;
  24743. addr.sin_port = htons(static_cast<uint16_t>(port));
  24744. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24745. ASSERT_EQ(
  24746. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24747. << "attempt " << attempt;
  24748. ASSERT_TRUE(send_bytes(sock,
  24749. "GET /ws HTTP/1.1\r\n"
  24750. "Host: 127.0.0.1\r\n"
  24751. "Upgrade: websocket\r\n"
  24752. "Connection: Upgrade\r\n"
  24753. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24754. "Sec-WebSocket-Version: 13\r\n"
  24755. "\r\n"))
  24756. << "attempt " << attempt;
  24757. std::string response;
  24758. while (response.find("\r\n\r\n") == std::string::npos) {
  24759. char buf[512];
  24760. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24761. if (n <= 0) { break; }
  24762. response.append(buf, static_cast<size_t>(n));
  24763. }
  24764. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24765. << "attempt " << attempt;
  24766. // Send the header of a Binary message but only the first prefix_len bytes
  24767. // of its payload, leaving the reader thread stalled inside the payload.
  24768. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24769. expected.substr(0, prefix_len)))
  24770. << "attempt " << attempt;
  24771. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24772. peer_stalled = true;
  24773. // Let close() send its Close frame and park in its own read before the
  24774. // rest of the payload arrives, so both threads are waiting for it.
  24775. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24776. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24777. close_frame += static_cast<char>(0x03); // status 1000
  24778. close_frame += static_cast<char>(0xE8);
  24779. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24780. << "attempt " << attempt;
  24781. // Closing the peer releases the reader thread even on the buggy path,
  24782. // where it waits for bytes another thread already consumed.
  24783. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24784. detail::close_socket(sock);
  24785. sock = INVALID_SOCKET;
  24786. wait_for(handler_done);
  24787. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24788. }
  24789. std::lock_guard<std::mutex> guard(received_mutex);
  24790. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24791. << "a message in flight when close() ran was dropped";
  24792. for (size_t i = 0; i < received.size(); i++) {
  24793. EXPECT_EQ(expected, received[i]) << "message " << i;
  24794. }
  24795. }
  24796. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24797. // returning the socket, or INVALID_SOCKET.
  24798. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24799. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24800. if (sock == INVALID_SOCKET) { return sock; }
  24801. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24802. sockaddr_in addr{};
  24803. addr.sin_family = AF_INET;
  24804. addr.sin_port = htons(static_cast<uint16_t>(port));
  24805. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24806. std::string req = "GET " + path +
  24807. " HTTP/1.1\r\n"
  24808. "Host: 127.0.0.1\r\n"
  24809. "Upgrade: websocket\r\n"
  24810. "Connection: Upgrade\r\n"
  24811. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24812. "Sec-WebSocket-Version: 13\r\n"
  24813. "\r\n";
  24814. std::string res;
  24815. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24816. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24817. static_cast<ssize_t>(req.size())) {
  24818. char c;
  24819. while (res.find("\r\n\r\n") == std::string::npos &&
  24820. ::recv(sock, &c, 1, 0) == 1) {
  24821. res += c;
  24822. }
  24823. }
  24824. if (res.find(" 101 ") == std::string::npos) {
  24825. detail::close_socket(sock);
  24826. return INVALID_SOCKET;
  24827. }
  24828. return sock;
  24829. }
  24830. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24831. // The payload must fit the 7-bit length field.
  24832. static std::string masked_frame(uint8_t first_byte,
  24833. const std::string &payload) {
  24834. std::string f;
  24835. f += static_cast<char>(first_byte);
  24836. f += static_cast<char>(0x80 | payload.size());
  24837. f.append(4, '\0');
  24838. return f + payload;
  24839. }
  24840. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24841. std::atomic<bool> done{false};
  24842. std::string received;
  24843. Server svr;
  24844. svr.set_websocket_ping_interval(0);
  24845. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24846. std::string msg;
  24847. if (ws.read(msg) == ws::Binary) { received = msg; }
  24848. done = true;
  24849. });
  24850. auto port = svr.bind_to_any_port("127.0.0.1");
  24851. std::thread t([&]() { svr.listen_after_bind(); });
  24852. auto se = detail::scope_exit([&] {
  24853. svr.stop();
  24854. t.join();
  24855. });
  24856. svr.wait_until_ready();
  24857. auto sock = connect_raw_websocket(port, "/ws");
  24858. ASSERT_NE(INVALID_SOCKET, sock);
  24859. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24860. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24861. masked_frame(0x89, "p") + // FIN + Ping
  24862. masked_frame(0x80, "lo"); // FIN + Continuation
  24863. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24864. for (int i = 0; i < 500 && !done; i++) {
  24865. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24866. }
  24867. ASSERT_TRUE(done);
  24868. EXPECT_EQ("Hello", received);
  24869. // The Ping between the fragments is answered with a Pong.
  24870. char pong[3];
  24871. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24872. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24873. }
  24874. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24875. Server svr;
  24876. svr.set_websocket_ping_interval(-1);
  24877. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24878. std::string msg;
  24879. while (ws.read(msg)) {}
  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 sock = connect_raw_websocket(port, "/ws");
  24889. ASSERT_NE(INVALID_SOCKET, sock);
  24890. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24891. // Nothing comes while the client stays quiet.
  24892. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24893. char c;
  24894. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24895. }
  24896. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24897. // and that has to end a read() already waiting on the peer, on every platform.
  24898. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24899. // The peer sends no pings, and its handler never calls read(), which is
  24900. // where pongs are written.
  24901. std::mutex mutex;
  24902. std::condition_variable cv;
  24903. auto release = false;
  24904. svr.set_websocket_ping_interval(0);
  24905. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24906. std::unique_lock<std::mutex> lock(mutex);
  24907. cv.wait(lock, [&] { return release; });
  24908. });
  24909. auto port = svr.bind_to_any_port(HOST);
  24910. std::thread t([&]() { svr.listen_after_bind(); });
  24911. auto se = detail::scope_exit([&] {
  24912. {
  24913. std::lock_guard<std::mutex> lock(mutex);
  24914. release = true;
  24915. }
  24916. cv.notify_all();
  24917. svr.stop();
  24918. t.join();
  24919. });
  24920. svr.wait_until_ready();
  24921. ws::WebSocketClient client(std::string(scheme) +
  24922. "://localhost:" + std::to_string(port) + "/ws");
  24923. #ifdef CPPHTTPLIB_SSL_ENABLED
  24924. client.enable_server_certificate_verification(false);
  24925. #endif
  24926. // A ping a second, given up on after two go unanswered: about 3s
  24927. client.set_websocket_ping_interval(1);
  24928. client.set_websocket_max_missed_pongs(2);
  24929. // Well past that, so that a read the timeout ends instead stands out
  24930. client.set_read_timeout(10);
  24931. ASSERT_TRUE(client.connect());
  24932. auto start = std::chrono::steady_clock::now();
  24933. std::string msg;
  24934. EXPECT_EQ(ws::Fail, client.read(msg));
  24935. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24936. std::chrono::steady_clock::now() - start)
  24937. .count(),
  24938. 6000);
  24939. EXPECT_FALSE(client.is_open());
  24940. }
  24941. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24942. Server svr;
  24943. check_pong_timeout_ends_read(svr, "ws");
  24944. }
  24945. #ifdef CPPHTTPLIB_SSL_ENABLED
  24946. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24947. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24948. ASSERT_TRUE(svr.is_valid());
  24949. check_pong_timeout_ends_read(svr, "wss");
  24950. }
  24951. #endif
  24952. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24953. Server svr;
  24954. svr.set_websocket_ping_interval(0);
  24955. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24956. std::string msg;
  24957. while (ws.read(msg)) {}
  24958. });
  24959. auto port = svr.bind_to_any_port("127.0.0.1");
  24960. std::thread t([&]() { svr.listen_after_bind(); });
  24961. auto se = detail::scope_exit([&] {
  24962. svr.stop();
  24963. t.join();
  24964. });
  24965. svr.wait_until_ready();
  24966. // Each Close payload and the reply it should get: an echo when valid, 1002
  24967. // otherwise.
  24968. std::vector<std::pair<std::string, std::string>> cases = {
  24969. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24970. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24971. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24972. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24973. };
  24974. // Also between the fragments of a message.
  24975. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24976. for (const auto &c : cases) {
  24977. auto sock = connect_raw_websocket(port, "/ws");
  24978. ASSERT_NE(INVALID_SOCKET, sock);
  24979. auto frames = prefix + masked_frame(0x88, c.first);
  24980. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24981. std::string reply;
  24982. char buf[256];
  24983. while (reply.size() < 2 + c.second.size()) {
  24984. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24985. if (n <= 0) { break; }
  24986. reply.append(buf, static_cast<size_t>(n));
  24987. }
  24988. detail::close_socket(sock);
  24989. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24990. c.second,
  24991. reply);
  24992. }
  24993. }
  24994. }
  24995. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24996. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24997. protected:
  24998. void SetUp() override {
  24999. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25000. SERVER_PRIVATE_KEY_FILE);
  25001. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25002. std::string msg;
  25003. ws::ReadResult ret;
  25004. while ((ret = ws.read(msg))) {
  25005. if (ret == ws::Binary) {
  25006. ws.send(msg.data(), msg.size());
  25007. } else {
  25008. ws.send(msg);
  25009. }
  25010. }
  25011. });
  25012. port_ = server_->bind_to_any_port(HOST);
  25013. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25014. server_->wait_until_ready();
  25015. }
  25016. void TearDown() override {
  25017. server_->stop();
  25018. if (server_thread_.joinable()) { server_thread_.join(); }
  25019. }
  25020. std::unique_ptr<SSLServer> server_;
  25021. std::thread server_thread_;
  25022. int port_ = 0;
  25023. };
  25024. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25025. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25026. {
  25027. ws::WebSocketClient client(url);
  25028. client.enable_server_certificate_verification(false);
  25029. auto calls = 0;
  25030. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25031. calls++;
  25032. return false;
  25033. });
  25034. EXPECT_FALSE(client.connect());
  25035. EXPECT_GT(calls, 0);
  25036. }
  25037. {
  25038. ws::WebSocketClient client(url);
  25039. client.enable_server_certificate_verification(false);
  25040. client.set_session_verifier([](tls::session_t) {
  25041. return SSLVerifierResponse::CertificateRejected;
  25042. });
  25043. EXPECT_FALSE(client.connect());
  25044. }
  25045. {
  25046. ws::WebSocketClient client(url);
  25047. client.enable_server_certificate_verification(false);
  25048. client.set_session_verifier([](tls::session_t) {
  25049. return SSLVerifierResponse::CertificateAccepted;
  25050. });
  25051. EXPECT_TRUE(client.connect());
  25052. }
  25053. }
  25054. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25055. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25056. "/ws-echo");
  25057. client.enable_server_certificate_verification(false);
  25058. ASSERT_TRUE(client.connect());
  25059. ASSERT_TRUE(client.is_open());
  25060. ASSERT_TRUE(client.send("Hello WSS"));
  25061. std::string msg;
  25062. EXPECT_EQ(ws::Text, client.read(msg));
  25063. EXPECT_EQ("Hello WSS", msg);
  25064. client.close();
  25065. }
  25066. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25067. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25068. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25069. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25070. // client (without calling close() first) is the only path that runs
  25071. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25072. // bug exactly.
  25073. //
  25074. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25075. // when linked against an instrumented libssl; run under Valgrind to catch it
  25076. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25077. // suite (the freed session otherwise stalls on the close handshake) — this test
  25078. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25079. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25080. {
  25081. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25082. "/ws-echo");
  25083. client.enable_server_certificate_verification(false);
  25084. client.set_read_timeout(2, 0);
  25085. client.set_write_timeout(2, 0);
  25086. ASSERT_TRUE(client.connect());
  25087. ASSERT_TRUE(client.is_open());
  25088. ASSERT_TRUE(client.send("still open"));
  25089. // Intentionally do NOT call client.close(): leaving scope runs
  25090. // shutdown_and_close() with the WebSocket still open, which must send the
  25091. // close frame while the TLS session is still alive.
  25092. }
  25093. }
  25094. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25095. // shutdown_and_close() at the start of connect(), reproducing the same
  25096. // use-after-free within the test body rather than at scope exit. The second
  25097. // connect must succeed and echo, proving the close handshake ran over a live
  25098. // session. See the note above about memory-tool requirements.
  25099. TEST_F(WebSocketSSLIntegrationTest,
  25100. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25101. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25102. "/ws-echo");
  25103. client.enable_server_certificate_verification(false);
  25104. client.set_read_timeout(2, 0);
  25105. client.set_write_timeout(2, 0);
  25106. ASSERT_TRUE(client.connect());
  25107. ASSERT_TRUE(client.is_open());
  25108. ASSERT_TRUE(client.send("still open"));
  25109. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25110. // the still-open connection, which must not touch a freed TLS session.
  25111. ASSERT_TRUE(client.connect());
  25112. ASSERT_TRUE(client.is_open());
  25113. ASSERT_TRUE(client.send("after reconnect"));
  25114. std::string msg;
  25115. EXPECT_EQ(ws::Text, client.read(msg));
  25116. EXPECT_EQ("after reconnect", msg);
  25117. client.close();
  25118. }
  25119. #endif
  25120. #ifdef CPPHTTPLIB_SSL_ENABLED
  25121. class WebSocketSSLCATest : public ::testing::Test {
  25122. protected:
  25123. void SetUp() override {
  25124. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25125. SERVER_PRIVATE_KEY_FILE);
  25126. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25127. std::string msg;
  25128. while (ws.read(msg)) {
  25129. ws.send(msg);
  25130. }
  25131. });
  25132. port_ = server_->bind_to_any_port("127.0.0.1");
  25133. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25134. server_->wait_until_ready();
  25135. }
  25136. void TearDown() override {
  25137. server_->stop();
  25138. if (server_thread_.joinable()) { server_thread_.join(); }
  25139. }
  25140. std::string url() const {
  25141. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25142. }
  25143. std::unique_ptr<SSLServer> server_;
  25144. std::thread server_thread_;
  25145. int port_ = 0;
  25146. };
  25147. // A custom CA loaded as PEM verifies the server with full certificate
  25148. // verification enabled
  25149. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25150. ws::WebSocketClient client(url());
  25151. std::string cert;
  25152. read_file(SERVER_CERT2_FILE, cert);
  25153. client.load_ca_cert_store(cert.c_str(), cert.size());
  25154. ASSERT_TRUE(client.connect());
  25155. ASSERT_TRUE(client.send("hello"));
  25156. std::string msg;
  25157. EXPECT_EQ(ws::Text, client.read(msg));
  25158. EXPECT_EQ("hello", msg);
  25159. client.close();
  25160. }
  25161. // A custom CA that does not cover the server must fail verification (the
  25162. // custom CA is exclusive; system certs are not loaded alongside it)
  25163. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25164. ws::WebSocketClient client(url());
  25165. std::string cert;
  25166. read_file(CLIENT_CA_CERT_FILE, cert);
  25167. client.load_ca_cert_store(cert.c_str(), cert.size());
  25168. auto res = client.connect();
  25169. ASSERT_FALSE(res);
  25170. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25171. EXPECT_EQ(-1, res.status());
  25172. EXPECT_NE(0u, res.ssl_backend_error());
  25173. }
  25174. // The same CA as a file path rather than PEM in memory
  25175. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25176. ws::WebSocketClient client(url());
  25177. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25178. ASSERT_TRUE(client.connect());
  25179. ASSERT_TRUE(client.send("hello"));
  25180. std::string msg;
  25181. EXPECT_EQ(ws::Text, client.read(msg));
  25182. EXPECT_EQ("hello", msg);
  25183. client.close();
  25184. }
  25185. // ...and a CA file that does not cover the server still fails, so it is the
  25186. // path above that decides the outcome
  25187. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25188. ws::WebSocketClient client(url());
  25189. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25190. ASSERT_FALSE(client.connect());
  25191. }
  25192. // Regression test: reconnecting with a native custom CA store used to reuse
  25193. // a store handle the previous TLS context had already freed (use-after-free
  25194. // under the OpenSSL backend). The context now lives as long as the client.
  25195. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25196. ws::WebSocketClient client(url());
  25197. std::string cert;
  25198. read_file(SERVER_CERT2_FILE, cert);
  25199. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25200. ASSERT_TRUE(client.connect());
  25201. client.close();
  25202. ASSERT_TRUE(client.connect());
  25203. ASSERT_TRUE(client.send("again"));
  25204. std::string msg;
  25205. EXPECT_EQ(ws::Text, client.read(msg));
  25206. EXPECT_EQ("again", msg);
  25207. client.close();
  25208. }
  25209. // Regression test: a certificate with a trusted chain but no identity match
  25210. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25211. // verification entirely for IP hosts, so this connection succeeded there.
  25212. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25213. // chain verification while the identity check must still fail.
  25214. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25215. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25216. ASSERT_TRUE(svr.is_valid());
  25217. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25218. std::string msg;
  25219. while (ws.read(msg)) {
  25220. ws.send(msg);
  25221. }
  25222. });
  25223. auto port = svr.bind_to_any_port("127.0.0.1");
  25224. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25225. auto se = detail::scope_exit([&] {
  25226. svr.stop();
  25227. t.join();
  25228. });
  25229. svr.wait_until_ready();
  25230. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25231. "/echo");
  25232. std::string cert;
  25233. read_file(SERVER_CERT_FILE, cert);
  25234. client.load_ca_cert_store(cert.c_str(), cert.size());
  25235. ASSERT_FALSE(client.connect());
  25236. }
  25237. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25238. // SNI, so nothing binds the host name to the TLS session. These bind the
  25239. // server to "localhost" instead, the only shape that exercises the SNI and
  25240. // hostname-verification path with certificate verification left enabled.
  25241. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25242. protected:
  25243. void Start(const char *cert_file) {
  25244. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25245. SERVER_PRIVATE_KEY_FILE);
  25246. ASSERT_TRUE(server_->is_valid());
  25247. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25248. std::string msg;
  25249. while (ws.read(msg)) {
  25250. ws.send(msg);
  25251. }
  25252. });
  25253. port_ = server_->bind_to_any_port("localhost");
  25254. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25255. server_->wait_until_ready();
  25256. }
  25257. void TearDown() override {
  25258. if (server_) { server_->stop(); }
  25259. if (server_thread_.joinable()) { server_thread_.join(); }
  25260. }
  25261. std::string url() const {
  25262. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25263. }
  25264. std::unique_ptr<SSLServer> server_;
  25265. std::thread server_thread_;
  25266. int port_ = 0;
  25267. };
  25268. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25269. // out and the connection is usable
  25270. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25271. Start(SERVER_CERT2_FILE);
  25272. ws::WebSocketClient client(url());
  25273. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25274. ASSERT_TRUE(client.connect());
  25275. ASSERT_TRUE(client.send("hello"));
  25276. std::string msg;
  25277. EXPECT_EQ(ws::Text, client.read(msg));
  25278. EXPECT_EQ("hello", msg);
  25279. client.close();
  25280. }
  25281. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25282. // while the identity check must still reject "localhost"
  25283. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25284. Start(SERVER_CERT_FILE);
  25285. ws::WebSocketClient client(url());
  25286. client.set_ca_cert_path(SERVER_CERT_FILE);
  25287. auto res = client.connect();
  25288. ASSERT_FALSE(res);
  25289. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25290. EXPECT_EQ(-1, res.status());
  25291. }
  25292. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25293. // disabled: the chain is still checked, only the identity check is skipped
  25294. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25295. Start(SERVER_CERT_FILE);
  25296. ws::WebSocketClient client(url());
  25297. client.set_ca_cert_path(SERVER_CERT_FILE);
  25298. client.enable_server_hostname_verification(false);
  25299. ASSERT_TRUE(client.connect());
  25300. ASSERT_TRUE(client.send("hello"));
  25301. std::string msg;
  25302. EXPECT_EQ(ws::Text, client.read(msg));
  25303. EXPECT_EQ("hello", msg);
  25304. client.close();
  25305. }
  25306. // A CA that did not sign the server certificate fails the chain, even though
  25307. // the name would match
  25308. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25309. Start(SERVER_CERT2_FILE);
  25310. ws::WebSocketClient client(url());
  25311. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25312. ASSERT_FALSE(client.connect());
  25313. }
  25314. // With verification disabled, neither the chain nor the name is checked
  25315. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25316. Start(SERVER_CERT_FILE);
  25317. ws::WebSocketClient client(url());
  25318. client.enable_server_certificate_verification(false);
  25319. ASSERT_TRUE(client.connect());
  25320. ASSERT_TRUE(client.send("hello"));
  25321. std::string msg;
  25322. EXPECT_EQ(ws::Text, client.read(msg));
  25323. EXPECT_EQ("hello", msg);
  25324. client.close();
  25325. }
  25326. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25327. protected:
  25328. void SetUp() override {
  25329. server_ = httplib::detail::make_unique<SSLServer>(
  25330. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25331. ASSERT_TRUE(server_->is_valid());
  25332. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25333. std::string msg;
  25334. while (ws.read(msg)) {
  25335. ws.send(msg);
  25336. }
  25337. });
  25338. port_ = server_->bind_to_any_port("localhost");
  25339. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25340. server_->wait_until_ready();
  25341. }
  25342. void TearDown() override {
  25343. server_->stop();
  25344. if (server_thread_.joinable()) { server_thread_.join(); }
  25345. }
  25346. std::string url() const {
  25347. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25348. }
  25349. void ConnectWithClientCert(const std::string &client_cert_file,
  25350. const std::string &client_private_key_file,
  25351. const char *private_key_password) {
  25352. std::string cert_pem, key_pem;
  25353. read_file(client_cert_file, cert_pem);
  25354. read_file(client_private_key_file, key_pem);
  25355. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25356. key_pem.c_str(), key_pem.size(),
  25357. private_key_password};
  25358. ConnectWithPem(pem);
  25359. }
  25360. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25361. ws::WebSocketClient client(url(), pem);
  25362. ASSERT_TRUE(client.is_valid());
  25363. client.enable_server_certificate_verification(false);
  25364. ASSERT_TRUE(client.connect());
  25365. ASSERT_TRUE(client.send("hello"));
  25366. std::string msg;
  25367. EXPECT_EQ(ws::Text, client.read(msg));
  25368. EXPECT_EQ("hello", msg);
  25369. client.close();
  25370. }
  25371. std::unique_ptr<SSLServer> server_;
  25372. std::thread server_thread_;
  25373. int port_ = 0;
  25374. };
  25375. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25376. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25377. }
  25378. // Control for the tests above: the fixture's server really does require a
  25379. // client certificate, so it is the PEM the constructor installed that decides
  25380. // the outcome.
  25381. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25382. ws::WebSocketClient client(url());
  25383. ASSERT_TRUE(client.is_valid());
  25384. client.enable_server_certificate_verification(false);
  25385. EXPECT_FALSE(client.connect());
  25386. }
  25387. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25388. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25389. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25390. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25391. }
  25392. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25393. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25394. std::string cert_pem, key_pem;
  25395. read_file(CLIENT_CERT_FILE, cert_pem);
  25396. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25397. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25398. std::vector<char> key(key_pem.begin(), key_pem.end());
  25399. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25400. key.size(), nullptr};
  25401. ConnectWithPem(pem);
  25402. }
  25403. #endif
  25404. #if !defined(_WIN32)
  25405. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25406. auto secret_dir = std::string("./symlink_test_secret");
  25407. auto served_dir = std::string("./symlink_test_served");
  25408. auto secret_file = secret_dir + "/secret.txt";
  25409. auto symlink_path = served_dir + "/escape";
  25410. // Setup: create directories and files
  25411. mkdir(secret_dir.c_str(), 0755);
  25412. mkdir(served_dir.c_str(), 0755);
  25413. {
  25414. std::ofstream ofs(secret_file);
  25415. ofs << "SECRET_DATA";
  25416. }
  25417. // Create symlink using absolute path so it resolves correctly
  25418. #ifdef PATH_MAX
  25419. char abs_secret[PATH_MAX];
  25420. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25421. #else
  25422. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25423. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25424. ASSERT_NE(nullptr, abs_secret);
  25425. #endif
  25426. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25427. auto se = detail::scope_exit([&] {
  25428. unlink(symlink_path.c_str());
  25429. unlink(secret_file.c_str());
  25430. rmdir(served_dir.c_str());
  25431. rmdir(secret_dir.c_str());
  25432. });
  25433. Server svr;
  25434. svr.set_mount_point("/", served_dir);
  25435. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25436. auto se2 = detail::scope_exit([&] {
  25437. svr.stop();
  25438. listen_thread.join();
  25439. });
  25440. svr.wait_until_ready();
  25441. Client cli("localhost", PORT);
  25442. // Symlink pointing outside base dir should be blocked
  25443. auto res = cli.Get("/escape/secret.txt");
  25444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25445. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25446. }
  25447. #endif
  25448. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25449. // "GET /smuggled" request), reads the first response, and only then sends the
  25450. // embedded request as the body. Returns how many times /smuggled ran.
  25451. //
  25452. // The body is sent AFTER receiving the first response (as in the original
  25453. // PoC) so that the stream_line_reader cannot buffer it together with the
  25454. // headers of the first request.
  25455. static int count_smuggled_requests(const std::string &outer_head,
  25456. std::string &first_response) {
  25457. Server svr;
  25458. svr.set_mount_point("/", "./www");
  25459. std::atomic<int> smuggled_count(0);
  25460. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25461. smuggled_count++;
  25462. res.set_content("oops", "text/plain");
  25463. });
  25464. svr.Post("/post", [&](const Request &req, Response &res) {
  25465. res.set_content(req.body, "text/plain");
  25466. });
  25467. auto port = svr.bind_to_any_port("localhost");
  25468. thread t = thread([&] { svr.listen_after_bind(); });
  25469. auto se = detail::scope_exit([&] {
  25470. svr.stop();
  25471. t.join();
  25472. });
  25473. svr.wait_until_ready();
  25474. auto error = Error::Success;
  25475. auto sock = detail::create_client_socket(
  25476. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25477. /*connection_timeout_sec=*/2, 0,
  25478. /*read_timeout_sec=*/2, 0,
  25479. /*write_timeout_sec=*/2, 0, std::string(), error);
  25480. EXPECT_NE(INVALID_SOCKET, sock);
  25481. if (sock == INVALID_SOCKET) { return -1; }
  25482. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25483. // The "smuggled" request will be sent as the body of the outer request
  25484. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25485. "Host: localhost\r\n"
  25486. "Connection: close\r\n"
  25487. "\r\n";
  25488. auto head = outer_head;
  25489. auto len = std::to_string(smuggled.size());
  25490. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25491. pos = head.find("{len}", pos + len.size())) {
  25492. head.replace(pos, 5, len);
  25493. }
  25494. // Step 1: Send only the outer request headers (no body yet)
  25495. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25496. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25497. // Step 2: Read the first response
  25498. char buf[4096];
  25499. for (;;) {
  25500. auto n = recv(sock, buf, sizeof(buf), 0);
  25501. if (n <= 0) break;
  25502. first_response.append(buf, static_cast<size_t>(n));
  25503. // Stop once we have a complete response (headers + body)
  25504. auto hdr_end = first_response.find("\r\n\r\n");
  25505. if (hdr_end != std::string::npos) {
  25506. // Check for Content-Length to know when the body is complete
  25507. auto cl_pos = first_response.find("Content-Length:");
  25508. if (cl_pos != std::string::npos) {
  25509. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25510. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25511. auto cl = std::stoul(
  25512. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25513. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25514. } else {
  25515. break; // No Content-Length, assume headers-only response
  25516. }
  25517. }
  25518. }
  25519. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25520. // vulnerable server the keep-alive loop reads this as a second request. The
  25521. // server may already have closed the connection, so the result is ignored.
  25522. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25523. // Half-close so that a server which drained the body sees EOF and closes,
  25524. // instead of the read below waiting for the read timeout.
  25525. #ifdef _WIN32
  25526. ::shutdown(sock, SD_SEND);
  25527. #else
  25528. ::shutdown(sock, SHUT_WR);
  25529. #endif
  25530. // Step 4: Read until the server closes the connection
  25531. for (;;) {
  25532. auto n = recv(sock, buf, sizeof(buf), 0);
  25533. if (n <= 0) break;
  25534. }
  25535. return smuggled_count.load();
  25536. }
  25537. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25538. // A GET request with Content-Length to a static file handler must have its
  25539. // body drained before the keep-alive connection is reused. Otherwise the
  25540. // unread body bytes are interpreted as the next HTTP request.
  25541. std::string first_response;
  25542. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25543. "Host: localhost\r\n"
  25544. "Content-Length: {len}\r\n"
  25545. "\r\n",
  25546. first_response));
  25547. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25548. }
  25549. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25550. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25551. // be answered with 400 and the connection closed. Treating it as "no body"
  25552. // leaves the body to be parsed as the next request.
  25553. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25554. const char *targets[] = {
  25555. "GET /file", // handler that never reads the body
  25556. "GET /not-found", // no handler matches (404)
  25557. "POST /post", // handler that reads the body
  25558. };
  25559. for (auto target : targets) {
  25560. for (auto value : values) {
  25561. std::string first_response;
  25562. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25563. " HTTP/1.1\r\n"
  25564. "Host: localhost\r\n"
  25565. "Content-Length: " +
  25566. value + "\r\n\r\n",
  25567. first_response))
  25568. << target << " with Content-Length: " << value;
  25569. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25570. << target << " with Content-Length: " << value;
  25571. }
  25572. }
  25573. }
  25574. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25575. // A 400 for an unparseable request line leaves the rest of the message
  25576. // unread, so the connection must be closed rather than reused.
  25577. std::string first_response;
  25578. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25579. "Host: localhost\r\n"
  25580. "Content-Length: {len}\r\n"
  25581. "\r\n",
  25582. first_response));
  25583. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25584. }
  25585. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25586. // Same as above for a header block that fails to parse.
  25587. std::string first_response;
  25588. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25589. "Host: localhost\r\n"
  25590. "Bad Header\r\n"
  25591. "Content-Length: {len}\r\n"
  25592. "\r\n",
  25593. first_response));
  25594. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25595. }
  25596. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25597. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25598. // server must not read another request on that connection, even when the
  25599. // request had no body to drain.
  25600. std::string first_response;
  25601. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25602. "Host: localhost\r\n"
  25603. "\r\n",
  25604. first_response));
  25605. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25606. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25607. }
  25608. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25609. // A content reader that stops early leaves the stream inside the body.
  25610. // Draining the whole Content-Length from there, or reading the body again,
  25611. // reads into the next request, and whatever follows is parsed as a request
  25612. // of its own.
  25613. Server svr;
  25614. std::atomic<int> smuggled_count(0);
  25615. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25616. svr.Post("/upload", [](const Request &req, Response &res,
  25617. const ContentReader &content_reader) {
  25618. // Stop at the last chunk, so the whole body has been read however it
  25619. // arrives.
  25620. auto length = req.get_header_value_u64("Content-Length");
  25621. size_t total = 0;
  25622. auto consumed = content_reader([&](const char *, size_t n) {
  25623. total += n;
  25624. return total < length;
  25625. });
  25626. EXPECT_FALSE(consumed);
  25627. if (req.has_param("retry")) {
  25628. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25629. }
  25630. // Replace the 400 the aborted read set, which would close the connection.
  25631. res.set_redirect("/done");
  25632. });
  25633. auto port = svr.bind_to_any_port(HOST);
  25634. thread t = thread([&] { svr.listen_after_bind(); });
  25635. auto se = detail::scope_exit([&] {
  25636. svr.stop();
  25637. t.join();
  25638. });
  25639. svr.wait_until_ready();
  25640. // A front end sees the second request as a POST whose body is the GET. The
  25641. // first body is as long as the POST's headers, so draining it again reads
  25642. // exactly those and leaves the GET to be parsed next.
  25643. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25644. "Host: localhost\r\n"
  25645. "\r\n";
  25646. std::string second_head = "POST /post HTTP/1.1\r\n"
  25647. "Host: localhost\r\n"
  25648. "Content-Length: " +
  25649. std::to_string(inner.size()) +
  25650. "\r\n"
  25651. "\r\n";
  25652. for (auto target : {"/upload", "/upload?retry"}) {
  25653. smuggled_count = 0;
  25654. std::string request = "POST " + std::string(target) +
  25655. " HTTP/1.1\r\n"
  25656. "Host: localhost\r\n"
  25657. "Content-Length: " +
  25658. std::to_string(second_head.size()) +
  25659. "\r\n"
  25660. "\r\n" +
  25661. std::string(second_head.size(), 'A') + second_head +
  25662. inner;
  25663. std::string response;
  25664. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25665. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25666. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25667. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25668. EXPECT_EQ(0, smuggled_count.load()) << target;
  25669. }
  25670. }
  25671. // An error response closes the connection anyway, so the body is left unread
  25672. // with a redirect, such as one to a login page.
  25673. static void serve_redirects(Server &svr,
  25674. const std::function<void(int)> &client) {
  25675. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25676. res.set_redirect("/login");
  25677. return Server::HandlerResponse::Handled;
  25678. });
  25679. auto port = svr.bind_to_any_port(HOST);
  25680. ASSERT_GT(port, 0);
  25681. thread t = thread([&] { svr.listen_after_bind(); });
  25682. auto se = detail::scope_exit([&] {
  25683. svr.stop();
  25684. t.join();
  25685. ASSERT_FALSE(svr.is_running());
  25686. });
  25687. svr.wait_until_ready();
  25688. client(port);
  25689. }
  25690. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25691. Server svr;
  25692. serve_redirects(svr, [](int port) {
  25693. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25694. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25695. std::to_string(body.size()) + "\r\n\r\n" + body +
  25696. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25697. std::string resp;
  25698. ASSERT_TRUE(send_request(1, req, &resp, port));
  25699. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25700. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25701. });
  25702. }
  25703. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25704. Server svr;
  25705. svr.set_read_timeout(0, 200000);
  25706. serve_redirects(svr, [](int port) {
  25707. // A byte every 100 ms keeps each read within the read timeout, but not the
  25708. // body as a whole, so the server closes and the bytes sent after that fail.
  25709. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25710. "Content-Length: 10\r\n\r\n"};
  25711. parts.resize(11, "x");
  25712. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25713. });
  25714. }
  25715. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25716. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25717. // must be rejected with 400 Bad Request.
  25718. Server svr;
  25719. svr.Post("/test", [&](const Request &, Response &res) {
  25720. res.set_content("ok", "text/plain");
  25721. });
  25722. thread t = thread([&] { svr.listen(HOST, PORT); });
  25723. auto se = detail::scope_exit([&] {
  25724. svr.stop();
  25725. t.join();
  25726. ASSERT_FALSE(svr.is_running());
  25727. });
  25728. svr.wait_until_ready();
  25729. // Exact "chunked"
  25730. {
  25731. auto req = "POST /test HTTP/1.1\r\n"
  25732. "Host: localhost\r\n"
  25733. "Content-Length: 5\r\n"
  25734. "Transfer-Encoding: chunked\r\n"
  25735. "Connection: close\r\n"
  25736. "\r\n"
  25737. "hello";
  25738. std::string response;
  25739. ASSERT_TRUE(send_request(1, req, &response));
  25740. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25741. response.substr(0, response.find("\r\n")));
  25742. }
  25743. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25744. {
  25745. auto req = "POST /test HTTP/1.1\r\n"
  25746. "Host: localhost\r\n"
  25747. "Content-Length: 5\r\n"
  25748. "Transfer-Encoding: gzip, chunked\r\n"
  25749. "Connection: close\r\n"
  25750. "\r\n"
  25751. "hello";
  25752. std::string response;
  25753. ASSERT_TRUE(send_request(1, req, &response));
  25754. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25755. response.substr(0, response.find("\r\n")));
  25756. }
  25757. }
  25758. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25759. Server svr;
  25760. svr.Post("/test", [&](const Request &, Response &res) {
  25761. res.set_content("ok", "text/plain");
  25762. });
  25763. thread t = thread([&] { svr.listen(HOST, PORT); });
  25764. auto se = detail::scope_exit([&] {
  25765. svr.stop();
  25766. t.join();
  25767. ASSERT_FALSE(svr.is_running());
  25768. });
  25769. svr.wait_until_ready();
  25770. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25771. // length cannot be determined, so the server must answer 400 and close
  25772. // rather than treat the request as bodyless and leave the body in the
  25773. // socket for the next request to pick up.
  25774. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25775. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25776. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25777. std::string response;
  25778. ASSERT_TRUE(send_request(1, req, &response));
  25779. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25780. response.substr(0, response.find("\r\n")))
  25781. << transfer_encoding;
  25782. }
  25783. // RFC 9110 5.3: the codings may also be split across several
  25784. // Transfer-Encoding lines, which combine in the order they were received.
  25785. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25786. // just like the single-line "chunked, gzip" above.
  25787. {
  25788. auto req = "POST /test HTTP/1.1\r\n"
  25789. "Host: localhost\r\n"
  25790. "Transfer-Encoding: chunked\r\n"
  25791. "Transfer-Encoding: gzip\r\n"
  25792. "\r\n"
  25793. "0\r\n\r\n";
  25794. std::string response;
  25795. ASSERT_TRUE(send_request(1, req, &response));
  25796. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25797. response.substr(0, response.find("\r\n")));
  25798. }
  25799. }
  25800. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25801. Server svr;
  25802. svr.Post("/test", [&](const Request &, Response &res) {
  25803. res.set_content("ok", "text/plain");
  25804. });
  25805. auto port = svr.bind_to_any_port(HOST);
  25806. ASSERT_GT(port, 0);
  25807. thread t = thread([&] { svr.listen_after_bind(); });
  25808. auto se = detail::scope_exit([&] {
  25809. svr.stop();
  25810. t.join();
  25811. ASSERT_FALSE(svr.is_running());
  25812. });
  25813. svr.wait_until_ready();
  25814. for (auto transfer_encoding :
  25815. {"Transfer-Encoding: gzip, chunked\r\n",
  25816. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25817. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25818. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25819. transfer_encoding + "\r\n0\r\n\r\n";
  25820. std::string response;
  25821. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25822. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25823. response.substr(0, response.find("\r\n")))
  25824. << transfer_encoding;
  25825. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25826. << transfer_encoding;
  25827. }
  25828. }
  25829. // Regression for issue #2450: a DELETE without Content-Length on a
  25830. // keep-alive connection must not let the post-response drain consume the
  25831. // next request's bytes.
  25832. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25833. Server svr;
  25834. std::atomic<int> delete_count(0);
  25835. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25836. delete_count++;
  25837. res.status = StatusCode::NoContent_204;
  25838. });
  25839. auto port = svr.bind_to_any_port(HOST);
  25840. thread t = thread([&] { svr.listen_after_bind(); });
  25841. auto se = detail::scope_exit([&] {
  25842. svr.stop();
  25843. t.join();
  25844. });
  25845. svr.wait_until_ready();
  25846. auto error = Error::Success;
  25847. auto sock = detail::create_client_socket(
  25848. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25849. /*connection_timeout_sec=*/2, 0,
  25850. /*read_timeout_sec=*/2, 0,
  25851. /*write_timeout_sec=*/2, 0, std::string(), error);
  25852. ASSERT_NE(INVALID_SOCKET, sock);
  25853. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25854. auto send_request_and_read_response = [&](const std::string &req,
  25855. std::string &out) -> bool {
  25856. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25857. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25858. char buf[4096];
  25859. for (;;) {
  25860. auto n = recv(sock, buf, sizeof(buf), 0);
  25861. if (n <= 0) { return !out.empty(); }
  25862. out.append(buf, static_cast<size_t>(n));
  25863. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25864. }
  25865. };
  25866. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25867. "Host: localhost\r\n"
  25868. "\r\n";
  25869. std::string resp1;
  25870. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25871. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25872. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25873. "Host: localhost\r\n"
  25874. "Connection: close\r\n"
  25875. "\r\n";
  25876. std::string resp2;
  25877. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25878. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25879. EXPECT_EQ(2, delete_count.load());
  25880. }
  25881. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25882. Server svr;
  25883. svr.Post("/ingest", [&](const Request &, Response &res,
  25884. const ContentReader &content_reader) {
  25885. auto consumed = content_reader([](const char *, size_t) { return false; });
  25886. EXPECT_FALSE(consumed);
  25887. res.status = StatusCode::Conflict_409;
  25888. res.set_header("Connection", "close");
  25889. });
  25890. auto port = svr.bind_to_any_port(HOST);
  25891. thread t = thread([&] { svr.listen_after_bind(); });
  25892. auto se = detail::scope_exit([&] {
  25893. svr.stop();
  25894. t.join();
  25895. });
  25896. svr.wait_until_ready();
  25897. auto error = Error::Success;
  25898. auto sock = detail::create_client_socket(
  25899. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25900. /*connection_timeout_sec=*/2, 0,
  25901. /*read_timeout_sec=*/1, 0,
  25902. /*write_timeout_sec=*/2, 0, std::string(), error);
  25903. ASSERT_NE(INVALID_SOCKET, sock);
  25904. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25905. std::string request = "POST /ingest HTTP/1.1\r\n"
  25906. "Host: localhost\r\n"
  25907. "Transfer-Encoding: chunked\r\n"
  25908. "\r\n"
  25909. "4\r\n"
  25910. "data\r\n";
  25911. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25912. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25913. std::string response;
  25914. ssize_t received = 0;
  25915. do {
  25916. char buf[4096];
  25917. received = recv(sock, buf, sizeof(buf), 0);
  25918. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25919. } while (received > 0);
  25920. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25921. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25922. EXPECT_EQ(0, received);
  25923. }
  25924. namespace no_proxy_test {
  25925. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25926. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25927. // calling listen().
  25928. class ScopedServer {
  25929. public:
  25930. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25931. ~ScopedServer() {
  25932. svr_.stop();
  25933. if (th_.joinable()) { th_.join(); }
  25934. }
  25935. Server &svr() { return svr_; }
  25936. int port() const { return port_; }
  25937. void listen() {
  25938. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25939. svr_.wait_until_ready();
  25940. }
  25941. private:
  25942. Server svr_;
  25943. std::thread th_;
  25944. int port_ = 0;
  25945. };
  25946. class ProxyAndTargetServers {
  25947. public:
  25948. ProxyAndTargetServers() {
  25949. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25950. proxy_hits_++;
  25951. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25952. res.set_content("via-proxy", "text/plain");
  25953. });
  25954. target_.Get(".*", [this](const Request &req, Response &res) {
  25955. target_hits_++;
  25956. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25957. res.set_content("direct", "text/plain");
  25958. });
  25959. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25960. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25961. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25962. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25963. proxy_mock_.wait_until_ready();
  25964. target_.wait_until_ready();
  25965. }
  25966. ~ProxyAndTargetServers() {
  25967. proxy_mock_.stop();
  25968. target_.stop();
  25969. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25970. if (target_thread_.joinable()) { target_thread_.join(); }
  25971. }
  25972. Server &proxy_mock() { return proxy_mock_; }
  25973. Server &target() { return target_; }
  25974. int proxy_port() const { return proxy_port_; }
  25975. int target_port() const { return target_port_; }
  25976. int proxy_hits() const { return proxy_hits_.load(); }
  25977. int target_hits() const { return target_hits_.load(); }
  25978. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25979. void reset_counters() {
  25980. proxy_hits_ = 0;
  25981. target_hits_ = 0;
  25982. last_had_proxy_authz_ = false;
  25983. }
  25984. private:
  25985. Server proxy_mock_;
  25986. Server target_;
  25987. std::thread proxy_thread_;
  25988. std::thread target_thread_;
  25989. int proxy_port_ = 0;
  25990. int target_port_ = 0;
  25991. std::atomic<int> proxy_hits_{0};
  25992. std::atomic<int> target_hits_{0};
  25993. std::atomic<bool> last_had_proxy_authz_{false};
  25994. };
  25995. inline std::unique_ptr<Client> make_client(const std::string &host,
  25996. ProxyAndTargetServers &s) {
  25997. auto cli = detail::make_unique<Client>(host, s.target_port());
  25998. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25999. cli->set_proxy("127.0.0.1", s.proxy_port());
  26000. return cli;
  26001. }
  26002. } // namespace no_proxy_test
  26003. using no_proxy_test::make_client;
  26004. using no_proxy_test::ProxyAndTargetServers;
  26005. // A stream request carries the credentials a buffered request does
  26006. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26007. no_proxy_test::ScopedServer origin;
  26008. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26009. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26010. });
  26011. origin.listen();
  26012. Client cli("127.0.0.1", origin.port());
  26013. cli.set_basic_auth("user", "pass");
  26014. auto handle = cli.open_stream("GET", "/x");
  26015. ASSERT_TRUE(handle.is_valid());
  26016. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26017. Client bearer("127.0.0.1", origin.port());
  26018. bearer.set_bearer_token_auth("tok");
  26019. auto handle2 = bearer.open_stream("GET", "/x");
  26020. ASSERT_TRUE(handle2.is_valid());
  26021. EXPECT_EQ("Bearer tok", read_all(handle2));
  26022. }
  26023. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26024. // takes its own credentials, as for a buffered request
  26025. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26026. std::string target, authz, proxy_authz;
  26027. no_proxy_test::ScopedServer proxy;
  26028. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26029. target = req.target;
  26030. authz = req.get_header_value("Authorization");
  26031. proxy_authz = req.get_header_value("Proxy-Authorization");
  26032. res.set_content("ok", "text/plain");
  26033. });
  26034. proxy.listen();
  26035. Client cli("origin.example", 8080);
  26036. cli.set_proxy("127.0.0.1", proxy.port());
  26037. cli.set_proxy_basic_auth("puser", "ppass");
  26038. cli.set_basic_auth("user", "pass");
  26039. auto handle = cli.open_stream("GET", "/x");
  26040. ASSERT_TRUE(handle.is_valid());
  26041. EXPECT_EQ("ok", read_all(handle));
  26042. EXPECT_EQ("http://origin.example:8080/x", target);
  26043. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26044. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26045. }
  26046. // In absolute-form the path follows the authority, so a path that does not
  26047. // begin with '/' would make the proxy connect to another host
  26048. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26049. std::vector<std::string> targets;
  26050. no_proxy_test::ScopedServer proxy;
  26051. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26052. targets.push_back(req.target);
  26053. res.set_content("ok", "text/plain");
  26054. });
  26055. proxy.listen();
  26056. Client cli("origin.example", 8080);
  26057. cli.set_proxy("127.0.0.1", proxy.port());
  26058. cli.set_basic_auth("user", "pass");
  26059. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26060. auto res = cli.Get(path);
  26061. EXPECT_FALSE(res) << path;
  26062. auto handle = cli.open_stream("GET", path);
  26063. EXPECT_FALSE(handle.is_valid()) << path;
  26064. }
  26065. EXPECT_TRUE(targets.empty());
  26066. auto res = cli.Get("/x");
  26067. ASSERT_TRUE(res);
  26068. ASSERT_EQ(1u, targets.size());
  26069. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26070. }
  26071. TEST(NoProxyTest, ExactHostnameBypasses) {
  26072. ProxyAndTargetServers s;
  26073. auto cli = make_client("example.com", s);
  26074. cli->set_no_proxy({"example.com"});
  26075. auto res = cli->Get("/");
  26076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26077. EXPECT_EQ(0, s.proxy_hits());
  26078. EXPECT_EQ(1, s.target_hits());
  26079. }
  26080. TEST(NoProxyTest, SubdomainBypasses) {
  26081. ProxyAndTargetServers s;
  26082. auto cli = make_client("foo.example.com", s);
  26083. cli->set_no_proxy({"example.com"});
  26084. auto res = cli->Get("/");
  26085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26086. EXPECT_EQ(0, s.proxy_hits());
  26087. EXPECT_EQ(1, s.target_hits());
  26088. }
  26089. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26090. // Regression guard: "evilexample.com" must not be considered a subdomain
  26091. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26092. // check would let traffic bypass the proxy and leak credentials direct
  26093. // to the attacker host.
  26094. ProxyAndTargetServers s;
  26095. auto cli = make_client("evilexample.com", s);
  26096. cli->set_no_proxy({"example.com"});
  26097. auto res = cli->Get("/");
  26098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26099. EXPECT_GE(s.proxy_hits(), 1);
  26100. EXPECT_EQ(0, s.target_hits());
  26101. }
  26102. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26103. ProxyAndTargetServers s;
  26104. auto cli = make_client("example.com.evil.com", s);
  26105. cli->set_no_proxy({"example.com"});
  26106. auto res = cli->Get("/");
  26107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26108. EXPECT_GE(s.proxy_hits(), 1);
  26109. EXPECT_EQ(0, s.target_hits());
  26110. }
  26111. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26112. ProxyAndTargetServers s;
  26113. auto cli = make_client("example.com", s);
  26114. cli->set_no_proxy({".example.com"});
  26115. auto res = cli->Get("/");
  26116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26117. EXPECT_EQ(0, s.proxy_hits());
  26118. EXPECT_EQ(1, s.target_hits());
  26119. }
  26120. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26121. ProxyAndTargetServers s;
  26122. auto cli = make_client("Example.COM", s);
  26123. cli->set_no_proxy({"EXAMPLE.com"});
  26124. auto res = cli->Get("/");
  26125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26126. EXPECT_EQ(0, s.proxy_hits());
  26127. EXPECT_EQ(1, s.target_hits());
  26128. }
  26129. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26130. ProxyAndTargetServers s;
  26131. auto cli = make_client("example.com.", s);
  26132. cli->set_no_proxy({"example.com"});
  26133. auto res = cli->Get("/");
  26134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26135. EXPECT_EQ(0, s.proxy_hits());
  26136. EXPECT_EQ(1, s.target_hits());
  26137. }
  26138. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26139. // Trailing dots must be normalized on BOTH sides — host and entry.
  26140. // An implementation that only strips the host-side trailing dot would
  26141. // fail to match host "example.com" against entry "example.com." because
  26142. // a literal substring search would compare 11 chars against 12.
  26143. ProxyAndTargetServers s;
  26144. auto cli = make_client("example.com", s);
  26145. cli->set_no_proxy({"example.com."});
  26146. auto res = cli->Get("/");
  26147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26148. EXPECT_EQ(0, s.proxy_hits());
  26149. EXPECT_EQ(1, s.target_hits());
  26150. }
  26151. TEST(NoProxyTest, WildcardBypassesEverything) {
  26152. ProxyAndTargetServers s;
  26153. auto cli = make_client("anything.invalid.test", s);
  26154. cli->set_no_proxy({"*"});
  26155. auto res = cli->Get("/");
  26156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26157. EXPECT_EQ(0, s.proxy_hits());
  26158. EXPECT_EQ(1, s.target_hits());
  26159. }
  26160. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26161. ProxyAndTargetServers s;
  26162. Client cli("127.0.0.1", s.target_port());
  26163. cli.set_proxy("127.0.0.1", s.proxy_port());
  26164. cli.set_no_proxy({"127.0.0.1"});
  26165. auto res = cli.Get("/");
  26166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26167. EXPECT_EQ(0, s.proxy_hits());
  26168. EXPECT_EQ(1, s.target_hits());
  26169. }
  26170. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26171. ProxyAndTargetServers s;
  26172. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26173. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26174. cli.set_proxy("127.0.0.1", s.proxy_port());
  26175. cli.set_no_proxy({"::1"});
  26176. auto res = cli.Get("/");
  26177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26178. EXPECT_EQ(0, s.proxy_hits());
  26179. EXPECT_EQ(1, s.target_hits());
  26180. }
  26181. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26182. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26183. // must still be recognized as IPv6 for CIDR matching. Implementations
  26184. // that detect IPv6 only when the host begins with '[' would parse the
  26185. // host as a hostname and miss the match.
  26186. ProxyAndTargetServers s;
  26187. Client cli("fe80::1", s.target_port());
  26188. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26189. cli.set_proxy("127.0.0.1", s.proxy_port());
  26190. cli.set_no_proxy({"fe80::/10"});
  26191. auto res = cli.Get("/");
  26192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26193. EXPECT_EQ(0, s.proxy_hits());
  26194. EXPECT_EQ(1, s.target_hits());
  26195. }
  26196. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26197. ProxyAndTargetServers s;
  26198. Client cli("::1", s.target_port());
  26199. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  26200. cli.set_proxy("127.0.0.1", s.proxy_port());
  26201. cli.set_no_proxy({"[::1]"});
  26202. auto res = cli.Get("/");
  26203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26204. EXPECT_EQ(0, s.proxy_hits());
  26205. EXPECT_EQ(1, s.target_hits());
  26206. }
  26207. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26208. ProxyAndTargetServers s;
  26209. Client cli("fe80::1", s.target_port());
  26210. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26211. cli.set_proxy("127.0.0.1", s.proxy_port());
  26212. cli.set_no_proxy({"[fe80::]/10"});
  26213. auto res = cli.Get("/");
  26214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26215. EXPECT_EQ(0, s.proxy_hits());
  26216. EXPECT_EQ(1, s.target_hits());
  26217. }
  26218. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26219. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26220. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26221. // tricks via address-family conversion.
  26222. ProxyAndTargetServers s;
  26223. Client cli("::ffff:127.0.0.1", s.target_port());
  26224. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26225. cli.set_proxy("127.0.0.1", s.proxy_port());
  26226. cli.set_no_proxy({"127.0.0.1"});
  26227. auto res = cli.Get("/");
  26228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26229. EXPECT_GE(s.proxy_hits(), 1);
  26230. EXPECT_EQ(0, s.target_hits());
  26231. }
  26232. TEST(NoProxyTest, IPv4CidrMatch) {
  26233. ProxyAndTargetServers s;
  26234. Client cli("127.0.0.1", s.target_port());
  26235. cli.set_proxy("127.0.0.1", s.proxy_port());
  26236. cli.set_no_proxy({"127.0.0.0/8"});
  26237. auto res = cli.Get("/");
  26238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26239. EXPECT_EQ(0, s.proxy_hits());
  26240. EXPECT_EQ(1, s.target_hits());
  26241. }
  26242. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26243. ProxyAndTargetServers s;
  26244. Client cli("127.0.0.1", s.target_port());
  26245. cli.set_proxy("127.0.0.1", s.proxy_port());
  26246. cli.set_no_proxy({"10.0.0.0/8"});
  26247. auto res = cli.Get("/");
  26248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26249. EXPECT_GE(s.proxy_hits(), 1);
  26250. EXPECT_EQ(0, s.target_hits());
  26251. }
  26252. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26253. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26254. // IPv4 target matches.
  26255. ProxyAndTargetServers s;
  26256. Client cli("127.0.0.1", s.target_port());
  26257. cli.set_proxy("127.0.0.1", s.proxy_port());
  26258. cli.set_no_proxy({"0.0.0.0/0"});
  26259. auto res = cli.Get("/");
  26260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26261. EXPECT_EQ(0, s.proxy_hits());
  26262. EXPECT_EQ(1, s.target_hits());
  26263. }
  26264. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26265. ProxyAndTargetServers s;
  26266. Client cli("127.0.0.1", s.target_port());
  26267. cli.set_proxy("127.0.0.1", s.proxy_port());
  26268. cli.set_no_proxy({"127.0.0.1"});
  26269. auto res = cli.Get("/");
  26270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26271. EXPECT_EQ(0, s.proxy_hits());
  26272. EXPECT_EQ(1, s.target_hits());
  26273. }
  26274. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26275. ProxyAndTargetServers s;
  26276. Client cli("127.0.0.1", s.target_port());
  26277. cli.set_proxy("127.0.0.1", s.proxy_port());
  26278. cli.set_no_proxy({"127.0.0.0/33"});
  26279. auto res = cli.Get("/");
  26280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26281. EXPECT_GE(s.proxy_hits(), 1);
  26282. EXPECT_EQ(0, s.target_hits());
  26283. }
  26284. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26285. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26286. ProxyAndTargetServers s;
  26287. Client cli("127.0.0.1", s.target_port());
  26288. cli.set_proxy("127.0.0.1", s.proxy_port());
  26289. cli.set_no_proxy({"127.0.0.1/"});
  26290. auto res = cli.Get("/");
  26291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26292. EXPECT_GE(s.proxy_hits(), 1);
  26293. EXPECT_EQ(0, s.target_hits());
  26294. }
  26295. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26296. ProxyAndTargetServers s;
  26297. auto cli = make_client("internal.corp", s);
  26298. cli->set_proxy_basic_auth("u", "p");
  26299. cli->set_no_proxy({"internal.corp"});
  26300. auto res = cli->Get("/");
  26301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26302. EXPECT_EQ(1, s.target_hits());
  26303. EXPECT_EQ(0, s.proxy_hits());
  26304. EXPECT_FALSE(s.last_had_proxy_authz())
  26305. << "Proxy-Authorization must not be sent direct to the target";
  26306. }
  26307. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26308. ProxyAndTargetServers s;
  26309. auto cli = make_client("public.example", s);
  26310. cli->set_proxy_basic_auth("u", "p");
  26311. cli->set_no_proxy({"internal.corp"}); // does not match
  26312. auto res = cli->Get("/");
  26313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26314. EXPECT_GE(s.proxy_hits(), 1);
  26315. EXPECT_TRUE(s.last_had_proxy_authz());
  26316. }
  26317. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26318. std::atomic<int> hits{0};
  26319. std::atomic<int> hits_with_authz{0};
  26320. no_proxy_test::ScopedServer proxy_mock;
  26321. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26322. hits++;
  26323. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26324. if (req.target.find("/redir") != std::string::npos) {
  26325. res.set_redirect("http://other.example/landed");
  26326. } else {
  26327. res.set_content("via-proxy", "text/plain");
  26328. }
  26329. });
  26330. proxy_mock.listen();
  26331. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26332. hits = 0;
  26333. hits_with_authz = 0;
  26334. Client cli("public.example", 80);
  26335. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26336. cli.set_proxy_basic_auth(c.first, c.second);
  26337. cli.set_follow_location(true);
  26338. // The redirect to another host goes through the proxy as well
  26339. auto res = cli.Get("/redir");
  26340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26341. EXPECT_EQ(2, hits.load());
  26342. EXPECT_EQ(2, hits_with_authz.load());
  26343. }
  26344. }
  26345. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26346. ProxyAndTargetServers s;
  26347. auto cli = make_client("anything.test", s);
  26348. auto res = cli->Get("/");
  26349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26350. EXPECT_GE(s.proxy_hits(), 1);
  26351. EXPECT_EQ(0, s.target_hits());
  26352. }
  26353. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26354. ProxyAndTargetServers s;
  26355. auto cli = make_client("example.com", s);
  26356. cli->set_no_proxy({"example.com:8080"});
  26357. auto res = cli->Get("/");
  26358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26359. EXPECT_GE(s.proxy_hits(), 1);
  26360. EXPECT_EQ(0, s.target_hits());
  26361. }
  26362. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26363. ProxyAndTargetServers s;
  26364. auto cli = make_client("anything.test", s);
  26365. cli->set_no_proxy({"", " ", "\t"});
  26366. auto res = cli->Get("/");
  26367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26368. EXPECT_GE(s.proxy_hits(), 1);
  26369. EXPECT_EQ(0, s.target_hits());
  26370. }
  26371. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26372. // An entry with leading/trailing whitespace must still match — env-style
  26373. // values are commonly pasted with stray spaces and an implementation
  26374. // that feeds the raw token directly to inet_pton would fail to match
  26375. // valid CIDRs because of the spaces.
  26376. ProxyAndTargetServers s;
  26377. Client cli("127.0.0.1", s.target_port());
  26378. cli.set_proxy("127.0.0.1", s.proxy_port());
  26379. cli.set_no_proxy({" 127.0.0.0/8 "});
  26380. auto res = cli.Get("/");
  26381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26382. EXPECT_EQ(0, s.proxy_hits());
  26383. EXPECT_EQ(1, s.target_hits());
  26384. }
  26385. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26386. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26387. // go direct and must NOT carry Proxy-Authorization.
  26388. std::atomic<int> proxy_hits{0};
  26389. std::atomic<int> target_hits{0};
  26390. std::atomic<bool> target_saw_authz{false};
  26391. no_proxy_test::ScopedServer proxy_mock, target;
  26392. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26393. proxy_hits++;
  26394. res.status = 302;
  26395. res.set_header("Location", "http://127.0.0.1:" +
  26396. std::to_string(target.port()) + "/landed");
  26397. });
  26398. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26399. target_hits++;
  26400. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26401. res.set_content("direct", "text/plain");
  26402. });
  26403. proxy_mock.listen();
  26404. target.listen();
  26405. Client cli("public.example", target.port());
  26406. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26407. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26408. cli.set_proxy_basic_auth("u", "p");
  26409. cli.set_no_proxy({"127.0.0.1"});
  26410. cli.set_follow_location(true);
  26411. auto res = cli.Get("/redir");
  26412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26413. EXPECT_GE(proxy_hits.load(), 1);
  26414. EXPECT_GE(target_hits.load(), 1);
  26415. EXPECT_FALSE(target_saw_authz.load());
  26416. }
  26417. #ifdef CPPHTTPLIB_SSL_ENABLED
  26418. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26419. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26420. // proxy creds would be sent to the (possibly hostile) origin.
  26421. std::atomic<int> target_hits{0};
  26422. std::atomic<bool> target_saw_proxy_authz{false};
  26423. no_proxy_test::ScopedServer target;
  26424. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26425. target_hits++;
  26426. if (req.has_header("Proxy-Authorization")) {
  26427. target_saw_proxy_authz = true;
  26428. }
  26429. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26430. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26431. "nonce=\"abc\", algorithm=MD5");
  26432. });
  26433. target.listen();
  26434. // The proxy address is set to the target's port: the bypass MUST kick in;
  26435. // if it doesn't, the test still routes "via proxy" to the same server and
  26436. // the Proxy-Authorization assertion below catches the leak.
  26437. Client cli("evil.example", target.port());
  26438. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26439. cli.set_proxy("127.0.0.1", target.port());
  26440. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26441. cli.set_no_proxy({"evil.example"});
  26442. auto res = cli.Get("/x");
  26443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26444. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26445. EXPECT_EQ(1, target_hits.load());
  26446. EXPECT_FALSE(target_saw_proxy_authz.load());
  26447. }
  26448. #endif
  26449. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26450. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26451. std::atomic<int> proxy_hits{0};
  26452. std::atomic<int> bypass_hits{0};
  26453. std::atomic<bool> proxy_saw_c_url{false};
  26454. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26455. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26456. proxy_hits++;
  26457. if (req.path.find("/start") != std::string::npos) {
  26458. res.status = 302;
  26459. res.set_header("Location", "http://127.0.0.1:" +
  26460. std::to_string(bypass_server.port()) +
  26461. "/middle");
  26462. return;
  26463. }
  26464. if (req.path.find("/end") != std::string::npos) {
  26465. proxy_saw_c_url = true;
  26466. res.set_content("c-via-proxy", "text/plain");
  26467. return;
  26468. }
  26469. res.set_content("unexpected", "text/plain");
  26470. });
  26471. // public.example's "advertised" port is arbitrary (the request never lands
  26472. // there — it goes through the proxy), but use a dynamic value to stay
  26473. // friendly with sharded parallel runs.
  26474. int public_port = bypass_server.port();
  26475. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26476. bypass_hits++;
  26477. res.status = 302;
  26478. res.set_header("Location", "http://public.example:" +
  26479. std::to_string(public_port) + "/end");
  26480. });
  26481. proxy_mock.listen();
  26482. bypass_server.listen();
  26483. Client cli("public.example", public_port);
  26484. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26485. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26486. cli.set_no_proxy({"127.0.0.1"});
  26487. cli.set_follow_location(true);
  26488. auto res = cli.Get("/start");
  26489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26490. EXPECT_EQ(StatusCode::OK_200, res->status);
  26491. EXPECT_EQ("c-via-proxy", res->body);
  26492. EXPECT_GE(proxy_hits.load(), 2);
  26493. EXPECT_GE(bypass_hits.load(), 1);
  26494. EXPECT_TRUE(proxy_saw_c_url.load());
  26495. }
  26496. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26497. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26498. // request reconnects to the correct endpoint.
  26499. std::atomic<int> proxy_hits{0};
  26500. std::atomic<int> target_hits{0};
  26501. no_proxy_test::ScopedServer proxy_mock, target;
  26502. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26503. proxy_hits++;
  26504. res.set_content("via-proxy", "text/plain");
  26505. });
  26506. target.svr().Get(".*", [&](const Request &, Response &res) {
  26507. target_hits++;
  26508. res.set_content("direct", "text/plain");
  26509. });
  26510. proxy_mock.listen();
  26511. target.listen();
  26512. Client cli("public.example", target.port());
  26513. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26514. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26515. cli.set_keep_alive(true);
  26516. auto res1 = cli.Get("/a");
  26517. ASSERT_TRUE(res1);
  26518. EXPECT_EQ("via-proxy", res1->body);
  26519. EXPECT_EQ(1, proxy_hits.load());
  26520. EXPECT_EQ(0, target_hits.load());
  26521. cli.set_no_proxy({"public.example"});
  26522. auto res2 = cli.Get("/b");
  26523. ASSERT_TRUE(res2);
  26524. EXPECT_EQ("direct", res2->body);
  26525. EXPECT_EQ(1, proxy_hits.load());
  26526. EXPECT_EQ(1, target_hits.load());
  26527. }
  26528. // Forward declarations (see the base64_encode note).
  26529. namespace httplib {
  26530. namespace detail {
  26531. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26532. int shutdown_socket(socket_t sock) noexcept;
  26533. } // namespace detail
  26534. } // namespace httplib
  26535. namespace proxy_tunnel_test {
  26536. const char *const kTunnelEstablished =
  26537. "HTTP/1.1 200 Connection established\r\n\r\n";
  26538. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26539. using ConnectReply = std::function<std::string(const std::string &head)>;
  26540. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26541. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26542. class ScopedConnectProxy {
  26543. public:
  26544. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26545. : forward_port_(forward_port), reply_(std::move(reply)) {
  26546. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26547. if (listen_sock_ == INVALID_SOCKET) { return; }
  26548. auto a = loopback(0);
  26549. auto addr = reinterpret_cast<sockaddr *>(&a);
  26550. socklen_t alen = sizeof(a);
  26551. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26552. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26553. ::listen(listen_sock_, 4) != 0) {
  26554. return;
  26555. }
  26556. port_ = ntohs(a.sin_port);
  26557. th_ = std::thread([this] { run(); });
  26558. }
  26559. ~ScopedConnectProxy() {
  26560. if (th_.joinable()) {
  26561. stop_ = true;
  26562. auto wake = connect_to(port_);
  26563. th_.join();
  26564. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26565. }
  26566. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26567. }
  26568. int port() const { return port_; }
  26569. int connect_hits() const { return connect_hits_.load(); }
  26570. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26571. std::string connect_request() const {
  26572. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26573. return connect_request_;
  26574. }
  26575. private:
  26576. static sockaddr_in loopback(int port) {
  26577. sockaddr_in a{};
  26578. a.sin_family = AF_INET;
  26579. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26580. a.sin_port = htons(static_cast<unsigned short>(port));
  26581. return a;
  26582. }
  26583. static socket_t connect_to(int port) {
  26584. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26585. if (sock == INVALID_SOCKET) { return sock; }
  26586. auto a = loopback(port);
  26587. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26588. detail::close_socket(sock);
  26589. return INVALID_SOCKET;
  26590. }
  26591. return sock;
  26592. }
  26593. static bool send_all(socket_t sock, const char *data, size_t size) {
  26594. while (size > 0) {
  26595. auto n = detail::send_socket(sock, data, size, 0);
  26596. if (n <= 0) { return false; }
  26597. data += n;
  26598. size -= static_cast<size_t>(n);
  26599. }
  26600. return true;
  26601. }
  26602. void run() {
  26603. for (;;) {
  26604. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26605. if (stop_) {
  26606. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26607. return;
  26608. }
  26609. if (client == INVALID_SOCKET) { continue; }
  26610. serve(client);
  26611. detail::close_socket(client);
  26612. }
  26613. }
  26614. void serve(socket_t client) {
  26615. std::string head;
  26616. char buf[2048];
  26617. while (head.find("\r\n\r\n") == std::string::npos) {
  26618. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26619. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26620. if (n <= 0) { return; }
  26621. head.append(buf, static_cast<size_t>(n));
  26622. }
  26623. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26624. connect_hits_++;
  26625. {
  26626. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26627. connect_request_ = head;
  26628. }
  26629. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26630. if (!send_all(client, res.data(), res.size()) ||
  26631. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26632. return;
  26633. }
  26634. auto origin = connect_to(forward_port_);
  26635. if (origin == INVALID_SOCKET) { return; }
  26636. // When either side stops, shut both down so the other pump returns too.
  26637. auto pump = [&](socket_t from, socket_t to) {
  26638. char b[8192];
  26639. for (;;) {
  26640. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26641. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26642. }
  26643. detail::shutdown_socket(client);
  26644. detail::shutdown_socket(origin);
  26645. };
  26646. std::thread up([&] { pump(client, origin); });
  26647. pump(origin, client);
  26648. up.join();
  26649. detail::close_socket(origin);
  26650. }
  26651. int forward_port_;
  26652. ConnectReply reply_;
  26653. socket_t listen_sock_ = INVALID_SOCKET;
  26654. int port_ = 0;
  26655. std::thread th_;
  26656. std::atomic<bool> stop_{false};
  26657. std::atomic<int> connect_hits_{0};
  26658. mutable std::mutex connect_request_mutex_;
  26659. std::string connect_request_;
  26660. };
  26661. } // namespace proxy_tunnel_test
  26662. #ifdef CPPHTTPLIB_SSL_ENABLED
  26663. namespace proxy_tunnel_test {
  26664. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26665. class ScopedSSLServer {
  26666. public:
  26667. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26668. port_ = svr_.bind_to_any_port("127.0.0.1");
  26669. }
  26670. ~ScopedSSLServer() {
  26671. svr_.stop();
  26672. if (th_.joinable()) { th_.join(); }
  26673. }
  26674. SSLServer &svr() { return svr_; }
  26675. int port() const { return port_; }
  26676. void listen() {
  26677. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26678. svr_.wait_until_ready();
  26679. }
  26680. private:
  26681. SSLServer svr_;
  26682. std::thread th_;
  26683. int port_ = 0;
  26684. };
  26685. // Sends one request through the CONNECT proxy to the TLS origin with a
  26686. // credential configured for each hop, and checks that each credential reaches
  26687. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26688. // origin's (every header in origin_headers) on the tunnelled request.
  26689. void CredentialsStayWithTheirHop(
  26690. const std::function<void(SSLClient &)> &set_credentials,
  26691. const std::string &scheme,
  26692. const std::vector<std::string> &origin_headers = {"Authorization"},
  26693. bool stream = false) {
  26694. std::atomic<int> origin_hits{0};
  26695. std::atomic<bool> origin_saw_proxy_authz{false};
  26696. std::atomic<bool> origin_saw_headers{false};
  26697. ScopedSSLServer origin;
  26698. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26699. origin_hits++;
  26700. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26701. origin_saw_headers =
  26702. std::all_of(origin_headers.begin(), origin_headers.end(),
  26703. [&](const std::string &h) { return req.has_header(h); });
  26704. res.set_content("ok", "text/plain");
  26705. });
  26706. origin.listen();
  26707. ScopedConnectProxy proxy(origin.port());
  26708. ASSERT_NE(0, proxy.port());
  26709. // Pinned to 127.0.0.1 for the same reason as the test below.
  26710. SSLClient cli("127.0.0.1", origin.port());
  26711. cli.enable_server_certificate_verification(false);
  26712. cli.set_proxy("127.0.0.1", proxy.port());
  26713. set_credentials(cli);
  26714. if (stream) {
  26715. auto handle = cli.open_stream("GET", "/x");
  26716. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26717. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26718. } else {
  26719. auto res = cli.Get("/x");
  26720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26721. EXPECT_EQ(StatusCode::OK_200, res->status);
  26722. }
  26723. EXPECT_EQ(1, origin_hits.load());
  26724. EXPECT_EQ(1, proxy.connect_hits());
  26725. EXPECT_TRUE(origin_saw_headers.load());
  26726. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26727. << "Proxy-Authorization must not be sent inside the tunnel";
  26728. auto connect_req = proxy.connect_request();
  26729. EXPECT_NE(std::string::npos,
  26730. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26731. for (const auto &h : origin_headers) {
  26732. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26733. << h << " must not be sent to the proxy on CONNECT";
  26734. }
  26735. }
  26736. } // namespace proxy_tunnel_test
  26737. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26738. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26739. [](SSLClient &cli) {
  26740. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26741. cli.set_basic_auth("origin-user", "origin-pass");
  26742. },
  26743. "Basic");
  26744. }
  26745. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26746. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26747. [](SSLClient &cli) {
  26748. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26749. cli.set_basic_auth("origin-user", "origin-pass");
  26750. },
  26751. "Basic", {"Authorization"}, true);
  26752. }
  26753. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26754. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26755. [](SSLClient &cli) {
  26756. cli.set_proxy_bearer_token_auth("proxy-token");
  26757. cli.set_bearer_token_auth("origin-token");
  26758. },
  26759. "Bearer");
  26760. }
  26761. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26762. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26763. [](SSLClient &cli) {
  26764. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26765. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26766. {"Cookie", "sid=origin-session"},
  26767. {"X-Api-Key", "origin-key"}});
  26768. },
  26769. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26770. }
  26771. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26772. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26773. // retry; otherwise proxy creds would be sent to the origin.
  26774. std::atomic<int> origin_hits{0};
  26775. std::atomic<bool> origin_saw_proxy_authz{false};
  26776. proxy_tunnel_test::ScopedSSLServer origin;
  26777. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26778. origin_hits++;
  26779. if (req.has_header("Proxy-Authorization")) {
  26780. origin_saw_proxy_authz = true;
  26781. }
  26782. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26783. res.set_header("Proxy-Authenticate",
  26784. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26785. "algorithm=MD5");
  26786. });
  26787. origin.listen();
  26788. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26789. ASSERT_NE(0, proxy.port());
  26790. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26791. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26792. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26793. // and answer with its own status, making this test flaky.
  26794. SSLClient cli("127.0.0.1", origin.port());
  26795. cli.enable_server_certificate_verification(false);
  26796. cli.set_proxy("127.0.0.1", proxy.port());
  26797. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26798. auto res = cli.Get("/x");
  26799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26800. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26801. EXPECT_EQ(1, origin_hits.load());
  26802. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26803. EXPECT_EQ(1, proxy.connect_hits());
  26804. }
  26805. #endif
  26806. namespace proxy_tunnel_test {
  26807. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26808. // anything else gets a 407 with `challenge`.
  26809. ConnectReply require_proxy_auth(const std::string &expected,
  26810. const std::string &challenge) {
  26811. return [=](const std::string &head) -> std::string {
  26812. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26813. std::string::npos) {
  26814. return kTunnelEstablished;
  26815. }
  26816. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26817. "Proxy-Authenticate: " +
  26818. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26819. };
  26820. }
  26821. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26822. // request, then echoes.
  26823. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26824. ws.send(
  26825. "authorization:" + req.get_header_value("Authorization") +
  26826. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26827. std::string msg;
  26828. while (ws.read(msg)) {
  26829. ws.send(msg);
  26830. }
  26831. }
  26832. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26833. class ScopedWebSocketOrigin {
  26834. public:
  26835. ScopedWebSocketOrigin() {
  26836. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26837. server_.listen();
  26838. }
  26839. int port() const { return server_.port(); }
  26840. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26841. std::string url() const {
  26842. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26843. }
  26844. private:
  26845. no_proxy_test::ScopedServer server_;
  26846. };
  26847. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26848. // passed as a constructor header, and checks that each reaches only its hop.
  26849. void WebSocketCredentialsStayWithTheirHop(
  26850. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26851. const std::string &proxy_authz, const std::string &origin_authz) {
  26852. ScopedWebSocketOrigin origin;
  26853. ScopedConnectProxy proxy(
  26854. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26855. ASSERT_NE(0, proxy.port());
  26856. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26857. client.set_proxy("127.0.0.1", proxy.port());
  26858. set_proxy_credentials(client);
  26859. auto res = client.connect();
  26860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26861. std::string msg;
  26862. ASSERT_TRUE(client.read(msg));
  26863. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26864. client.close();
  26865. EXPECT_EQ(1, proxy.connect_hits());
  26866. EXPECT_EQ(std::string::npos,
  26867. proxy.connect_request().find("\r\nAuthorization: "))
  26868. << "origin credentials must not be sent to the proxy";
  26869. }
  26870. } // namespace proxy_tunnel_test
  26871. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26872. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26873. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26874. ASSERT_NE(0, proxy.port());
  26875. ws::WebSocketClient client(origin.url());
  26876. client.set_proxy("127.0.0.1", proxy.port());
  26877. auto res = client.connect();
  26878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26879. std::string msg;
  26880. ASSERT_TRUE(client.read(msg));
  26881. ASSERT_TRUE(client.send("hello"));
  26882. ASSERT_TRUE(client.read(msg));
  26883. EXPECT_EQ("hello", msg);
  26884. client.close();
  26885. EXPECT_EQ(1, proxy.connect_hits());
  26886. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26887. auto connect_req = proxy.connect_request();
  26888. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26889. EXPECT_NE(std::string::npos,
  26890. connect_req.find("\r\nHost: " + target + "\r\n"));
  26891. }
  26892. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26893. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26894. [](ws::WebSocketClient &cli) {
  26895. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26896. },
  26897. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26898. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26899. }
  26900. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26901. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26902. [](ws::WebSocketClient &cli) {
  26903. cli.set_proxy_bearer_token_auth("proxy-token");
  26904. },
  26905. "Bearer proxy-token", "Bearer origin-token");
  26906. }
  26907. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26908. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26909. proxy_tunnel_test::ScopedConnectProxy proxy(
  26910. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26911. "Basic " + detail::base64_encode("proxy-user:"),
  26912. "Basic realm=\"proxy\""));
  26913. ASSERT_NE(0, proxy.port());
  26914. ws::WebSocketClient client(origin.url());
  26915. client.set_proxy("127.0.0.1", proxy.port());
  26916. client.set_proxy_basic_auth("proxy-user", "");
  26917. auto res = client.connect();
  26918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26919. client.close();
  26920. EXPECT_EQ(1, proxy.connect_hits());
  26921. }
  26922. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26923. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26924. proxy_tunnel_test::ScopedConnectProxy proxy(
  26925. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26926. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26927. ASSERT_NE(0, proxy.port());
  26928. ws::WebSocketClient client(origin.url());
  26929. client.set_proxy("127.0.0.1", proxy.port());
  26930. auto res = client.connect();
  26931. EXPECT_FALSE(res);
  26932. EXPECT_EQ(Error::ProxyConnection, res.error());
  26933. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26934. EXPECT_EQ("Basic realm=\"proxy\"",
  26935. res.get_header_value("Proxy-Authenticate"));
  26936. EXPECT_FALSE(client.is_open());
  26937. }
  26938. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26939. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26940. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26941. ASSERT_NE(0, proxy.port());
  26942. ws::WebSocketClient client(origin.url());
  26943. client.set_proxy("127.0.0.1", proxy.port());
  26944. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26945. client.set_no_proxy({"127.0.0.1"});
  26946. auto res = client.connect();
  26947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26948. std::string msg;
  26949. ASSERT_TRUE(client.read(msg));
  26950. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26951. << "proxy credentials must not reach a bypassed origin";
  26952. client.close();
  26953. EXPECT_EQ(0, proxy.connect_hits());
  26954. }
  26955. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26956. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26957. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26958. ASSERT_NE(0, proxy.port());
  26959. ws::WebSocketClient client(origin.url());
  26960. client.set_proxy("127.0.0.1", proxy.port());
  26961. ASSERT_TRUE(client.connect());
  26962. ASSERT_TRUE(client.connect());
  26963. client.close();
  26964. EXPECT_EQ(2, proxy.connect_hits());
  26965. }
  26966. #ifdef CPPHTTPLIB_SSL_ENABLED
  26967. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26968. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26969. proxy_tunnel_test::ScopedConnectProxy proxy(
  26970. origin.port(), [](const std::string &head) -> std::string {
  26971. if (head.find(
  26972. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26973. std::string::npos) {
  26974. return proxy_tunnel_test::kTunnelEstablished;
  26975. }
  26976. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26977. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26978. "nonce=\"abc\", algorithm=MD5\r\n"
  26979. "Content-Length: 0\r\n\r\n";
  26980. });
  26981. ASSERT_NE(0, proxy.port());
  26982. ws::WebSocketClient client(origin.url());
  26983. client.set_proxy("127.0.0.1", proxy.port());
  26984. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26985. auto res = client.connect();
  26986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26987. std::string msg;
  26988. ASSERT_TRUE(client.read(msg));
  26989. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26990. client.close();
  26991. EXPECT_EQ(2, proxy.connect_hits());
  26992. }
  26993. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26994. proxy_tunnel_test::ScopedSSLServer origin;
  26995. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26996. origin.listen();
  26997. proxy_tunnel_test::ScopedConnectProxy proxy(
  26998. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26999. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27000. ASSERT_NE(0, proxy.port());
  27001. ws::WebSocketClient client(
  27002. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27003. client.enable_server_certificate_verification(false);
  27004. client.set_proxy("127.0.0.1", proxy.port());
  27005. client.set_proxy_bearer_token_auth("proxy-token");
  27006. auto res = client.connect();
  27007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27008. std::string msg;
  27009. ASSERT_TRUE(client.read(msg));
  27010. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27011. << "Proxy-Authorization must not be sent inside the tunnel";
  27012. client.close();
  27013. EXPECT_EQ(1, proxy.connect_hits());
  27014. }
  27015. #endif