test.cc 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. #ifndef _WIN32
  253. TEST(SocketStream, wait_writable_UNIX) {
  254. int fds[2];
  255. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  256. const auto asSocketStream = [&](socket_t fd,
  257. std::function<bool(Stream &)> func) {
  258. return detail::process_client_socket(
  259. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  260. };
  261. asSocketStream(fds[0], [&](Stream &s0) {
  262. EXPECT_EQ(s0.socket(), fds[0]);
  263. EXPECT_TRUE(s0.wait_writable());
  264. EXPECT_TRUE(s0.is_peer_alive());
  265. EXPECT_EQ(0, close(fds[1]));
  266. EXPECT_FALSE(s0.is_peer_alive());
  267. return true;
  268. });
  269. EXPECT_EQ(0, close(fds[0]));
  270. }
  271. TEST(SocketStream, wait_writable_INET) {
  272. sockaddr_in addr;
  273. memset(&addr, 0, sizeof(addr));
  274. addr.sin_family = AF_INET;
  275. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  276. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  277. int disconnected_svr_sock = -1;
  278. std::thread svr{[&] {
  279. const int s = socket(AF_INET, SOCK_STREAM, 0);
  280. ASSERT_LE(0, s);
  281. // PORT + 1 is shared with the SSL redirect tests and with
  282. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  283. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  284. // because that happens on a worker thread the ASSERT does not stop the
  285. // test: it runs on and fails at the disconnected_svr_sock check instead.
  286. default_socket_options(s);
  287. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  288. ASSERT_EQ(0, listen(s, 1));
  289. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  290. ASSERT_EQ(0, close(s));
  291. }};
  292. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  293. std::thread cli{[&] {
  294. const int s = socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_LE(0, s);
  296. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  297. ASSERT_EQ(0, close(s));
  298. }};
  299. cli.join();
  300. svr.join();
  301. ASSERT_NE(disconnected_svr_sock, -1);
  302. const auto asSocketStream = [&](socket_t fd,
  303. std::function<bool(Stream &)> func) {
  304. return detail::process_client_socket(
  305. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  306. };
  307. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  308. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  309. // wait_writable() returns true because select_write() only checks if the
  310. // send buffer has space. Peer disconnection is detected later by send().
  311. EXPECT_TRUE(ss.wait_writable());
  312. return true;
  313. });
  314. ASSERT_EQ(0, close(disconnected_svr_sock));
  315. }
  316. #endif // #ifndef _WIN32
  317. TEST(SetSocketOptTest, TcpNoDelay) {
  318. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  319. ASSERT_NE(sock, INVALID_SOCKET);
  320. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  321. int val = 0;
  322. socklen_t len = sizeof(val);
  323. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  324. reinterpret_cast<char *>(&val), &len));
  325. EXPECT_NE(val, 0);
  326. detail::close_socket(sock);
  327. }
  328. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  329. // accept() reports failures through WSAGetLastError() on Windows and through
  330. // errno everywhere else. Asking the wrong one is what made the accept loop
  331. // treat every recoverable failure as fatal on Windows.
  332. struct Classification {
  333. bool resource;
  334. bool transient;
  335. };
  336. auto classify = [](int err) {
  337. #ifdef _WIN32
  338. WSASetLastError(err);
  339. #else
  340. errno = err;
  341. #endif
  342. // Read both before asserting: an assertion may clobber the error slot.
  343. Classification c;
  344. c.resource = detail::is_accept_resource_error();
  345. c.transient = detail::is_accept_transient_error();
  346. return c;
  347. };
  348. #ifdef _WIN32
  349. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  350. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  351. WSAECONNRESET, WSAECONNABORTED};
  352. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  353. #else
  354. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  355. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  356. ECONNABORTED};
  357. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  358. #endif
  359. for (auto err : resource_errors) {
  360. const auto c = classify(err);
  361. EXPECT_TRUE(c.resource) << "error " << err;
  362. EXPECT_FALSE(c.transient) << "error " << err;
  363. }
  364. for (auto err : transient_errors) {
  365. const auto c = classify(err);
  366. EXPECT_TRUE(c.transient) << "error " << err;
  367. EXPECT_FALSE(c.resource) << "error " << err;
  368. }
  369. for (auto err : fatal_errors) {
  370. const auto c = classify(err);
  371. EXPECT_FALSE(c.resource) << "error " << err;
  372. EXPECT_FALSE(c.transient) << "error " << err;
  373. }
  374. #ifdef _WIN32
  375. WSASetLastError(0);
  376. #else
  377. errno = 0;
  378. #endif
  379. }
  380. TEST(ClientTest, MoveConstructible) {
  381. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  382. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  383. }
  384. TEST(ClientTest, MoveAssignable) {
  385. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  386. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  387. }
  388. #ifdef _WIN32
  389. TEST(StartupTest, WSAStartup) {
  390. WSADATA wsaData;
  391. int ret = WSAStartup(0x0002, &wsaData);
  392. ASSERT_EQ(0, ret);
  393. }
  394. #endif
  395. TEST(DecodePathTest, PercentCharacter) {
  396. EXPECT_EQ(
  397. decode_path_component(
  398. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  399. U8("descrip=Gastos áéíóúñÑ 6"));
  400. }
  401. TEST(DecodePathTest, PercentCharacterNUL) {
  402. string expected;
  403. expected.push_back('x');
  404. expected.push_back('\0');
  405. expected.push_back('x');
  406. EXPECT_EQ(decode_path_component("x%00x"), expected);
  407. }
  408. TEST(DecodePathTest, UnicodeEncoding) {
  409. // %u0041 = 'A' (1-byte UTF-8)
  410. EXPECT_EQ("A", decode_path_component("%u0041"));
  411. // %u00E9 = 'é' (2-byte UTF-8)
  412. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  413. // %u3042 = 'あ' (3-byte UTF-8)
  414. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  415. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  416. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  417. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  418. // neighbours)
  419. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  420. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  421. }
  422. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  423. // A sign or whitespace inside the two-character escape window must not be
  424. // accepted as a valid percent-encoding; the sequence is passed through
  425. // literally, matching decode_uri_component / decode_path_component.
  426. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  427. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  428. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  429. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  430. // Well-formed escapes still decode.
  431. EXPECT_EQ("-", decode_query_component("%2D", false));
  432. EXPECT_EQ("A", decode_query_component("%41", false));
  433. }
  434. TEST(SanitizeFilenameTest, VariousPatterns) {
  435. // Path traversal
  436. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  437. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  438. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  439. // Normal and edge cases
  440. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  441. EXPECT_EQ("filename.txt",
  442. httplib::sanitize_filename("/path/to/filename.txt"));
  443. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  444. EXPECT_EQ("", httplib::sanitize_filename(".."));
  445. EXPECT_EQ("", httplib::sanitize_filename(""));
  446. // Null bytes stripped
  447. EXPECT_EQ("safe.txt",
  448. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  449. // Whitespace-only rejected
  450. EXPECT_EQ("", httplib::sanitize_filename(" "));
  451. }
  452. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  453. // before it is dropped; anywhere else it is an ordinary file name character.
  454. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  455. #ifdef _WIN32
  456. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  457. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  458. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  459. #else
  460. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  461. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  462. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  463. #endif
  464. }
  465. // Forward declaration (see the base64_encode note below): split builds move the
  466. // definition into httplib.cc, so re-declaring it here lets the test link.
  467. namespace httplib {
  468. namespace detail {
  469. bool is_chunked_transfer_encoding(const Headers &headers);
  470. } // namespace detail
  471. } // namespace httplib
  472. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  473. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  474. auto make = [](std::initializer_list<const char *> lines) {
  475. Headers h;
  476. for (auto te : lines) {
  477. if (te) { h.emplace("Transfer-Encoding", te); }
  478. }
  479. return h;
  480. };
  481. // Sole coding, matched case-insensitively.
  482. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  483. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  484. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  485. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  486. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  487. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  488. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  489. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  490. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  491. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  492. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  493. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  494. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  495. // were received, into one list. Headers preserves that order, so the answer
  496. // is decided by the last coding of the last line and the order the lines
  497. // arrived in is significant.
  498. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  499. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  500. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  501. // The split can fall anywhere in the list.
  502. EXPECT_TRUE(
  503. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  504. EXPECT_FALSE(
  505. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  506. // A trailing line naming no coding leaves the list ending in nothing, so it
  507. // must not inherit the chunked from the line before it.
  508. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  509. }
  510. // Forward declarations (see the base64_encode note below).
  511. namespace httplib {
  512. namespace detail {
  513. bool parse_status_line(const char *line, std::string &version, int &status,
  514. std::string &reason);
  515. std::string file_extension(const std::string &path);
  516. std::string
  517. find_content_type(const std::string &path,
  518. const std::map<std::string, std::string> &user_data,
  519. const std::string &default_content_type);
  520. bool can_compress_content_type(const std::string &content_type);
  521. bool is_prohibited_header_name(const std::string &name);
  522. bool is_valid_path(const std::string &path);
  523. #ifdef CPPHTTPLIB_SSL_ENABLED
  524. bool match_hostname(const std::string &pattern, const std::string &hostname);
  525. #endif
  526. } // namespace detail
  527. } // namespace httplib
  528. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  529. struct {
  530. const char *line;
  531. const char *version;
  532. int status;
  533. const char *reason;
  534. } cases[] = {
  535. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  536. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  537. // The reason phrase may be empty, or left out along with its space.
  538. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  539. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  540. };
  541. for (const auto &c : cases) {
  542. std::string version;
  543. int status = 0;
  544. std::string reason = "unset";
  545. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  546. << c.line;
  547. EXPECT_EQ(c.version, version);
  548. EXPECT_EQ(c.status, status);
  549. EXPECT_EQ(c.reason, reason);
  550. }
  551. }
  552. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  553. const char *lines[] = {
  554. "HTTP/2 200 OK\r\n",
  555. "HTTP/1.2 200 OK\r\n",
  556. "HTTP/1.1 20 OK\r\n",
  557. "HTTP/1.1 2000 OK\r\n",
  558. "HTTP/1.1 2x0 OK\r\n",
  559. "HTTP/1.1 200 OK\r\n",
  560. "HTTP/1.1 200OK\r\n",
  561. "HTTP/1.1 200 O\rK\r\n",
  562. "HTTP/1.1 200 OK",
  563. "HTTP/1.1 200 OK\r\nX",
  564. "",
  565. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  566. "HTTP/1.1 200 OK\n",
  567. #endif
  568. };
  569. for (auto line : lines) {
  570. std::string version;
  571. int status = 0;
  572. std::string reason;
  573. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  574. << line;
  575. }
  576. }
  577. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  578. // Long enough to overflow the stack when matched with std::regex.
  579. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  580. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  581. std::string version;
  582. int status = 0;
  583. std::string reason;
  584. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  585. EXPECT_EQ(200, status);
  586. EXPECT_EQ(long_reason, reason);
  587. }
  588. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  589. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  590. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  591. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  592. EXPECT_EQ("", detail::file_extension("noext"));
  593. EXPECT_EQ("", detail::file_extension("a."));
  594. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  595. EXPECT_EQ("", detail::file_extension("a.b-c"));
  596. // Long enough to overflow the stack when matched with std::regex.
  597. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  598. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  599. }
  600. #ifdef CPPHTTPLIB_SSL_ENABLED
  601. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  602. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  603. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  604. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  605. // A wildcard needs two labels after it, in the leftmost label only
  606. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  607. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  608. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  609. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  610. EXPECT_FALSE(
  611. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  612. // No name may have an empty label
  613. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  614. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  615. }
  616. #endif
  617. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  618. detail::case_ignore::hash hash;
  619. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  620. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  621. // Long enough to overflow the stack if hashed one call per character.
  622. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  623. }
  624. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  625. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  626. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  627. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  628. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  629. // Same 26-bit hash as html, svg and js.
  630. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  631. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  632. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  633. }
  634. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  635. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  636. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  637. }
  638. }
  639. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  640. // name anywhere else.
  641. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  642. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  643. #ifdef _WIN32
  644. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  645. #else
  646. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  647. #endif
  648. }
  649. }
  650. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  651. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  652. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  653. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  654. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  655. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  656. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  657. // Same 26-bit hash as application/json.
  658. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  659. }
  660. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  661. Request req;
  662. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  663. EXPECT_TRUE(req.is_multipart_form_data());
  664. std::string boundary;
  665. EXPECT_TRUE(detail::parse_multipart_boundary(
  666. req.get_header_value("Content-Type"), boundary));
  667. EXPECT_EQ("x", boundary);
  668. }
  669. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  670. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  671. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  672. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  673. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  674. // Same 26-bit hash as REMOTE_ADDR.
  675. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  676. }
  677. // Forward declaration: in split builds split.py strips `inline` and moves the
  678. // definition into httplib.cc, so detail::base64_encode is not visible from the
  679. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  680. // in both header-only and split builds.
  681. namespace httplib {
  682. namespace detail {
  683. std::string base64_encode(const std::string &in);
  684. } // namespace detail
  685. } // namespace httplib
  686. TEST(Base64EncodeTest, KnownAnswers) {
  687. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  688. // where the accumulator's top bit is already set before the next shift.
  689. EXPECT_EQ("", detail::base64_encode(""));
  690. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  691. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  692. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  693. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  694. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  695. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  696. // High bytes keep the top bit set across several rounds.
  697. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  698. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  699. }
  700. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  701. string unescapedCharacters = "-_.!~*'()";
  702. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  703. }
  704. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  705. string reservedCharacters = ";,/?:@&=+$";
  706. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  707. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  708. }
  709. TEST(ClientQueryOrder, PreserveOrder) {
  710. // This test reproduces Issue #2259: client may reorder query parameters
  711. // when sending a GET request. The expected behavior is that the client
  712. // preserves the original query string order when the caller supplied it
  713. // as part of the path.
  714. Server svr;
  715. svr.Get("/", [&](const Request &req, Response &res) {
  716. // Echo back the raw target so the test can assert ordering
  717. res.set_content(req.target, "text/plain");
  718. });
  719. std::thread t{[&] { svr.listen(HOST, PORT); }};
  720. auto se = detail::scope_exit([&] {
  721. svr.stop();
  722. t.join();
  723. ASSERT_FALSE(svr.is_running());
  724. });
  725. svr.wait_until_ready();
  726. Client cli(HOST, PORT);
  727. ASSERT_TRUE(cli.is_valid());
  728. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  729. auto res = cli.Get(original);
  730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  731. // Expect the echoed target to exactly match the original path (order
  732. // preserved)
  733. EXPECT_EQ(res->body, original);
  734. }
  735. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  736. string chineseCharacters = U8("中国語");
  737. string russianCharacters = U8("дом");
  738. string brazilianCharacters = U8("óculos");
  739. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  740. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  741. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  742. "%D0%B4%D0%BE%D0%BC");
  743. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  744. }
  745. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  746. string unescapedCharacters = "-_.!~*'()";
  747. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  748. }
  749. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  750. string reservedCharacters = ";,/?:@&=+$";
  751. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  752. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  753. }
  754. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  755. string chineseCharacters = U8("中国語");
  756. string russianCharacters = U8("дом");
  757. string brazilianCharacters = U8("óculos");
  758. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  759. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  760. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  761. "%D0%B4%D0%BE%D0%BC");
  762. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  763. }
  764. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  765. // Issue #2082 use case: encoding path component with ampersand
  766. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  767. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  768. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  769. }
  770. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  771. string unescapedCharacters = "-_.!~*'()";
  772. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  773. }
  774. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  775. string reservedCharacters = ";,/?:@&=+$#";
  776. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  777. }
  778. TEST(EncodeUriTest, TestUTF8Characters) {
  779. string chineseCharacters = U8("中国語");
  780. string russianCharacters = U8("дом");
  781. string brazilianCharacters = U8("óculos");
  782. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  783. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  784. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  785. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  786. }
  787. TEST(EncodeUriTest, TestCompleteUri) {
  788. string uri =
  789. "https://example.com/path/to/resource?query=value&param=test#fragment";
  790. EXPECT_EQ(
  791. httplib::encode_uri(uri),
  792. "https://example.com/path/to/resource?query=value&param=test#fragment");
  793. }
  794. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  795. string uri =
  796. "https://example.com/path with spaces/file name.html?q=hello world";
  797. EXPECT_EQ(httplib::encode_uri(uri),
  798. "https://example.com/path%20with%20spaces/"
  799. "file%20name.html?q=hello%20world");
  800. }
  801. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  802. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  803. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  804. }
  805. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  806. string unescapedCharacters = "-_.!~*'()";
  807. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  808. }
  809. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  810. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  811. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  812. string encodedBrazilian = "%C3%B3culos";
  813. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  814. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  815. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  816. }
  817. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  818. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  819. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  820. "Piri Tommy Villiers - on & on");
  821. }
  822. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  823. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  824. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  825. }
  826. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  827. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  828. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  829. }
  830. TEST(DecodeUriTest, TestUTF8Characters) {
  831. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  832. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  833. string encodedBrazilian = "%C3%B3culos";
  834. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  835. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  836. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  837. }
  838. TEST(DecodeUriTest, TestCompleteUri) {
  839. string encodedUri = "https://example.com/path%20with%20spaces/"
  840. "file%20name.html?q=hello%20world";
  841. EXPECT_EQ(
  842. httplib::decode_uri(encodedUri),
  843. "https://example.com/path with spaces/file name.html?q=hello world");
  844. }
  845. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  846. string original =
  847. "https://example.com/path with spaces/file name.html?q=hello world";
  848. string encoded = httplib::encode_uri(original);
  849. string decoded = httplib::decode_uri(encoded);
  850. EXPECT_EQ(decoded, original);
  851. }
  852. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  853. // decode_uri is the inverse of encode_uri: an escaped reserved character
  854. // stays encoded so it is not promoted into a real delimiter, while
  855. // non-reserved escapes still decode (like JS decodeURI).
  856. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  857. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  858. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  859. "%3F%3A%40%26%3D%2B%24%2C%3B");
  860. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  861. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  862. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  863. "http://example.com/a%2Fb");
  864. // decode_uri_component still decodes the reserved character.
  865. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  866. }
  867. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  868. string original = "Piri Tommy Villiers - on & on";
  869. string encoded = httplib::encode_uri_component(original);
  870. string decoded = httplib::decode_uri_component(encoded);
  871. EXPECT_EQ(decoded, original);
  872. }
  873. TEST(TrimTests, TrimStringTests) {
  874. EXPECT_EQ("abc", detail::trim_copy("abc"));
  875. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  876. EXPECT_TRUE(detail::trim_copy("").empty());
  877. }
  878. TEST(AsciiTest, LocaleIndependentClassification) {
  879. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  880. // which consult the global C locale: std::isalnum(0xC5) can return true
  881. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  882. // helpers must classify every byte by the ASCII grammar alone.
  883. for (int i = 0; i < 256; i++) {
  884. auto c = static_cast<char>(i);
  885. auto is_digit = i >= '0' && i <= '9';
  886. auto is_upper = i >= 'A' && i <= 'Z';
  887. auto is_lower = i >= 'a' && i <= 'z';
  888. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  889. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  890. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  891. << "byte " << i;
  892. }
  893. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  894. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  895. // Non-ASCII bytes must be percent-encoded, never passed through as
  896. // alphanumeric.
  897. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  898. }
  899. TEST(FromCharsTest, Double) {
  900. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  901. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  902. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  903. auto parse = [](const std::string &s, double &v) {
  904. return detail::from_chars(s.data(), s.data() + s.size(), v);
  905. };
  906. double v = -1.0;
  907. // Representative quality values.
  908. EXPECT_EQ(parse("0", v).ec, std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.0);
  910. EXPECT_EQ(parse("1", v).ec, std::errc{});
  911. EXPECT_DOUBLE_EQ(v, 1.0);
  912. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  913. EXPECT_DOUBLE_EQ(v, 0.8);
  914. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  915. EXPECT_DOUBLE_EQ(v, 0.001);
  916. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  917. EXPECT_DOUBLE_EQ(v, 1.0);
  918. // A missing integer or fractional part is tolerated.
  919. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  920. EXPECT_DOUBLE_EQ(v, 0.5);
  921. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  922. EXPECT_DOUBLE_EQ(v, 5.0);
  923. // Values outside [0, 1] still parse; the caller range-checks them.
  924. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  925. EXPECT_DOUBLE_EQ(v, 123.456);
  926. // Stops at the first byte that is not part of the number and reports where.
  927. std::string trailing = "0.9, text/html";
  928. auto r = parse(trailing, v);
  929. EXPECT_EQ(r.ec, std::errc{});
  930. EXPECT_DOUBLE_EQ(v, 0.9);
  931. EXPECT_EQ(*r.ptr, ',');
  932. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  933. // outright, and an 'e'/'E' simply ends the number.
  934. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  935. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  936. std::string exp_input = "1.5e3";
  937. r = parse(exp_input, v);
  938. EXPECT_EQ(r.ec, std::errc{});
  939. EXPECT_DOUBLE_EQ(v, 1.5);
  940. EXPECT_EQ(*r.ptr, 'e');
  941. // Invalid inputs.
  942. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  943. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  944. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  945. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  946. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  947. // Pathological but well-formed inputs must stay bounded (no overflow, no
  948. // out-of-bounds table access) and stay within [0, 1] for the caller.
  949. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  950. std::errc{});
  951. EXPECT_DOUBLE_EQ(v, 0.0);
  952. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  953. std::errc{});
  954. EXPECT_GE(v, 0.0);
  955. EXPECT_LE(v, 1.0);
  956. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  957. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  958. }
  959. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  960. // Simple case without quality values
  961. std::vector<std::string> result1;
  962. EXPECT_TRUE(detail::parse_accept_header(
  963. "text/html,application/json,text/plain", result1));
  964. EXPECT_EQ(result1.size(), 3U);
  965. EXPECT_EQ(result1[0], "text/html");
  966. EXPECT_EQ(result1[1], "application/json");
  967. EXPECT_EQ(result1[2], "text/plain");
  968. // With quality values
  969. std::vector<std::string> result2;
  970. EXPECT_TRUE(detail::parse_accept_header(
  971. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  972. EXPECT_EQ(result2.size(), 3U);
  973. EXPECT_EQ(result2[0], "application/json"); // highest q value
  974. EXPECT_EQ(result2[1], "text/html");
  975. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  976. }
  977. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  978. // Mixed with and without quality values
  979. std::vector<std::string> result;
  980. EXPECT_TRUE(detail::parse_accept_header(
  981. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  982. EXPECT_EQ(result.size(), 3U);
  983. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  984. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  985. EXPECT_EQ(result[2], "application/json"); // q=0.5
  986. }
  987. TEST(ParseAcceptHeaderTest, EdgeCases) {
  988. // Empty header
  989. std::vector<std::string> empty_result;
  990. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  991. EXPECT_TRUE(empty_result.empty());
  992. // Single type
  993. std::vector<std::string> single_result;
  994. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  995. EXPECT_EQ(single_result.size(), 1U);
  996. EXPECT_EQ(single_result[0], "application/json");
  997. // Wildcard types
  998. std::vector<std::string> wildcard_result;
  999. EXPECT_TRUE(detail::parse_accept_header(
  1000. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1001. EXPECT_EQ(wildcard_result.size(), 3U);
  1002. EXPECT_EQ(wildcard_result[0], "application/json");
  1003. EXPECT_EQ(wildcard_result[1], "text/*");
  1004. EXPECT_EQ(wildcard_result[2], "*/*");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1007. // Common browser Accept header
  1008. std::vector<std::string> browser_result;
  1009. EXPECT_TRUE(
  1010. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1011. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1012. browser_result));
  1013. EXPECT_EQ(browser_result.size(), 6U);
  1014. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1015. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1016. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1017. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1018. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1019. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1020. // API client header
  1021. std::vector<std::string> api_result;
  1022. EXPECT_TRUE(detail::parse_accept_header(
  1023. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1024. api_result));
  1025. EXPECT_EQ(api_result.size(), 3U);
  1026. EXPECT_EQ(api_result[0], "application/json");
  1027. EXPECT_EQ(api_result[1], "application/xml");
  1028. EXPECT_EQ(api_result[2], "text/plain");
  1029. }
  1030. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1031. // Quality value with 3 decimal places
  1032. std::vector<std::string> decimal_result;
  1033. EXPECT_TRUE(detail::parse_accept_header(
  1034. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1035. EXPECT_EQ(decimal_result.size(), 2U);
  1036. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1037. EXPECT_EQ(decimal_result[1], "text/html");
  1038. // Zero quality (should still be included but with lowest priority)
  1039. std::vector<std::string> zero_q_result;
  1040. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1041. zero_q_result));
  1042. EXPECT_EQ(zero_q_result.size(), 2U);
  1043. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1044. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1045. // No spaces around commas
  1046. std::vector<std::string> no_space_result;
  1047. EXPECT_TRUE(detail::parse_accept_header(
  1048. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1049. no_space_result));
  1050. EXPECT_EQ(no_space_result.size(), 3U);
  1051. EXPECT_EQ(no_space_result[0], "text/html");
  1052. EXPECT_EQ(no_space_result[1], "application/json");
  1053. EXPECT_EQ(no_space_result[2], "text/plain");
  1054. }
  1055. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1056. // Quality values always use '.' as the decimal separator, so parsing must
  1057. // not depend on the process locale. An embedding application may have
  1058. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1059. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1060. std::string saved = cur ? cur : "C";
  1061. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1062. "fr_FR.UTF-8"};
  1063. bool switched = false;
  1064. for (const auto loc : comma_locales) {
  1065. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1066. std::localeconv()->decimal_point[0] == ',') {
  1067. switched = true;
  1068. break;
  1069. }
  1070. }
  1071. if (!switched) {
  1072. std::setlocale(LC_NUMERIC, saved.c_str());
  1073. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1074. }
  1075. // The higher-weighted type appears later in the list, so a correct parse
  1076. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1077. // sensitive parse reads both weights as 0 and leaves the original order.
  1078. std::vector<std::string> result;
  1079. EXPECT_TRUE(detail::parse_accept_header(
  1080. "application/json;q=0.1,text/html;q=0.9", result));
  1081. ASSERT_EQ(result.size(), 2U);
  1082. EXPECT_EQ(result[0], "text/html");
  1083. EXPECT_EQ(result[1], "application/json");
  1084. std::setlocale(LC_NUMERIC, saved.c_str());
  1085. }
  1086. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1087. std::vector<std::string> result;
  1088. // Invalid quality value (> 1.0)
  1089. EXPECT_FALSE(
  1090. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1091. // Invalid quality value (< 0.0)
  1092. EXPECT_FALSE(
  1093. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1094. // Invalid quality value (not a number)
  1095. EXPECT_FALSE(detail::parse_accept_header(
  1096. "text/html;q=invalid,application/json", result));
  1097. // A valid numeric prefix does not make the entire quality value valid.
  1098. EXPECT_FALSE(detail::parse_accept_header(
  1099. "text/html;q=0.5junk,application/json", result));
  1100. // Empty quality value
  1101. EXPECT_FALSE(
  1102. detail::parse_accept_header("text/html;q=,application/json", result));
  1103. // Invalid media type format (no slash and not wildcard)
  1104. EXPECT_FALSE(
  1105. detail::parse_accept_header("invalidtype,application/json", result));
  1106. // Valid cases should still work
  1107. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1108. EXPECT_EQ(result.size(), 1U);
  1109. EXPECT_EQ(result[0], "*/*");
  1110. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1111. EXPECT_EQ(result.size(), 1U);
  1112. EXPECT_EQ(result[0], "*");
  1113. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1114. EXPECT_EQ(result.size(), 1U);
  1115. EXPECT_EQ(result[0], "text/*");
  1116. }
  1117. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1118. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1119. // and must not be answered with 400 Bad Request.
  1120. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1121. struct {
  1122. const char *value;
  1123. std::vector<std::string> expected;
  1124. } cases[] = {
  1125. {",application/json", {"application/json"}},
  1126. {"text/html,", {"text/html"}},
  1127. {"text/html,,*/*", {"text/html", "*/*"}},
  1128. // An empty element may be spelled with whitespace in it
  1129. {"text/html, , application/json", {"text/html", "application/json"}},
  1130. // Nothing but empty elements is an empty list, which means the same
  1131. // thing as no Accept header at all
  1132. {",,,", {}},
  1133. // Quality values still apply across ignored empty elements
  1134. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1135. };
  1136. for (const auto &c : cases) {
  1137. std::vector<std::string> result;
  1138. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1139. << "value: " << c.value;
  1140. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1141. }
  1142. // An invalid entry is still rejected when empty elements surround it
  1143. std::vector<std::string> result;
  1144. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1145. }
  1146. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1147. // or ';' inside one does not end the list element or the parameter. Section
  1148. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1149. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1150. struct {
  1151. const char *value;
  1152. std::vector<std::string> expected;
  1153. } cases[] = {
  1154. {"text/html;profile=\"a,b\",application/json",
  1155. {"text/html", "application/json"}},
  1156. // A "q=" inside a quoted value is not the weight
  1157. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1158. {"text/html", "application/json"}},
  1159. // The weight after a quoted value still applies
  1160. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1161. {"application/json", "text/html"}},
  1162. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1163. {"application/json", "text/html"}},
  1164. {"text/html;profile=\"a\\\"b\",application/json",
  1165. {"text/html", "application/json"}},
  1166. // An escaped backslash does not escape the '"' after it
  1167. {"text/html;profile=\"a\\\\\",application/json",
  1168. {"text/html", "application/json"}},
  1169. };
  1170. for (const auto &c : cases) {
  1171. std::vector<std::string> result;
  1172. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1173. << "value: " << c.value;
  1174. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1175. }
  1176. }
  1177. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1178. Server svr;
  1179. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1180. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1181. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1182. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1183. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1184. res.set_content("ok", "text/plain");
  1185. });
  1186. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1187. EXPECT_TRUE(false);
  1188. res.set_content("bad request", "text/plain");
  1189. });
  1190. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1191. auto se = detail::scope_exit([&] {
  1192. svr.stop();
  1193. listen_thread.join();
  1194. ASSERT_FALSE(svr.is_running());
  1195. });
  1196. svr.wait_until_ready();
  1197. Client cli("localhost", PORT);
  1198. {
  1199. auto res = cli.Get(
  1200. "/accept_ok",
  1201. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1203. EXPECT_EQ(StatusCode::OK_200, res->status);
  1204. }
  1205. {
  1206. auto res = cli.Get("/accept_bad_request",
  1207. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1209. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1210. }
  1211. }
  1212. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1213. Server svr;
  1214. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1215. res.set_content("ok", "text/plain");
  1216. });
  1217. std::atomic<int> start_count{0};
  1218. std::atomic<bool> running_when_called{false};
  1219. svr.set_start_handler([&]() {
  1220. running_when_called = svr.is_running();
  1221. start_count++;
  1222. });
  1223. auto port = svr.bind_to_any_port(HOST);
  1224. std::thread t([&]() { svr.listen_after_bind(); });
  1225. auto se = detail::scope_exit([&] {
  1226. svr.stop();
  1227. t.join();
  1228. ASSERT_FALSE(svr.is_running());
  1229. });
  1230. svr.wait_until_ready();
  1231. // A successful request proves the accept loop is running, which the start
  1232. // handler precedes; so by now the handler must have run exactly once.
  1233. Client cli(HOST, port);
  1234. cli.set_connection_timeout(std::chrono::seconds(5));
  1235. auto res = cli.Get("/");
  1236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1237. EXPECT_EQ(StatusCode::OK_200, res->status);
  1238. EXPECT_EQ(1, start_count.load());
  1239. EXPECT_TRUE(running_when_called.load());
  1240. }
  1241. TEST(DivideTest, DivideStringTests) {
  1242. auto divide = [](const std::string &str, char d) {
  1243. std::string lhs;
  1244. std::string rhs;
  1245. detail::divide(str, d,
  1246. [&](const char *lhs_data, std::size_t lhs_size,
  1247. const char *rhs_data, std::size_t rhs_size) {
  1248. lhs.assign(lhs_data, lhs_size);
  1249. rhs.assign(rhs_data, rhs_size);
  1250. });
  1251. return std::make_pair(std::move(lhs), std::move(rhs));
  1252. };
  1253. {
  1254. const auto res = divide("", '=');
  1255. EXPECT_EQ(res.first, "");
  1256. EXPECT_EQ(res.second, "");
  1257. }
  1258. {
  1259. const auto res = divide("=", '=');
  1260. EXPECT_EQ(res.first, "");
  1261. EXPECT_EQ(res.second, "");
  1262. }
  1263. {
  1264. const auto res = divide(" ", '=');
  1265. EXPECT_EQ(res.first, " ");
  1266. EXPECT_EQ(res.second, "");
  1267. }
  1268. {
  1269. const auto res = divide("a", '=');
  1270. EXPECT_EQ(res.first, "a");
  1271. EXPECT_EQ(res.second, "");
  1272. }
  1273. {
  1274. const auto res = divide("a=", '=');
  1275. EXPECT_EQ(res.first, "a");
  1276. EXPECT_EQ(res.second, "");
  1277. }
  1278. {
  1279. const auto res = divide("=b", '=');
  1280. EXPECT_EQ(res.first, "");
  1281. EXPECT_EQ(res.second, "b");
  1282. }
  1283. {
  1284. const auto res = divide("a=b", '=');
  1285. EXPECT_EQ(res.first, "a");
  1286. EXPECT_EQ(res.second, "b");
  1287. }
  1288. {
  1289. const auto res = divide("a=b=", '=');
  1290. EXPECT_EQ(res.first, "a");
  1291. EXPECT_EQ(res.second, "b=");
  1292. }
  1293. {
  1294. const auto res = divide("a=b=c", '=');
  1295. EXPECT_EQ(res.first, "a");
  1296. EXPECT_EQ(res.second, "b=c");
  1297. }
  1298. }
  1299. TEST(SplitTest, ParseQueryString) {
  1300. string s = "key1=val1&key2=val2&key3=val3";
  1301. Params dic;
  1302. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1303. [&](const char *b, const char *e) {
  1304. string key, val;
  1305. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1306. if (key.empty()) {
  1307. key.assign(b2, e2);
  1308. } else {
  1309. val.assign(b2, e2);
  1310. }
  1311. });
  1312. dic.emplace(key, val);
  1313. });
  1314. EXPECT_EQ("val1", dic.find("key1")->second);
  1315. EXPECT_EQ("val2", dic.find("key2")->second);
  1316. EXPECT_EQ("val3", dic.find("key3")->second);
  1317. }
  1318. TEST(SplitTest, ParseInvalidQueryTests) {
  1319. {
  1320. string s = " ";
  1321. Params dict;
  1322. detail::parse_query_text(s, dict);
  1323. EXPECT_TRUE(dict.empty());
  1324. }
  1325. {
  1326. string s = " = =";
  1327. Params dict;
  1328. detail::parse_query_text(s, dict);
  1329. EXPECT_TRUE(dict.empty());
  1330. }
  1331. }
  1332. TEST(ParseQueryTest, ParseQueryString) {
  1333. {
  1334. std::string s = "key1=val1&key2=val2&key3=val3";
  1335. Params dic;
  1336. detail::parse_query_text(s, dic);
  1337. EXPECT_EQ("val1", dic.find("key1")->second);
  1338. EXPECT_EQ("val2", dic.find("key2")->second);
  1339. EXPECT_EQ("val3", dic.find("key3")->second);
  1340. }
  1341. {
  1342. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1343. Params dic;
  1344. detail::parse_query_text(s, dic);
  1345. EXPECT_EQ("", dic.find("key1")->second);
  1346. EXPECT_EQ("val1", dic.find("key2")->second);
  1347. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1348. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1349. }
  1350. }
  1351. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1352. Params dic;
  1353. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1354. dic.emplace("key1", "val1");
  1355. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1356. dic.emplace("key2", "val2");
  1357. dic.emplace("key3", "val3");
  1358. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1359. }
  1360. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1361. Params params;
  1362. params.emplace("a", "1");
  1363. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1364. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1365. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1366. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1367. // Long enough to overflow the stack when matched with std::regex.
  1368. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1369. EXPECT_EQ("/p?" + long_query + "&a=1",
  1370. append_query_params("/p?" + long_query, params));
  1371. }
  1372. // Joins every entry of a Headers or Params into "key=value " so a whole
  1373. // traversal can be compared in one assertion. Both are instantiations of the
  1374. // same insertion-ordered container, so one helper serves both.
  1375. template <typename Map> static std::string entries_to_string(const Map &m) {
  1376. std::string s;
  1377. for (const auto &entry : m) {
  1378. s += entry.first + "=" + entry.second + " ";
  1379. }
  1380. return s;
  1381. }
  1382. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1383. // Params used to be a std::multimap, which sorted by name and handed the
  1384. // caller's query back alphabetised. A client signing its query string could
  1385. // not reproduce the order it asked for.
  1386. Params dic;
  1387. dic.emplace("zulu", "1");
  1388. dic.emplace("alpha", "2");
  1389. dic.emplace("mike", "3");
  1390. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1391. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1392. }
  1393. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1394. Params dic;
  1395. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1396. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1397. }
  1398. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1399. Request req;
  1400. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1401. req.params);
  1402. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1403. EXPECT_EQ("first", req.get_param_value("tag"));
  1404. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1405. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1406. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1407. EXPECT_EQ("", req.get_param_value("tag", 3));
  1408. }
  1409. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1410. // Params shares its container with Headers, which matches field names
  1411. // case-insensitively. Parameter names must not pick that up.
  1412. Params dic;
  1413. dic.emplace("Key", "upper");
  1414. dic.emplace("key", "lower");
  1415. EXPECT_EQ(2U, dic.size());
  1416. EXPECT_EQ(1U, dic.count("Key"));
  1417. EXPECT_EQ(1U, dic.count("key"));
  1418. EXPECT_EQ("upper", dic.find("Key")->second);
  1419. EXPECT_EQ("lower", dic.find("key")->second);
  1420. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1421. }
  1422. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1423. Server svr;
  1424. std::string order;
  1425. svr.Get("/order", [&](const Request &req, Response &res) {
  1426. order = entries_to_string(req.params);
  1427. res.set_content("ok", "text/plain");
  1428. });
  1429. auto port = svr.bind_to_any_port(HOST);
  1430. thread t = thread([&] { svr.listen_after_bind(); });
  1431. auto se = detail::scope_exit([&] {
  1432. svr.stop();
  1433. t.join();
  1434. ASSERT_FALSE(svr.is_running());
  1435. });
  1436. svr.wait_until_ready();
  1437. Client cli(HOST, port);
  1438. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1439. ASSERT_TRUE(res);
  1440. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1441. }
  1442. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1443. Server svr;
  1444. std::string field_order, file_order;
  1445. svr.Post("/order", [&](const Request &req, Response &res) {
  1446. for (const auto &field : req.form.fields) {
  1447. field_order += field.first + "=" + field.second.content + " ";
  1448. }
  1449. for (const auto &file : req.form.files) {
  1450. file_order += file.first + "=" + file.second.filename + " ";
  1451. }
  1452. res.set_content("ok", "text/plain");
  1453. });
  1454. auto port = svr.bind_to_any_port(HOST);
  1455. thread t = thread([&] { svr.listen_after_bind(); });
  1456. auto se = detail::scope_exit([&] {
  1457. svr.stop();
  1458. t.join();
  1459. ASSERT_FALSE(svr.is_running());
  1460. });
  1461. svr.wait_until_ready();
  1462. UploadFormDataItems items = {
  1463. {"zulu", "1", "", ""},
  1464. {"alpha", "2", "", ""},
  1465. {"mike", "3", "", ""},
  1466. {"zebra", "z", "z.txt", "text/plain"},
  1467. {"apple", "a", "a.txt", "text/plain"},
  1468. };
  1469. Client cli(HOST, port);
  1470. auto res = cli.Post("/order", items);
  1471. ASSERT_TRUE(res);
  1472. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1473. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1474. }
  1475. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1476. Server svr;
  1477. std::vector<std::string> values;
  1478. std::string first, second, out_of_range, order;
  1479. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1480. values = req.form.get_fields("tag");
  1481. first = req.form.get_field("tag", 0);
  1482. second = req.form.get_field("tag", 1);
  1483. out_of_range = req.form.get_field("tag", 2);
  1484. for (const auto &field : req.form.fields) {
  1485. order += field.first + "=" + field.second.content + " ";
  1486. }
  1487. res.set_content("ok", "text/plain");
  1488. });
  1489. auto port = svr.bind_to_any_port(HOST);
  1490. thread t = thread([&] { svr.listen_after_bind(); });
  1491. auto se = detail::scope_exit([&] {
  1492. svr.stop();
  1493. t.join();
  1494. ASSERT_FALSE(svr.is_running());
  1495. });
  1496. svr.wait_until_ready();
  1497. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1498. // not adjacent in the container.
  1499. UploadFormDataItems items = {
  1500. {"tag", "first", "", ""},
  1501. {"other", "x", "", ""},
  1502. {"tag", "second", "", ""},
  1503. };
  1504. Client cli(HOST, port);
  1505. auto res = cli.Post("/repeated", items);
  1506. ASSERT_TRUE(res);
  1507. ASSERT_EQ(2U, values.size());
  1508. EXPECT_EQ("first", values[0]);
  1509. EXPECT_EQ("second", values[1]);
  1510. EXPECT_EQ("first", first);
  1511. EXPECT_EQ("second", second);
  1512. // std::multimap already kept entries sharing a name in insertion order, so
  1513. // everything above passes without this change too. The whole traversal is
  1514. // what tells the two apart: sorting by name would hoist "other" to the front
  1515. // and the two "tag" parts would end up adjacent.
  1516. EXPECT_EQ("tag=first other=x tag=second ", order);
  1517. // Advancing past the last entry of a name used to run off the container;
  1518. // the container's saturating increment makes it return the default instead.
  1519. EXPECT_EQ("", out_of_range);
  1520. }
  1521. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1522. Server svr;
  1523. std::string file_names;
  1524. svr.Post("/upload", [&](const Request &req, Response &res) {
  1525. for (const auto &file : req.form.files) {
  1526. file_names += file.first + "|" + file.second.filename + " ";
  1527. }
  1528. res.set_content("ok", "text/plain");
  1529. });
  1530. auto port = svr.bind_to_any_port(HOST);
  1531. thread t = thread([&] { svr.listen_after_bind(); });
  1532. auto se = detail::scope_exit([&] {
  1533. svr.stop();
  1534. t.join();
  1535. ASSERT_FALSE(svr.is_running());
  1536. });
  1537. svr.wait_until_ready();
  1538. // A trailing backslash would otherwise escape the closing quote.
  1539. UploadFormDataItems items = {
  1540. {"dir\\", "x", "a.txt", "text/plain"},
  1541. {"b", "y", "a\\\\b.txt", "text/plain"},
  1542. };
  1543. Client cli(HOST, port);
  1544. auto res = cli.Post("/upload", items);
  1545. ASSERT_TRUE(res);
  1546. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1547. }
  1548. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1549. // Server::read_content() keeps a FormFields::iterator alive across the
  1550. // content callbacks that fill the part it points at. The container is
  1551. // vector-backed, so a later emplace can reallocate and invalidate an older
  1552. // iterator; 64 parts grow the vector through seven reallocations, which
  1553. // checks that every part's content still lands in its own entry.
  1554. const size_t part_count = 64;
  1555. // One formula for both the parts sent and the values expected back, so the
  1556. // two cannot drift apart.
  1557. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1558. auto content_of = [](size_t i) {
  1559. return std::string(64, static_cast<char>('a' + (i % 26)));
  1560. };
  1561. Server svr;
  1562. std::vector<std::pair<std::string, std::string>> received;
  1563. svr.Post("/many", [&](const Request &req, Response &res) {
  1564. for (const auto &field : req.form.fields) {
  1565. received.emplace_back(field.first, field.second.content);
  1566. }
  1567. res.set_content("ok", "text/plain");
  1568. });
  1569. auto port = svr.bind_to_any_port(HOST);
  1570. thread t = thread([&] { svr.listen_after_bind(); });
  1571. auto se = detail::scope_exit([&] {
  1572. svr.stop();
  1573. t.join();
  1574. ASSERT_FALSE(svr.is_running());
  1575. });
  1576. svr.wait_until_ready();
  1577. UploadFormDataItems items;
  1578. for (size_t i = 0; i < part_count; i++) {
  1579. items.push_back({name_of(i), content_of(i), "", ""});
  1580. }
  1581. Client cli(HOST, port);
  1582. auto res = cli.Post("/many", items);
  1583. ASSERT_TRUE(res);
  1584. ASSERT_EQ(part_count, received.size());
  1585. for (size_t i = 0; i < part_count; i++) {
  1586. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1587. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1588. }
  1589. }
  1590. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1591. string content_type = "multipart/form-data; boundary=something";
  1592. string boundary;
  1593. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1594. EXPECT_TRUE(ret);
  1595. EXPECT_EQ(boundary, "something");
  1596. }
  1597. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1598. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1599. string boundary;
  1600. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1601. EXPECT_TRUE(ret);
  1602. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1603. }
  1604. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1605. string content_type =
  1606. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1607. string boundary;
  1608. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1609. EXPECT_TRUE(ret);
  1610. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1611. }
  1612. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1613. string content_type =
  1614. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1615. string boundary;
  1616. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1617. EXPECT_TRUE(ret);
  1618. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1619. }
  1620. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1621. const string boundary(70, 'a');
  1622. string content_type = "multipart/form-data; boundary=" + boundary;
  1623. string parsed;
  1624. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1625. EXPECT_TRUE(ret);
  1626. EXPECT_EQ(parsed, boundary);
  1627. }
  1628. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1629. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1630. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1631. string parsed;
  1632. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1633. EXPECT_FALSE(ret);
  1634. }
  1635. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1636. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1637. // is 72 characters on the wire and still valid.
  1638. const string boundary(70, 'a');
  1639. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1640. string parsed;
  1641. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1642. EXPECT_EQ(parsed, boundary);
  1643. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1644. parsed.clear();
  1645. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1646. }
  1647. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1648. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1649. // The parameter parser must not treat that '=' as the key/value separator.
  1650. string content_type =
  1651. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1652. "charset=UTF-8";
  1653. string parsed;
  1654. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1655. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1656. }
  1657. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1658. // A ';' inside the quoted-string is part of the value, not a parameter
  1659. // separator, so it must not truncate the boundary.
  1660. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1661. string parsed;
  1662. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1663. EXPECT_EQ(parsed, "a;b");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1666. string parsed;
  1667. EXPECT_TRUE(detail::parse_multipart_boundary(
  1668. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1669. EXPECT_EQ("a\\b", parsed);
  1670. EXPECT_TRUE(detail::parse_multipart_boundary(
  1671. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1672. EXPECT_EQ("a\"b", parsed);
  1673. }
  1674. TEST(ParseDispositionParamsTest, QuotedValues) {
  1675. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1676. // ';' and '=' are ordinary characters inside one.
  1677. struct {
  1678. const char *value;
  1679. std::vector<std::pair<const char *, const char *>> expected;
  1680. } cases[] = {
  1681. {"name=\"file1\"; filename=\"a.txt\"",
  1682. {{"name", "file1"}, {"filename", "a.txt"}}},
  1683. // Whitespace around '=' and ';' is still trimmed
  1684. {"name=\"file2\" ;filename = \"a.html\"",
  1685. {{"name", "file2"}, {"filename", "a.html"}}},
  1686. // '=' inside the value used to leave only the text after the last one
  1687. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1688. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1689. {"name=\"x=y\"", {{"name", "x=y"}}},
  1690. // ';' inside the value used to truncate the pair and leave a bogus one
  1691. {"name=\"file3\"; filename=\"a;b.txt\"",
  1692. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1693. // An unquoted value keeps working, and so does filename*
  1694. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1695. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1696. // A parameter with no key is dropped rather than turned into one whose
  1697. // key is the value
  1698. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1699. // An escaped quote does not end the value
  1700. {"name=\"a\\\"; filename=evil.php\"",
  1701. {{"name", "a\"; filename=evil.php"}}},
  1702. // Other backslashes, as in a Windows path, are kept
  1703. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1704. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1705. };
  1706. for (const auto &c : cases) {
  1707. Params params;
  1708. detail::parse_disposition_params(c.value, params);
  1709. for (const auto &kv : c.expected) {
  1710. auto it = params.find(kv.first);
  1711. ASSERT_NE(it, params.end())
  1712. << "value: " << c.value << ", key: " << kv.first;
  1713. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1714. }
  1715. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1716. }
  1717. }
  1718. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1719. Server svr;
  1720. std::string filename;
  1721. std::string content;
  1722. svr.Post("/upload", [&](const Request &req, Response &) {
  1723. const auto &file = req.form.get_file("file");
  1724. filename = file.filename;
  1725. content = file.content;
  1726. });
  1727. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1728. auto se = detail::scope_exit([&] {
  1729. svr.stop();
  1730. thread.join();
  1731. ASSERT_FALSE(svr.is_running());
  1732. });
  1733. svr.wait_until_ready();
  1734. std::string body = "--B\r\n"
  1735. "Content-Disposition: form-data; name=\"file\"; "
  1736. "filename=\"a.txt\"\r\n"
  1737. "Content-Type: text/plain\r\n"
  1738. "\r\n"
  1739. "hello\r\n"
  1740. "--B--\r\n";
  1741. Client cli(HOST, PORT);
  1742. auto res = cli.Post(
  1743. "/upload",
  1744. [&](size_t offset, DataSink &sink) {
  1745. if (offset < body.size()) {
  1746. sink.write(&body[offset], 1);
  1747. } else {
  1748. sink.done();
  1749. }
  1750. return true;
  1751. },
  1752. "multipart/form-data; boundary=B");
  1753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1754. EXPECT_EQ(StatusCode::OK_200, res->status);
  1755. EXPECT_EQ("a.txt", filename);
  1756. EXPECT_EQ("hello", content);
  1757. }
  1758. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1759. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1760. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1761. Server svr;
  1762. std::string field_value, file_name, file_filename;
  1763. bool has_field = false, has_file = false;
  1764. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1765. has_field = req.form.has_field("x=y");
  1766. field_value = req.form.get_field("x=y");
  1767. has_file = req.form.has_file("file1");
  1768. const auto &file = req.form.get_file("file1");
  1769. file_name = file.name;
  1770. file_filename = file.filename;
  1771. res.set_content("ok", "text/plain");
  1772. });
  1773. auto port = svr.bind_to_any_port(HOST);
  1774. thread t = thread([&] { svr.listen_after_bind(); });
  1775. auto se = detail::scope_exit([&] {
  1776. svr.stop();
  1777. t.join();
  1778. ASSERT_FALSE(svr.is_running());
  1779. });
  1780. svr.wait_until_ready();
  1781. UploadFormDataItems items = {
  1782. {"x=y", "field-value", "", ""},
  1783. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1784. };
  1785. Client cli(HOST, port);
  1786. auto res = cli.Post("/quoted", items);
  1787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1788. ASSERT_EQ(StatusCode::OK_200, res->status);
  1789. EXPECT_TRUE(has_field);
  1790. EXPECT_EQ("field-value", field_value);
  1791. EXPECT_TRUE(has_file);
  1792. EXPECT_EQ("file1", file_name);
  1793. EXPECT_EQ("a;b=report.pdf", file_filename);
  1794. }
  1795. TEST(GetHeaderValueTest, DefaultValue) {
  1796. Headers headers = {{"Dummy", "Dummy"}};
  1797. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1798. EXPECT_STREQ("text/plain", val);
  1799. }
  1800. TEST(GetHeaderValueTest, DefaultValueInt) {
  1801. Headers headers = {{"Dummy", "Dummy"}};
  1802. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1803. EXPECT_EQ(100ull, val);
  1804. }
  1805. TEST(GetHeaderValueTest, RegularValue) {
  1806. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1807. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1808. EXPECT_STREQ("text/html", val);
  1809. }
  1810. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1811. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1812. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1813. EXPECT_STREQ("text/html", val);
  1814. }
  1815. TEST(GetHeaderValueTest, SetContent) {
  1816. Response res;
  1817. res.set_content("html", "text/html");
  1818. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1819. res.set_content("text", "text/plain");
  1820. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1821. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1822. }
  1823. TEST(GetHeaderValueTest, RegularValueInt) {
  1824. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1825. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1826. EXPECT_EQ(100ull, val);
  1827. }
  1828. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1829. Headers headers = {{"Content-Length", "x"}};
  1830. auto is_invalid_value = false;
  1831. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1832. is_invalid_value);
  1833. EXPECT_EQ(0ull, val);
  1834. EXPECT_TRUE(is_invalid_value);
  1835. }
  1836. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1837. // An all-digit value that overflows size_t must be reported as invalid, not
  1838. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1839. // a large length to a small one on 32-bit builds, leaving the framing length
  1840. // wrong while is_invalid_value stayed false.
  1841. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1842. auto is_invalid_value = false;
  1843. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1844. is_invalid_value);
  1845. EXPECT_TRUE(is_invalid_value);
  1846. // A well-formed length is unaffected.
  1847. Headers ok = {{"Content-Length", "1234"}};
  1848. is_invalid_value = false;
  1849. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1850. is_invalid_value);
  1851. EXPECT_EQ(1234ull, val);
  1852. EXPECT_FALSE(is_invalid_value);
  1853. }
  1854. TEST(GetHeaderValueTest, Range) {
  1855. {
  1856. Headers headers = {make_range_header({{1, -1}})};
  1857. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1858. EXPECT_STREQ("bytes=1-", val);
  1859. }
  1860. {
  1861. Headers headers = {make_range_header({{-1, 1}})};
  1862. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1863. EXPECT_STREQ("bytes=-1", val);
  1864. }
  1865. {
  1866. Headers headers = {make_range_header({{1, 10}})};
  1867. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1868. EXPECT_STREQ("bytes=1-10", val);
  1869. }
  1870. {
  1871. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1872. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1873. EXPECT_STREQ("bytes=1-10, 100-", val);
  1874. }
  1875. {
  1876. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1877. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1878. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1879. }
  1880. {
  1881. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1882. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1883. EXPECT_STREQ("bytes=0-0, -1", val);
  1884. }
  1885. }
  1886. TEST(BearerTokenAuthTest, SchemeValidation) {
  1887. // A value shorter than "Bearer " must not throw from the fixed-length
  1888. // substr, and a non-Bearer scheme must not be reported as a token.
  1889. struct {
  1890. const char *value;
  1891. const char *expected;
  1892. } cases[] = {
  1893. {"x", ""},
  1894. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1895. {"Bearer abc123", "abc123"},
  1896. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1897. };
  1898. for (const auto &c : cases) {
  1899. Request req;
  1900. req.set_header("Authorization", c.value);
  1901. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1902. }
  1903. }
  1904. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1905. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1906. // to depend on the standard library (libstdc++ handed back duplicates in
  1907. // reverse insertion order, libc++ in insertion order).
  1908. Request req;
  1909. req.set_header("Accept-Encoding", "gzip");
  1910. req.set_header("Accept-Encoding", "deflate");
  1911. req.set_header("Accept-Encoding", "br");
  1912. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1913. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1914. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1915. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1916. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1917. }
  1918. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1919. Request req;
  1920. req.set_header("X-Test", "only");
  1921. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1922. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1923. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1924. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1925. }
  1926. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1927. Request req;
  1928. req.set_header("X-First", "1");
  1929. req.set_header("X-Test", "2");
  1930. req.params.emplace("first", "1");
  1931. req.params.emplace("test", "2");
  1932. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1933. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1934. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1935. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1936. // The second one is negative when read as a signed value
  1937. const auto max_id = (std::numeric_limits<size_t>::max)();
  1938. for (auto id : {max_id / 2, max_id}) {
  1939. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1940. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1941. EXPECT_EQ("", req.get_param_value("test", id));
  1942. EXPECT_EQ("", req.form.get_field("test", id));
  1943. EXPECT_EQ("", req.form.get_file("test", id).content);
  1944. }
  1945. }
  1946. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1947. Headers headers;
  1948. headers.emplace("Host", "example.com");
  1949. headers.emplace("Accept-Encoding", "gzip");
  1950. headers.emplace("User-Agent", "test");
  1951. headers.emplace("Accept-Encoding", "deflate");
  1952. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1953. "Accept-Encoding=deflate ",
  1954. entries_to_string(headers));
  1955. }
  1956. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1957. Headers headers = {{"Content-Type", "text/html"},
  1958. {"CONTENT-TYPE", "text/xml"}};
  1959. EXPECT_EQ(2U, headers.count("content-type"));
  1960. auto it = headers.find("content-type");
  1961. ASSERT_TRUE(it != headers.end());
  1962. EXPECT_EQ("text/html", it->second);
  1963. }
  1964. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1965. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1966. // drop only those fields and leave everything positioned between them.
  1967. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1968. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1969. auto rng = headers.equal_range("a");
  1970. headers.erase(rng.first, rng.second);
  1971. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1972. }
  1973. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1974. Headers headers = {
  1975. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1976. EXPECT_EQ(3U, headers.erase("A"));
  1977. EXPECT_EQ(0U, headers.count("A"));
  1978. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1979. }
  1980. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1981. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1982. headers.emplace_front("Host", "example.com");
  1983. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1984. entries_to_string(headers));
  1985. }
  1986. TEST(ParseHeaderValueTest, Range) {
  1987. {
  1988. Ranges ranges;
  1989. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1990. EXPECT_TRUE(ret);
  1991. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1992. }
  1993. {
  1994. Ranges ranges;
  1995. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1996. EXPECT_TRUE(ret);
  1997. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1998. }
  1999. {
  2000. Ranges ranges;
  2001. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2002. EXPECT_TRUE(ret);
  2003. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2004. }
  2005. {
  2006. Ranges ranges;
  2007. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2008. EXPECT_FALSE(ret);
  2009. }
  2010. {
  2011. Ranges ranges;
  2012. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2013. EXPECT_TRUE(ret);
  2014. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2015. }
  2016. {
  2017. Ranges ranges;
  2018. auto ret =
  2019. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2020. EXPECT_TRUE(ret);
  2021. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2022. }
  2023. {
  2024. Ranges ranges;
  2025. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2026. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2027. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2028. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2029. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2030. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2031. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2032. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2033. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2034. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2035. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2036. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2037. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2038. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2039. EXPECT_FALSE(
  2040. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2041. EXPECT_TRUE(ranges.empty());
  2042. }
  2043. {
  2044. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2045. // remainder of the representation, so it stays accepted.
  2046. Ranges ranges;
  2047. auto ret =
  2048. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2049. EXPECT_TRUE(ret);
  2050. ASSERT_EQ(1u, ranges.size());
  2051. EXPECT_EQ(0, ranges[0].first);
  2052. EXPECT_EQ(-1, ranges[0].second);
  2053. }
  2054. // RFC 9110 14.1: range unit names are case-insensitive.
  2055. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2056. Ranges ranges;
  2057. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2058. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2059. }
  2060. }
  2061. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2062. Request req;
  2063. req.set_header("Accept-Encoding", "gzip");
  2064. Response res;
  2065. res.set_header("Content-Type", "text/plain");
  2066. auto ret = detail::encoding_type(req, res);
  2067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2068. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2069. #else
  2070. EXPECT_TRUE(ret == detail::EncodingType::None);
  2071. #endif
  2072. }
  2073. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2074. Request req;
  2075. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2076. Response res;
  2077. res.set_header("Content-Type", "text/plain");
  2078. auto ret = detail::encoding_type(req, res);
  2079. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2080. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2081. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2082. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2083. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2084. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2085. #else
  2086. EXPECT_TRUE(ret == detail::EncodingType::None);
  2087. #endif
  2088. }
  2089. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2090. Request req;
  2091. req.set_header("Accept-Encoding",
  2092. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2093. Response res;
  2094. res.set_header("Content-Type", "text/plain");
  2095. auto ret = detail::encoding_type(req, res);
  2096. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2097. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2098. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2099. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2100. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2101. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2102. #else
  2103. EXPECT_TRUE(ret == detail::EncodingType::None);
  2104. #endif
  2105. }
  2106. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2107. // All supported encodings rejected with q=0 should return None
  2108. Request req;
  2109. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2110. Response res;
  2111. res.set_header("Content-Type", "text/plain");
  2112. auto ret = detail::encoding_type(req, res);
  2113. EXPECT_TRUE(ret == detail::EncodingType::None);
  2114. }
  2115. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2116. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2117. Request req;
  2118. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2119. Response res;
  2120. res.set_header("Content-Type", "text/plain");
  2121. auto ret = detail::encoding_type(req, res);
  2122. EXPECT_TRUE(ret == detail::EncodingType::None);
  2123. }
  2124. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2125. Request req;
  2126. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2127. Response res;
  2128. res.set_header("Content-Type", "text/plain");
  2129. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2130. }
  2131. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2132. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2133. Request req;
  2134. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2135. Response res;
  2136. res.set_header("Content-Type", "text/plain");
  2137. auto ret = detail::encoding_type(req, res);
  2138. EXPECT_TRUE(ret == detail::EncodingType::None);
  2139. }
  2140. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2141. // RFC 7231: Accept-Encoding values are case-insensitive
  2142. Request req;
  2143. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2144. Response res;
  2145. res.set_header("Content-Type", "text/plain");
  2146. auto ret = detail::encoding_type(req, res);
  2147. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2149. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2151. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2152. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2153. #else
  2154. EXPECT_TRUE(ret == detail::EncodingType::None);
  2155. #endif
  2156. }
  2157. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2158. // q value should determine priority, not hardcoded order
  2159. Request req;
  2160. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2161. Response res;
  2162. res.set_header("Content-Type", "text/plain");
  2163. auto ret = detail::encoding_type(req, res);
  2164. // gzip has highest q=1.0, so it should be selected even though
  2165. // br and zstd are also supported
  2166. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2168. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2169. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2170. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2171. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2172. #else
  2173. EXPECT_TRUE(ret == detail::EncodingType::None);
  2174. #endif
  2175. }
  2176. TEST(BufferStreamTest, read) {
  2177. detail::BufferStream strm1;
  2178. Stream &strm = strm1;
  2179. EXPECT_EQ(5, strm.write("hello"));
  2180. char buf[512];
  2181. EXPECT_EQ(2, strm.read(buf, 2));
  2182. EXPECT_EQ('h', buf[0]);
  2183. EXPECT_EQ('e', buf[1]);
  2184. EXPECT_EQ(2, strm.read(buf, 2));
  2185. EXPECT_EQ('l', buf[0]);
  2186. EXPECT_EQ('l', buf[1]);
  2187. EXPECT_EQ(1, strm.read(buf, 1));
  2188. EXPECT_EQ('o', buf[0]);
  2189. EXPECT_EQ(0, strm.read(buf, 1));
  2190. }
  2191. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2192. auto host = "www.httpwatch.com";
  2193. auto ip = hosted_at(host);
  2194. EXPECT_EQ("23.96.13.243", ip);
  2195. std::vector<std::string> addrs;
  2196. hosted_at(host, addrs);
  2197. EXPECT_EQ(1u, addrs.size());
  2198. }
  2199. #if 0 // It depends on each test environment...
  2200. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2201. auto host = "www.youtube.com";
  2202. std::vector<std::string> addrs;
  2203. hosted_at(host, addrs);
  2204. EXPECT_EQ(20u, addrs.size());
  2205. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2206. EXPECT_TRUE(it != addrs.end());
  2207. }
  2208. #endif
  2209. class ChunkedEncodingTest : public ::testing::Test {
  2210. protected:
  2211. ChunkedEncodingTest()
  2212. : cli_(HOST, PORT)
  2213. #ifdef CPPHTTPLIB_SSL_ENABLED
  2214. ,
  2215. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2216. #endif
  2217. {
  2218. cli_.set_connection_timeout(2);
  2219. #ifdef CPPHTTPLIB_SSL_ENABLED
  2220. cli_.enable_server_certificate_verification(false);
  2221. #endif
  2222. }
  2223. virtual void SetUp() {
  2224. read_file("./image.jpg", image_data_);
  2225. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2226. res.set_content("Hello World!", "text/plain");
  2227. });
  2228. svr_.Get(
  2229. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2230. res.set_chunked_content_provider(
  2231. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2232. size_t remaining = image_data_.size() - offset;
  2233. if (remaining == 0) {
  2234. sink.done();
  2235. } else {
  2236. constexpr size_t CHUNK_SIZE = 1024;
  2237. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2238. sink.write(&image_data_[offset], send_size);
  2239. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2240. }
  2241. return true;
  2242. });
  2243. });
  2244. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2245. svr_.wait_until_ready();
  2246. }
  2247. virtual void TearDown() {
  2248. svr_.stop();
  2249. if (!request_threads_.empty()) {
  2250. std::this_thread::sleep_for(std::chrono::seconds(1));
  2251. for (auto &t : request_threads_) {
  2252. t.join();
  2253. }
  2254. }
  2255. t_.join();
  2256. }
  2257. #ifdef CPPHTTPLIB_SSL_ENABLED
  2258. SSLClient cli_;
  2259. SSLServer svr_;
  2260. #else
  2261. Client cli_;
  2262. Server svr_;
  2263. #endif
  2264. thread t_;
  2265. std::vector<thread> request_threads_;
  2266. std::string image_data_;
  2267. };
  2268. TEST_F(ChunkedEncodingTest, NormalGet) {
  2269. auto res = cli_.Get("/chunked");
  2270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2271. std::string out;
  2272. read_file("./image.jpg", out);
  2273. EXPECT_EQ(StatusCode::OK_200, res->status);
  2274. EXPECT_EQ(out, res->body);
  2275. }
  2276. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2277. std::string body;
  2278. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2279. body.append(data, data_length);
  2280. return true;
  2281. });
  2282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2283. std::string out;
  2284. read_file("./image.jpg", out);
  2285. EXPECT_EQ(StatusCode::OK_200, res->status);
  2286. EXPECT_EQ(out, body);
  2287. }
  2288. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2289. std::string body;
  2290. auto res = cli_.Get(
  2291. "/chunked",
  2292. [&](const Response &response) {
  2293. EXPECT_EQ(StatusCode::OK_200, response.status);
  2294. return true;
  2295. },
  2296. [&](const char *data, size_t data_length) {
  2297. body.append(data, data_length);
  2298. return true;
  2299. });
  2300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2301. std::string out;
  2302. read_file("./image.jpg", out);
  2303. EXPECT_EQ(StatusCode::OK_200, res->status);
  2304. EXPECT_EQ(out, body);
  2305. }
  2306. TEST(RangeTest, FromHTTPBin_Online) {
  2307. auto host = "httpbingo.org";
  2308. auto path = std::string{"/range/32"};
  2309. #ifdef CPPHTTPLIB_SSL_ENABLED
  2310. auto port = 443;
  2311. SSLClient cli(host, port);
  2312. #else
  2313. auto port = 80;
  2314. Client cli(host, port);
  2315. #endif
  2316. cli.set_connection_timeout(5);
  2317. {
  2318. auto res = cli.Get(path);
  2319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2320. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2321. EXPECT_EQ(StatusCode::OK_200, res->status);
  2322. }
  2323. {
  2324. Headers headers = {make_range_header({{1, -1}})};
  2325. auto res = cli.Get(path, headers);
  2326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2327. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2328. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2329. }
  2330. {
  2331. Headers headers = {make_range_header({{1, 10}})};
  2332. auto res = cli.Get(path, headers);
  2333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2334. EXPECT_EQ("bcdefghijk", res->body);
  2335. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2336. }
  2337. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2338. // entire resource, while the original httpbin returned 200. Both are
  2339. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2340. {
  2341. Headers headers = {make_range_header({{0, 31}})};
  2342. auto res = cli.Get(path, headers);
  2343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2344. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2345. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2346. res->status == StatusCode::PartialContent_206);
  2347. }
  2348. {
  2349. Headers headers = {make_range_header({{0, -1}})};
  2350. auto res = cli.Get(path, headers);
  2351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2352. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2353. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2354. res->status == StatusCode::PartialContent_206);
  2355. }
  2356. // go-httpbin returns 206 with clamped range for over-range requests,
  2357. // while the original httpbin returned 416. Both behaviors are observed
  2358. // in real servers, so we only verify the request succeeds.
  2359. {
  2360. Headers headers = {make_range_header({{0, 32}})};
  2361. auto res = cli.Get(path, headers);
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. }
  2364. }
  2365. TEST(RangeTest, IgnoredForPost) {
  2366. Server svr;
  2367. svr.Post("/", [](const Request &, Response &res) {
  2368. res.set_content("abcdefg", "text/plain");
  2369. });
  2370. auto port = svr.bind_to_any_port(HOST);
  2371. ASSERT_GT(port, 0);
  2372. thread t = thread([&] { svr.listen_after_bind(); });
  2373. auto se = detail::scope_exit([&] {
  2374. svr.stop();
  2375. t.join();
  2376. ASSERT_FALSE(svr.is_running());
  2377. });
  2378. svr.wait_until_ready();
  2379. Client cli(HOST, port);
  2380. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2381. auto res = cli.Post("/", Headers{{"Range", range}});
  2382. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2383. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2384. EXPECT_EQ("abcdefg", res->body) << range;
  2385. }
  2386. }
  2387. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2388. auto host = "unresolvableaddress.local";
  2389. auto path = std::string{"/"};
  2390. #ifdef CPPHTTPLIB_SSL_ENABLED
  2391. auto port = 443;
  2392. SSLClient cli(host, port);
  2393. #else
  2394. auto port = 80;
  2395. Client cli(host, port);
  2396. #endif
  2397. cli.set_connection_timeout(1);
  2398. {
  2399. auto res = cli.Get(path);
  2400. ASSERT_FALSE(res);
  2401. }
  2402. std::this_thread::sleep_for(std::chrono::seconds(8));
  2403. }
  2404. #if defined(__linux__) && defined(__GLIBC__) && \
  2405. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2406. // Forward declaration: in split builds split.py strips `inline` and moves the
  2407. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2408. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2409. // against the symbol in both header-only and split builds.
  2410. namespace httplib {
  2411. namespace detail {
  2412. int getaddrinfo_with_timeout(const char *node, const char *service,
  2413. const struct addrinfo *hints,
  2414. struct addrinfo **res, time_t timeout_sec);
  2415. } // namespace detail
  2416. } // namespace httplib
  2417. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2418. //
  2419. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2420. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2421. // gai_suspend() call hits the connection timeout the function calls
  2422. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2423. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2424. // still alive and still references the now-destroyed stack frame.
  2425. //
  2426. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2427. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2428. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2429. // and runs them in a container.
  2430. namespace {
  2431. bool should_run_issue_2431_tests() {
  2432. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2433. return v && *v && std::string(v) != "0";
  2434. }
  2435. std::string unique_unresolvable_host(int n) {
  2436. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2437. // glibc still asks the configured nameserver — which is exactly the path
  2438. // we want to exercise. A unique label per call avoids the resolver cache.
  2439. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2440. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2441. std::to_string(n) + ".invalid";
  2442. }
  2443. } // namespace
  2444. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2445. if (!should_run_issue_2431_tests()) {
  2446. GTEST_SKIP()
  2447. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2448. }
  2449. for (int i = 0; i < 8; ++i) {
  2450. struct addrinfo hints;
  2451. memset(&hints, 0, sizeof(hints));
  2452. hints.ai_family = AF_UNSPEC;
  2453. hints.ai_socktype = SOCK_STREAM;
  2454. auto host = unique_unresolvable_host(i);
  2455. struct addrinfo *result = nullptr;
  2456. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2457. &result, /*timeout_sec=*/1);
  2458. if (rc == 0 && result) { freeaddrinfo(result); }
  2459. }
  2460. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2461. // stack region they still believe holds their gaicb.
  2462. std::this_thread::sleep_for(std::chrono::seconds(3));
  2463. }
  2464. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2465. if (!should_run_issue_2431_tests()) {
  2466. GTEST_SKIP()
  2467. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2468. }
  2469. std::atomic<bool> stop{false};
  2470. std::vector<std::thread> threads;
  2471. for (int t = 0; t < 8; ++t) {
  2472. threads.emplace_back([t, &stop] {
  2473. int i = 0;
  2474. while (!stop.load(std::memory_order_relaxed)) {
  2475. struct addrinfo hints;
  2476. memset(&hints, 0, sizeof(hints));
  2477. hints.ai_family = AF_UNSPEC;
  2478. hints.ai_socktype = SOCK_STREAM;
  2479. auto host = unique_unresolvable_host(t * 100000 + i++);
  2480. struct addrinfo *result = nullptr;
  2481. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2482. &result, /*timeout_sec=*/1);
  2483. if (rc == 0 && result) { freeaddrinfo(result); }
  2484. }
  2485. });
  2486. }
  2487. std::this_thread::sleep_for(std::chrono::seconds(8));
  2488. stop.store(true, std::memory_order_relaxed);
  2489. for (auto &th : threads) {
  2490. th.join();
  2491. }
  2492. std::this_thread::sleep_for(std::chrono::seconds(3));
  2493. }
  2494. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2495. if (!should_run_issue_2431_tests()) {
  2496. GTEST_SKIP()
  2497. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2498. }
  2499. std::atomic<bool> stop{false};
  2500. std::vector<std::thread> threads;
  2501. for (int t = 0; t < 8; ++t) {
  2502. threads.emplace_back([t, &stop] {
  2503. int i = 0;
  2504. while (!stop.load(std::memory_order_relaxed)) {
  2505. auto host = unique_unresolvable_host(t * 100000 + i++);
  2506. Client cli(host, 80);
  2507. cli.set_connection_timeout(1, 0);
  2508. cli.set_read_timeout(1, 0);
  2509. cli.set_write_timeout(1, 0);
  2510. (void)cli.Get("/");
  2511. }
  2512. });
  2513. }
  2514. std::this_thread::sleep_for(std::chrono::seconds(8));
  2515. stop.store(true, std::memory_order_relaxed);
  2516. for (auto &th : threads) {
  2517. th.join();
  2518. }
  2519. std::this_thread::sleep_for(std::chrono::seconds(3));
  2520. }
  2521. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2522. TEST(ConnectionErrorTest, InvalidHost) {
  2523. auto host = "-abcde.com";
  2524. #ifdef CPPHTTPLIB_SSL_ENABLED
  2525. auto port = 443;
  2526. SSLClient cli(host, port);
  2527. #else
  2528. auto port = 80;
  2529. Client cli(host, port);
  2530. #endif
  2531. cli.set_connection_timeout(std::chrono::seconds(2));
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. EXPECT_EQ(Error::Connection, res.error());
  2535. }
  2536. TEST(ConnectionErrorTest, InvalidHost2) {
  2537. auto host = "httpcan.org/";
  2538. #ifdef CPPHTTPLIB_SSL_ENABLED
  2539. SSLClient cli(host);
  2540. #else
  2541. Client cli(host);
  2542. #endif
  2543. cli.set_connection_timeout(std::chrono::seconds(2));
  2544. auto res = cli.Get("/");
  2545. ASSERT_TRUE(!res);
  2546. EXPECT_EQ(Error::Connection, res.error());
  2547. }
  2548. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2549. auto host = "httpcan.org/";
  2550. #ifdef CPPHTTPLIB_SSL_ENABLED
  2551. SSLClient cli(host);
  2552. #else
  2553. Client cli(host);
  2554. #endif
  2555. cli.set_connection_timeout(std::chrono::seconds(2));
  2556. auto res = cli.Get("/");
  2557. ASSERT_TRUE(!res);
  2558. stringstream s;
  2559. s << "error code: " << res.error();
  2560. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2561. }
  2562. TEST(ConnectionErrorTest, InvalidPort) {
  2563. auto host = "localhost";
  2564. auto port = 44380;
  2565. #ifdef CPPHTTPLIB_SSL_ENABLED
  2566. SSLClient cli(host, port);
  2567. #else
  2568. Client cli(host, port);
  2569. #endif
  2570. cli.set_connection_timeout(std::chrono::seconds(2));
  2571. auto res = cli.Get("/");
  2572. ASSERT_TRUE(!res);
  2573. EXPECT_TRUE(Error::Connection == res.error() ||
  2574. Error::ConnectionTimeout == res.error());
  2575. }
  2576. TEST(ConnectionErrorTest, Timeout_Online) {
  2577. auto host = "google.com";
  2578. #ifdef CPPHTTPLIB_SSL_ENABLED
  2579. auto port = 44380;
  2580. SSLClient cli(host, port);
  2581. #else
  2582. auto port = 8080;
  2583. Client cli(host, port);
  2584. #endif
  2585. cli.set_connection_timeout(std::chrono::seconds(2));
  2586. // only probe one address type so that the error reason
  2587. // correlates to the timed-out IPv4, not the unsupported
  2588. // IPv6 connection attempt
  2589. cli.set_address_family(AF_INET);
  2590. auto res = cli.Get("/");
  2591. ASSERT_TRUE(!res);
  2592. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2593. }
  2594. TEST(CancelTest, NoCancel_Online) {
  2595. auto host = "httpbingo.org";
  2596. auto path = std::string{"/range/32"};
  2597. #ifdef CPPHTTPLIB_SSL_ENABLED
  2598. auto port = 443;
  2599. SSLClient cli(host, port);
  2600. #else
  2601. auto port = 80;
  2602. Client cli(host, port);
  2603. #endif
  2604. cli.set_connection_timeout(std::chrono::seconds(5));
  2605. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2608. EXPECT_EQ(StatusCode::OK_200, res->status);
  2609. }
  2610. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2611. // Use /bytes with a large payload so that the DownloadProgress callback
  2612. // (which only fires for Content-Length responses) is invoked before the
  2613. // entire body is received, giving cancellation a chance to fire.
  2614. auto host = "httpbingo.org";
  2615. auto path = std::string{"/bytes/524288"};
  2616. #ifdef CPPHTTPLIB_SSL_ENABLED
  2617. auto port = 443;
  2618. SSLClient cli(host, port);
  2619. #else
  2620. auto port = 80;
  2621. Client cli(host, port);
  2622. #endif
  2623. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2624. cli.set_connection_timeout(std::chrono::seconds(5));
  2625. ASSERT_TRUE(!res);
  2626. EXPECT_EQ(Error::Canceled, res.error());
  2627. }
  2628. TEST(CancelTest, WithCancelLargePayload_Online) {
  2629. auto host = "httpbingo.org";
  2630. auto path = std::string{"/bytes/524288"};
  2631. #ifdef CPPHTTPLIB_SSL_ENABLED
  2632. auto port = 443;
  2633. SSLClient cli(host, port);
  2634. #else
  2635. auto port = 80;
  2636. Client cli(host, port);
  2637. #endif
  2638. cli.set_connection_timeout(std::chrono::seconds(5));
  2639. uint32_t count = 0;
  2640. auto res =
  2641. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2642. ASSERT_TRUE(!res);
  2643. EXPECT_EQ(Error::Canceled, res.error());
  2644. }
  2645. TEST(CancelTest, NoCancelPost) {
  2646. Server svr;
  2647. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2648. res.set_content("Hello World!", "text/plain");
  2649. });
  2650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2651. auto se = detail::scope_exit([&] {
  2652. svr.stop();
  2653. thread.join();
  2654. ASSERT_FALSE(svr.is_running());
  2655. });
  2656. svr.wait_until_ready();
  2657. Client cli(HOST, PORT);
  2658. cli.set_connection_timeout(std::chrono::seconds(5));
  2659. auto res =
  2660. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2661. "application/json", [](uint64_t, uint64_t) { return true; });
  2662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2663. EXPECT_EQ("Hello World!", res->body);
  2664. EXPECT_EQ(StatusCode::OK_200, res->status);
  2665. }
  2666. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2667. Server svr;
  2668. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2669. res.set_content("Hello World!", "text/plain");
  2670. });
  2671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2672. auto se = detail::scope_exit([&] {
  2673. svr.stop();
  2674. thread.join();
  2675. ASSERT_FALSE(svr.is_running());
  2676. });
  2677. svr.wait_until_ready();
  2678. Client cli(HOST, PORT);
  2679. cli.set_connection_timeout(std::chrono::seconds(5));
  2680. auto res =
  2681. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2682. "application/json", [](uint64_t, uint64_t) { return false; });
  2683. ASSERT_TRUE(!res);
  2684. EXPECT_EQ(Error::Canceled, res.error());
  2685. }
  2686. TEST(CancelTest, WithCancelLargePayloadPost) {
  2687. Server svr;
  2688. svr.set_payload_max_length(200 * 1024 * 1024);
  2689. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2690. res.set_content(LARGE_DATA, "text/plain");
  2691. });
  2692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. thread.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, PORT);
  2700. cli.set_payload_max_length(200 * 1024 * 1024);
  2701. cli.set_connection_timeout(std::chrono::seconds(5));
  2702. auto res =
  2703. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2704. "application/json", [](uint64_t, uint64_t) { return false; });
  2705. ASSERT_TRUE(!res);
  2706. EXPECT_EQ(Error::Canceled, res.error());
  2707. }
  2708. TEST(CancelTest, NoCancelPut) {
  2709. Server svr;
  2710. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2711. res.set_content("Hello World!", "text/plain");
  2712. });
  2713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2714. auto se = detail::scope_exit([&] {
  2715. svr.stop();
  2716. thread.join();
  2717. ASSERT_FALSE(svr.is_running());
  2718. });
  2719. svr.wait_until_ready();
  2720. Client cli(HOST, PORT);
  2721. cli.set_connection_timeout(std::chrono::seconds(5));
  2722. auto res =
  2723. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2724. "application/json", [](uint64_t, uint64_t) { return true; });
  2725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2726. EXPECT_EQ("Hello World!", res->body);
  2727. EXPECT_EQ(StatusCode::OK_200, res->status);
  2728. }
  2729. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2730. Server svr;
  2731. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2732. res.set_content("Hello World!", "text/plain");
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. Client cli(HOST, PORT);
  2742. cli.set_connection_timeout(std::chrono::seconds(5));
  2743. auto res =
  2744. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2745. "application/json", [](uint64_t, uint64_t) { return false; });
  2746. ASSERT_TRUE(!res);
  2747. EXPECT_EQ(Error::Canceled, res.error());
  2748. }
  2749. TEST(CancelTest, WithCancelLargePayloadPut) {
  2750. Server svr;
  2751. svr.set_payload_max_length(200 * 1024 * 1024);
  2752. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2753. res.set_content(LARGE_DATA, "text/plain");
  2754. });
  2755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli(HOST, PORT);
  2763. cli.set_payload_max_length(200 * 1024 * 1024);
  2764. cli.set_connection_timeout(std::chrono::seconds(5));
  2765. auto res =
  2766. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2767. "application/json", [](uint64_t, uint64_t) { return false; });
  2768. ASSERT_TRUE(!res);
  2769. EXPECT_EQ(Error::Canceled, res.error());
  2770. }
  2771. TEST(CancelTest, NoCancelPatch) {
  2772. Server svr;
  2773. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2777. auto se = detail::scope_exit([&] {
  2778. svr.stop();
  2779. thread.join();
  2780. ASSERT_FALSE(svr.is_running());
  2781. });
  2782. svr.wait_until_ready();
  2783. Client cli(HOST, PORT);
  2784. cli.set_connection_timeout(std::chrono::seconds(5));
  2785. auto res =
  2786. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2787. "application/json", [](uint64_t, uint64_t) { return true; });
  2788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2789. EXPECT_EQ("Hello World!", res->body);
  2790. EXPECT_EQ(StatusCode::OK_200, res->status);
  2791. }
  2792. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2793. Server svr;
  2794. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2795. res.set_content("Hello World!", "text/plain");
  2796. });
  2797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(HOST, PORT);
  2805. cli.set_connection_timeout(std::chrono::seconds(5));
  2806. auto res =
  2807. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2808. "application/json", [](uint64_t, uint64_t) { return false; });
  2809. ASSERT_TRUE(!res);
  2810. EXPECT_EQ(Error::Canceled, res.error());
  2811. }
  2812. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2813. Server svr;
  2814. svr.set_payload_max_length(200 * 1024 * 1024);
  2815. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2816. res.set_content(LARGE_DATA, "text/plain");
  2817. });
  2818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2819. auto se = detail::scope_exit([&] {
  2820. svr.stop();
  2821. thread.join();
  2822. ASSERT_FALSE(svr.is_running());
  2823. });
  2824. svr.wait_until_ready();
  2825. Client cli(HOST, PORT);
  2826. cli.set_payload_max_length(200 * 1024 * 1024);
  2827. cli.set_connection_timeout(std::chrono::seconds(5));
  2828. auto res =
  2829. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2830. "application/json", [](uint64_t, uint64_t) { return false; });
  2831. ASSERT_TRUE(!res);
  2832. EXPECT_EQ(Error::Canceled, res.error());
  2833. }
  2834. TEST(CancelTest, NoCancelDelete) {
  2835. Server svr;
  2836. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2837. res.set_content("Hello World!", "text/plain");
  2838. });
  2839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2840. auto se = detail::scope_exit([&] {
  2841. svr.stop();
  2842. thread.join();
  2843. ASSERT_FALSE(svr.is_running());
  2844. });
  2845. svr.wait_until_ready();
  2846. Client cli(HOST, PORT);
  2847. cli.set_connection_timeout(std::chrono::seconds(5));
  2848. auto res =
  2849. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2850. "application/json", [](uint64_t, uint64_t) { return true; });
  2851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2852. EXPECT_EQ("Hello World!", res->body);
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2856. Server svr;
  2857. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2858. res.set_content("Hello World!", "text/plain");
  2859. });
  2860. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2861. auto se = detail::scope_exit([&] {
  2862. svr.stop();
  2863. thread.join();
  2864. ASSERT_FALSE(svr.is_running());
  2865. });
  2866. svr.wait_until_ready();
  2867. Client cli(HOST, PORT);
  2868. cli.set_connection_timeout(std::chrono::seconds(5));
  2869. auto res =
  2870. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2871. "application/json", [](uint64_t, uint64_t) { return false; });
  2872. ASSERT_TRUE(!res);
  2873. EXPECT_EQ(Error::Canceled, res.error());
  2874. }
  2875. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2876. Server svr;
  2877. svr.set_payload_max_length(200 * 1024 * 1024);
  2878. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2879. res.set_content(LARGE_DATA, "text/plain");
  2880. });
  2881. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2882. auto se = detail::scope_exit([&] {
  2883. svr.stop();
  2884. thread.join();
  2885. ASSERT_FALSE(svr.is_running());
  2886. });
  2887. svr.wait_until_ready();
  2888. Client cli(HOST, PORT);
  2889. cli.set_payload_max_length(200 * 1024 * 1024);
  2890. cli.set_connection_timeout(std::chrono::seconds(5));
  2891. auto res =
  2892. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2893. "application/json", [](uint64_t, uint64_t) { return false; });
  2894. ASSERT_TRUE(!res);
  2895. EXPECT_EQ(Error::Canceled, res.error());
  2896. }
  2897. // One stop() from another thread ends a request that waits for the response
  2898. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2899. Server svr;
  2900. std::atomic<bool> received{false};
  2901. std::atomic<bool> done{false};
  2902. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2903. received.store(true);
  2904. while (!done.load()) {
  2905. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2906. }
  2907. res.set_content("Hello World!", "text/plain");
  2908. });
  2909. auto port = svr.bind_to_any_port(HOST);
  2910. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2911. Client cli(HOST, port);
  2912. cli.set_read_timeout(std::chrono::seconds(30));
  2913. std::future<Result> request;
  2914. auto se = detail::scope_exit([&] {
  2915. done.store(true);
  2916. svr.stop();
  2917. thread.join();
  2918. ASSERT_FALSE(svr.is_running());
  2919. });
  2920. svr.wait_until_ready();
  2921. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  2922. for (int i = 0; i < 500 && !received.load(); ++i) {
  2923. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2924. }
  2925. ASSERT_TRUE(received.load());
  2926. // Let the client block in the wait for the response
  2927. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2928. auto start = std::chrono::steady_clock::now();
  2929. cli.stop();
  2930. ASSERT_EQ(std::future_status::ready,
  2931. request.wait_for(std::chrono::seconds(5)));
  2932. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  2933. auto res = request.get();
  2934. ASSERT_TRUE(!res);
  2935. EXPECT_EQ(Error::Read, res.error());
  2936. }
  2937. static std::string remove_whitespace(const std::string &input) {
  2938. std::string output;
  2939. output.reserve(input.size());
  2940. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2941. [](unsigned char c) { return !std::isspace(c); });
  2942. return output;
  2943. }
  2944. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2945. auto host = "httpbingo.org";
  2946. auto path = std::string{"/basic-auth/hello/world"};
  2947. #ifdef CPPHTTPLIB_SSL_ENABLED
  2948. auto port = 443;
  2949. SSLClient cli(host, port);
  2950. #else
  2951. auto port = 80;
  2952. Client cli(host, port);
  2953. #endif
  2954. {
  2955. auto res = cli.Get(path);
  2956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2957. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2958. }
  2959. {
  2960. auto res = cli.Get(
  2961. path, Headers{make_basic_authentication_header("hello", "world")});
  2962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2963. auto body = remove_whitespace(res->body);
  2964. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2965. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2966. EXPECT_EQ(StatusCode::OK_200, res->status);
  2967. }
  2968. {
  2969. cli.set_basic_auth("hello", "world");
  2970. auto res = cli.Get(path);
  2971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2972. auto body = remove_whitespace(res->body);
  2973. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2974. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2975. EXPECT_EQ(StatusCode::OK_200, res->status);
  2976. }
  2977. {
  2978. cli.set_basic_auth("hello", "bad");
  2979. auto res = cli.Get(path);
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2982. }
  2983. {
  2984. cli.set_basic_auth("bad", "world");
  2985. auto res = cli.Get(path);
  2986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2987. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2988. }
  2989. }
  2990. #ifdef CPPHTTPLIB_SSL_ENABLED
  2991. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2992. auto host = "httpbingo.org";
  2993. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2994. auto paths = std::vector<std::string>{
  2995. "/digest-auth/auth/hello/world/MD5",
  2996. "/digest-auth/auth/hello/world/SHA-256",
  2997. };
  2998. auto port = 443;
  2999. SSLClient cli(host, port);
  3000. {
  3001. auto res = cli.Get(unauth_path);
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3004. }
  3005. {
  3006. cli.set_digest_auth("hello", "world");
  3007. for (const auto &path : paths) {
  3008. auto res = cli.Get(path.c_str());
  3009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3010. auto body = remove_whitespace(res->body);
  3011. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3012. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3013. EXPECT_EQ(StatusCode::OK_200, res->status);
  3014. }
  3015. cli.set_digest_auth("hello", "bad");
  3016. for (const auto &path : paths) {
  3017. auto res = cli.Get(path.c_str());
  3018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3019. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3020. }
  3021. }
  3022. }
  3023. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3024. // comma-separated list of challenges, and each challenge may itself carry a
  3025. // comma-separated auth-param list, so a server can legally offer Basic
  3026. // before Digest, either as two field lines or packed into one. Runs one 401
  3027. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3028. // value() joins them in receipt order) and checks that the retry carries a
  3029. // well-formed Digest Authorization header naming expected_realm.
  3030. static void
  3031. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3032. const std::string &expected_realm) {
  3033. std::atomic<int> hits{0};
  3034. Server svr;
  3035. svr.Get("/x", [&](const Request &req, Response &res) {
  3036. if (++hits == 1) {
  3037. res.status = StatusCode::Unauthorized_401;
  3038. for (const auto &challenge : challenges) {
  3039. res.set_header("WWW-Authenticate", challenge);
  3040. }
  3041. } else {
  3042. auto authorization = req.get_header_value("Authorization");
  3043. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3044. EXPECT_NE(std::string::npos,
  3045. authorization.find("realm=\"" + expected_realm + "\""));
  3046. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3047. res.set_content("ok", "text/plain");
  3048. }
  3049. });
  3050. auto port = svr.bind_to_any_port(HOST);
  3051. std::thread t([&]() { svr.listen_after_bind(); });
  3052. auto se = detail::scope_exit([&] {
  3053. svr.stop();
  3054. t.join();
  3055. });
  3056. svr.wait_until_ready();
  3057. Client cli(HOST, port);
  3058. cli.set_digest_auth("hello", "world");
  3059. auto res = cli.Get("/x");
  3060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3061. EXPECT_EQ(2, hits.load());
  3062. }
  3063. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3064. static const char *kDigestChallenge =
  3065. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3066. "algorithm=MD5";
  3067. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3068. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3069. "testrealm");
  3070. }
  3071. // Same challenge list with the schemes in the opposite order, to make sure
  3072. // the fix above didn't just special-case "Basic first".
  3073. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3074. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3075. "testrealm");
  3076. }
  3077. // A comma inside a quoted auth-param value must not be mistaken for the
  3078. // separator between two challenges (or two auth-params).
  3079. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3080. run_digest_challenge_list_test(
  3081. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3082. "algorithm=MD5"},
  3083. "test,realm");
  3084. }
  3085. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3086. // the params and leaves out the fragment.
  3087. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3088. Server svr;
  3089. std::string uri, target;
  3090. svr.Get("/a b", [&](const Request &req, Response &res) {
  3091. auto auth = req.get_header_value("Authorization");
  3092. if (auth.empty()) {
  3093. res.status = StatusCode::Unauthorized_401;
  3094. res.set_header("WWW-Authenticate",
  3095. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3096. return;
  3097. }
  3098. auto b = auth.find("uri=\"") + 5;
  3099. uri = auth.substr(b, auth.find('"', b) - b);
  3100. target = req.target;
  3101. });
  3102. auto port = svr.bind_to_any_port(HOST);
  3103. std::thread t([&]() { svr.listen_after_bind(); });
  3104. auto se = detail::scope_exit([&] {
  3105. svr.stop();
  3106. t.join();
  3107. });
  3108. svr.wait_until_ready();
  3109. Client cli(HOST, port);
  3110. cli.set_digest_auth("hello", "world");
  3111. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3113. EXPECT_EQ("/a%20b?x=1", target);
  3114. EXPECT_EQ(target, uri);
  3115. }
  3116. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3117. // make_digest_authentication_header() dereferences both unconditionally, so
  3118. // a server sending a challenge missing either one must not be treated as
  3119. // usable -- doing so used to crash the client with std::out_of_range.
  3120. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3121. Server svr;
  3122. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3123. res.status = StatusCode::Unauthorized_401;
  3124. res.set_header("WWW-Authenticate", challenge);
  3125. });
  3126. auto port = svr.bind_to_any_port(HOST);
  3127. std::thread t([&]() { svr.listen_after_bind(); });
  3128. auto se = detail::scope_exit([&] {
  3129. svr.stop();
  3130. t.join();
  3131. });
  3132. svr.wait_until_ready();
  3133. Client cli(HOST, port);
  3134. cli.set_digest_auth("hello", "world");
  3135. auto res = cli.Get("/x");
  3136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3137. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3138. }
  3139. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3140. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3141. }
  3142. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3143. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3144. }
  3145. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3146. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3147. }
  3148. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3149. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3150. // when storing the values, so the header builder has to re-escape them (and
  3151. // keep algorithm a bare token); otherwise the value breaks out of its
  3152. // quoted-string and injects extra auth-params into the client's Authorization.
  3153. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3154. std::atomic<int> hits{0};
  3155. std::string authorization;
  3156. Server svr;
  3157. svr.Get("/x", [&](const Request &req, Response &res) {
  3158. if (++hits == 1) {
  3159. res.status = StatusCode::Unauthorized_401;
  3160. // On the wire the quotes embedded in the values are backslash-escaped.
  3161. res.set_header("WWW-Authenticate",
  3162. "Digest realm=\"testrealm\", "
  3163. "nonce=\"n\\\"; injected=\\\"x\", "
  3164. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3165. } else {
  3166. authorization = req.get_header_value("Authorization");
  3167. res.set_content("ok", "text/plain");
  3168. }
  3169. });
  3170. auto port = svr.bind_to_any_port(HOST);
  3171. std::thread t([&]() { svr.listen_after_bind(); });
  3172. auto se = detail::scope_exit([&] {
  3173. svr.stop();
  3174. t.join();
  3175. });
  3176. svr.wait_until_ready();
  3177. Client cli(HOST, port);
  3178. cli.set_digest_auth("hello", "world");
  3179. auto res = cli.Get("/x");
  3180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3181. EXPECT_EQ(2, hits.load());
  3182. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3183. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3184. // inside its quoted-string rather than starting an "injected" auth-param.
  3185. EXPECT_NE(std::string::npos,
  3186. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3187. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3188. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3189. }
  3190. #endif
  3191. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3192. auto host = "google.com";
  3193. auto another_host = "example.com";
  3194. auto wrong_ip = "0.0.0.0";
  3195. #ifdef CPPHTTPLIB_SSL_ENABLED
  3196. SSLClient cli(host);
  3197. #else
  3198. Client cli(host);
  3199. #endif
  3200. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3201. auto res = cli.Get("/");
  3202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3203. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3204. }
  3205. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3206. auto host = "google.com";
  3207. auto wrong_ip = "0.0.0.0";
  3208. #ifdef CPPHTTPLIB_SSL_ENABLED
  3209. SSLClient cli(host);
  3210. #else
  3211. Client cli(host);
  3212. #endif
  3213. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3214. auto res = cli.Get("/");
  3215. ASSERT_TRUE(!res);
  3216. EXPECT_EQ(Error::Connection, res.error());
  3217. }
  3218. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3219. // A mapped value that is not an IP literal must be resolved. "localhost"
  3220. // resolves from the hosts file, so this test needs no external DNS.
  3221. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3222. auto host = "target.invalid";
  3223. Server svr;
  3224. std::string received_host;
  3225. svr.Get("/hi", [&](const Request &req, Response &res) {
  3226. received_host = req.get_header_value("Host");
  3227. res.set_content("Hello World!", "text/plain");
  3228. });
  3229. auto port = svr.bind_to_any_port(HOST);
  3230. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3231. auto se = detail::scope_exit([&] {
  3232. svr.stop();
  3233. thread.join();
  3234. ASSERT_FALSE(svr.is_running());
  3235. });
  3236. svr.wait_until_ready();
  3237. Client cli(host, port);
  3238. cli.set_direct_hostname_addr_map({{host, HOST}});
  3239. auto res = cli.Get("/hi");
  3240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3241. EXPECT_EQ(StatusCode::OK_200, res->status);
  3242. // The mapping only redirects the connection; the identity stays host_.
  3243. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3244. }
  3245. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3246. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3247. auto host = "target.invalid";
  3248. Server svr;
  3249. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3250. res.set_content("Hello World!", "text/plain");
  3251. });
  3252. auto port = svr.bind_to_any_port("127.0.0.1");
  3253. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3254. auto se = detail::scope_exit([&] {
  3255. svr.stop();
  3256. thread.join();
  3257. ASSERT_FALSE(svr.is_running());
  3258. });
  3259. svr.wait_until_ready();
  3260. Client cli(host, port);
  3261. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3262. auto res = cli.Get("/hi");
  3263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3264. EXPECT_EQ(StatusCode::OK_200, res->status);
  3265. }
  3266. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3267. // An empty mapped value must leave host_ as the connection target. Without
  3268. // that guard the empty value would become the host argument, getaddrinfo
  3269. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3270. // loopback - silently connecting somewhere the caller never asked for.
  3271. // The server listens on loopback, so such a fallback would succeed and is
  3272. // therefore observable as a failure of this test.
  3273. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3274. Server svr;
  3275. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3276. res.set_content("Hello World!", "text/plain");
  3277. });
  3278. auto port = svr.bind_to_any_port(HOST);
  3279. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3280. auto se = detail::scope_exit([&] {
  3281. svr.stop();
  3282. thread.join();
  3283. ASSERT_FALSE(svr.is_running());
  3284. });
  3285. svr.wait_until_ready();
  3286. Client cli(blackhole, port);
  3287. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3288. cli.set_connection_timeout(1);
  3289. auto res = cli.Get("/hi");
  3290. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3291. }
  3292. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3293. auto host = "target.invalid";
  3294. Server svr;
  3295. std::string received_host;
  3296. svr.Get("/hi", [&](const Request &req, Response &res) {
  3297. received_host = req.get_header_value("Host");
  3298. res.set_content("Hello World!", "text/plain");
  3299. });
  3300. auto port = svr.bind_to_any_port("127.0.0.1");
  3301. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3302. auto se = detail::scope_exit([&] {
  3303. svr.stop();
  3304. thread.join();
  3305. ASSERT_FALSE(svr.is_running());
  3306. });
  3307. svr.wait_until_ready();
  3308. Client cli(host, port);
  3309. #pragma GCC diagnostic push
  3310. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3311. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3312. #pragma GCC diagnostic pop
  3313. auto res = cli.Get("/hi");
  3314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3315. EXPECT_EQ(StatusCode::OK_200, res->status);
  3316. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3317. }
  3318. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3319. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3320. Server svr;
  3321. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3322. res.set_content("Hello World!", "text/plain");
  3323. });
  3324. auto port = svr.bind_to_any_port("127.0.0.1");
  3325. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3326. auto se = detail::scope_exit([&] {
  3327. svr.stop();
  3328. thread.join();
  3329. ASSERT_FALSE(svr.is_running());
  3330. });
  3331. svr.wait_until_ready();
  3332. Client cli("127.0.0.1", port);
  3333. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3334. cli.set_connection_timeout(1);
  3335. auto res = cli.Get("/hi");
  3336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3337. EXPECT_EQ(StatusCode::OK_200, res->status);
  3338. }
  3339. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3340. auto host = "httpbingo.org";
  3341. auto path = std::string{"/absolute-redirect/3"};
  3342. #ifdef CPPHTTPLIB_SSL_ENABLED
  3343. SSLClient cli(host);
  3344. #else
  3345. Client cli(host);
  3346. #endif
  3347. cli.set_follow_location(true);
  3348. auto res = cli.Get(path);
  3349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3350. EXPECT_EQ(StatusCode::OK_200, res->status);
  3351. }
  3352. TEST(RedirectTest, Redirect_Online) {
  3353. auto host = "httpbingo.org";
  3354. auto path = std::string{"/redirect/3"};
  3355. #ifdef CPPHTTPLIB_SSL_ENABLED
  3356. SSLClient cli(host);
  3357. #else
  3358. Client cli(host);
  3359. #endif
  3360. cli.set_follow_location(true);
  3361. auto res = cli.Get(path);
  3362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3363. EXPECT_EQ(StatusCode::OK_200, res->status);
  3364. }
  3365. TEST(RelativeRedirectTest, Redirect_Online) {
  3366. auto host = "httpbingo.org";
  3367. auto path = std::string{"/relative-redirect/3"};
  3368. #ifdef CPPHTTPLIB_SSL_ENABLED
  3369. SSLClient cli(host);
  3370. #else
  3371. Client cli(host);
  3372. #endif
  3373. cli.set_follow_location(true);
  3374. auto res = cli.Get(path);
  3375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3376. EXPECT_EQ(StatusCode::OK_200, res->status);
  3377. }
  3378. TEST(TooManyRedirectTest, Redirect_Online) {
  3379. auto host = "httpbingo.org";
  3380. auto path = std::string{"/redirect/21"};
  3381. #ifdef CPPHTTPLIB_SSL_ENABLED
  3382. SSLClient cli(host);
  3383. #else
  3384. Client cli(host);
  3385. #endif
  3386. cli.set_follow_location(true);
  3387. auto res = cli.Get(path);
  3388. ASSERT_TRUE(!res);
  3389. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3390. }
  3391. #ifdef CPPHTTPLIB_SSL_ENABLED
  3392. TEST(YahooRedirectTest, Redirect_Online) {
  3393. Client cli("yahoo.com");
  3394. auto res = cli.Get("/");
  3395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3396. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3397. cli.set_follow_location(true);
  3398. res = cli.Get("/");
  3399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3400. EXPECT_EQ(StatusCode::OK_200, res->status);
  3401. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3402. }
  3403. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3404. #define REDIR_HOST "httpbingo.org"
  3405. #define REDIR_PATH "/redirect-to"
  3406. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3407. SSLClient cli(REDIR_HOST);
  3408. cli.set_follow_location(true);
  3409. auto res =
  3410. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3412. EXPECT_EQ(StatusCode::OK_200, res->status);
  3413. }
  3414. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3415. SSLClient cli(REDIR_HOST);
  3416. cli.set_follow_location(true);
  3417. Params params;
  3418. params.emplace("url", "http://example.com");
  3419. params.emplace("status_code", "302");
  3420. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3422. EXPECT_EQ(StatusCode::OK_200, res->status);
  3423. }
  3424. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3425. SSLClient cli(REDIR_HOST);
  3426. cli.set_follow_location(true);
  3427. Params params;
  3428. params.emplace("url", "http://example.com");
  3429. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3431. EXPECT_EQ(StatusCode::OK_200, res->status);
  3432. }
  3433. TEST(UrlWithSpace, Redirect_Online) {
  3434. SSLClient cli("edge.forgecdn.net");
  3435. cli.set_follow_location(true);
  3436. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(StatusCode::OK_200, res->status);
  3439. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3440. }
  3441. #endif
  3442. #if !defined(_WIN32) && !defined(_WIN64)
  3443. TEST(ReceiveSignals, Signal) {
  3444. auto setupSignalHandlers = []() {
  3445. struct sigaction act;
  3446. sigemptyset(&act.sa_mask);
  3447. act.sa_flags = SA_SIGINFO;
  3448. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3449. switch (sig) {
  3450. case SIGINT:
  3451. default: break;
  3452. }
  3453. };
  3454. ::sigaction(SIGINT, &act, nullptr);
  3455. };
  3456. Server svr;
  3457. int port = 0;
  3458. auto thread = std::thread([&]() {
  3459. setupSignalHandlers();
  3460. port = svr.bind_to_any_port(HOST);
  3461. svr.listen_after_bind();
  3462. });
  3463. auto se = detail::scope_exit([&] {
  3464. svr.stop();
  3465. thread.join();
  3466. ASSERT_FALSE(svr.is_running());
  3467. });
  3468. svr.wait_until_ready();
  3469. ASSERT_TRUE(svr.is_running());
  3470. pthread_kill(thread.native_handle(), SIGINT);
  3471. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3472. ASSERT_TRUE(svr.is_running());
  3473. }
  3474. #endif
  3475. TEST(RedirectToDifferentPort, Redirect) {
  3476. Server svr1;
  3477. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3478. res.set_content("Hello World!", "text/plain");
  3479. });
  3480. int svr1_port = 0;
  3481. auto thread1 = std::thread([&]() {
  3482. svr1_port = svr1.bind_to_any_port(HOST);
  3483. svr1.listen_after_bind();
  3484. });
  3485. Server svr2;
  3486. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3487. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3488. });
  3489. int svr2_port = 0;
  3490. auto thread2 = std::thread([&]() {
  3491. svr2_port = svr2.bind_to_any_port(HOST);
  3492. svr2.listen_after_bind();
  3493. });
  3494. auto se = detail::scope_exit([&] {
  3495. svr2.stop();
  3496. thread2.join();
  3497. svr1.stop();
  3498. thread1.join();
  3499. ASSERT_FALSE(svr2.is_running());
  3500. ASSERT_FALSE(svr1.is_running());
  3501. });
  3502. svr1.wait_until_ready();
  3503. svr2.wait_until_ready();
  3504. Client cli("localhost", svr2_port);
  3505. cli.set_follow_location(true);
  3506. auto res = cli.Get("/2");
  3507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3508. EXPECT_EQ(StatusCode::OK_200, res->status);
  3509. EXPECT_EQ("Hello World!", res->body);
  3510. }
  3511. // GET /redir on one server redirects to /target on another port, so the
  3512. // client follows it with a new client.
  3513. static Result
  3514. GetThroughRedirectToDifferentPort(Server::Handler target,
  3515. const std::function<void(Client &)> &setup,
  3516. const Headers &headers = Headers()) {
  3517. Server target_svr;
  3518. target_svr.Get("/target", target);
  3519. int target_port = 0;
  3520. auto target_thread = std::thread([&]() {
  3521. target_port = target_svr.bind_to_any_port(HOST);
  3522. target_svr.listen_after_bind();
  3523. });
  3524. Server origin_svr;
  3525. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3526. res.set_redirect(
  3527. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3528. });
  3529. int origin_port = 0;
  3530. auto origin_thread = std::thread([&]() {
  3531. origin_port = origin_svr.bind_to_any_port(HOST);
  3532. origin_svr.listen_after_bind();
  3533. });
  3534. auto se = detail::scope_exit([&] {
  3535. origin_svr.stop();
  3536. origin_thread.join();
  3537. target_svr.stop();
  3538. target_thread.join();
  3539. });
  3540. target_svr.wait_until_ready();
  3541. origin_svr.wait_until_ready();
  3542. Client cli("localhost", origin_port);
  3543. cli.set_follow_location(true);
  3544. setup(cli);
  3545. return cli.Get("/redir", headers);
  3546. }
  3547. static void
  3548. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3549. std::string captured_authorization;
  3550. auto result = GetThroughRedirectToDifferentPort(
  3551. [&](const Request &req, Response &res) {
  3552. captured_authorization = req.get_header_value("Authorization");
  3553. res.set_content("OK", "text/plain");
  3554. },
  3555. set_auth);
  3556. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3557. EXPECT_EQ(StatusCode::OK_200, result->status);
  3558. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3559. EXPECT_TRUE(captured_authorization.empty());
  3560. }
  3561. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3562. TestDoNotForwardCredentialsOnRedirect(
  3563. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3564. }
  3565. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3566. TestDoNotForwardCredentialsOnRedirect(
  3567. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3568. }
  3569. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3570. std::string captured_cookie;
  3571. auto result = GetThroughRedirectToDifferentPort(
  3572. [&](const Request &req, Response &res) {
  3573. captured_cookie = req.get_header_value("Cookie");
  3574. res.set_content("OK", "text/plain");
  3575. },
  3576. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3577. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3578. EXPECT_EQ(StatusCode::OK_200, result->status);
  3579. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3580. EXPECT_TRUE(captured_cookie.empty());
  3581. }
  3582. TEST(RedirectToSamePort, ForwardCookie) {
  3583. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3584. // header so that ordinary session flows keep working.
  3585. Server svr;
  3586. std::string captured_cookie;
  3587. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3588. res.set_redirect("/target", 302);
  3589. });
  3590. svr.Get("/target", [&](const Request &req, Response &res) {
  3591. captured_cookie = req.get_header_value("Cookie");
  3592. res.set_content("OK", "text/plain");
  3593. });
  3594. auto port = svr.bind_to_any_port(HOST);
  3595. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3596. auto se = detail::scope_exit([&] {
  3597. svr.stop();
  3598. thread.join();
  3599. ASSERT_FALSE(svr.is_running());
  3600. });
  3601. svr.wait_until_ready();
  3602. Client cli(HOST, port);
  3603. cli.set_follow_location(true);
  3604. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3605. auto res = cli.Get("/redir", headers);
  3606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3607. EXPECT_EQ(StatusCode::OK_200, res->status);
  3608. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3609. }
  3610. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3611. std::string authorization;
  3612. std::string trace_id;
  3613. auto result = GetThroughRedirectToDifferentPort(
  3614. [&](const Request &req, Response &res) {
  3615. authorization = req.get_header_value("Authorization");
  3616. trace_id = req.get_header_value("X-Trace-Id");
  3617. res.set_content("OK", "text/plain");
  3618. },
  3619. [](Client &cli) {
  3620. cli.set_default_headers(
  3621. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3622. });
  3623. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3624. EXPECT_EQ(StatusCode::OK_200, result->status);
  3625. // Like a header given with the request, a default one goes along unless it
  3626. // carries credentials (RFC 9110 15.4).
  3627. EXPECT_TRUE(authorization.empty());
  3628. EXPECT_EQ("42", trace_id);
  3629. }
  3630. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3631. auto result = GetThroughRedirectToDifferentPort(
  3632. [](const Request &, Response &res) {
  3633. res.set_content(std::string(2048, 'x'), "text/plain");
  3634. },
  3635. [](Client &cli) { cli.set_payload_max_length(1024); });
  3636. EXPECT_FALSE(result);
  3637. }
  3638. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3639. auto result = GetThroughRedirectToDifferentPort(
  3640. [](const Request &req, Response &res) {
  3641. // Answer after a second, or once the client gives up.
  3642. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3643. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3644. }
  3645. res.set_content("late", "text/plain");
  3646. },
  3647. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3648. ASSERT_FALSE(result);
  3649. EXPECT_EQ(Error::Read, result.error());
  3650. }
  3651. #ifdef CPPHTTPLIB_SSL_ENABLED
  3652. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3653. auto result = GetThroughRedirectToDifferentPort(
  3654. [](const Request &, Response &res) {
  3655. res.status = StatusCode::Unauthorized_401;
  3656. res.set_header("WWW-Authenticate",
  3657. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3658. },
  3659. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3660. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3661. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3662. }
  3663. #endif
  3664. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3665. Server svr;
  3666. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3667. // Port number that overflows int — should not crash
  3668. res.set_redirect("http://localhost:99999999999999999999/target");
  3669. });
  3670. auto port = svr.bind_to_any_port(HOST);
  3671. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3672. auto se = detail::scope_exit([&] {
  3673. svr.stop();
  3674. thread.join();
  3675. ASSERT_FALSE(svr.is_running());
  3676. });
  3677. svr.wait_until_ready();
  3678. Client cli(HOST, port);
  3679. cli.set_follow_location(true);
  3680. auto res = cli.Get("/redir");
  3681. // Should fail gracefully, not crash (no valid response due to bad port)
  3682. EXPECT_FALSE(res);
  3683. }
  3684. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3685. Server svr;
  3686. auto port = svr.bind_to_any_port(HOST);
  3687. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3688. // The server's own port followed by junk must not be followed
  3689. res.set_redirect("http://" + std::string(HOST) + ":" +
  3690. std::to_string(port) + "junk/target");
  3691. });
  3692. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3693. res.set_content("target", "text/plain");
  3694. });
  3695. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3696. auto se = detail::scope_exit([&] {
  3697. svr.stop();
  3698. thread.join();
  3699. ASSERT_FALSE(svr.is_running());
  3700. });
  3701. svr.wait_until_ready();
  3702. Client cli(HOST, port);
  3703. cli.set_follow_location(true);
  3704. auto res = cli.Get("/redir");
  3705. EXPECT_FALSE(res);
  3706. }
  3707. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3708. Server svr;
  3709. std::atomic<bool> followed{false};
  3710. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3711. res.status = StatusCode::NotModified_304;
  3712. res.set_header("Location", "/target");
  3713. });
  3714. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3715. res.status = StatusCode::UseProxy_305;
  3716. res.set_header("Location", "/target");
  3717. });
  3718. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3719. followed = true;
  3720. res.set_content("target", "text/plain");
  3721. });
  3722. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3723. auto se = detail::scope_exit([&] {
  3724. svr.stop();
  3725. th.join();
  3726. ASSERT_FALSE(svr.is_running());
  3727. });
  3728. svr.wait_until_ready();
  3729. Client cli("localhost", PORT);
  3730. cli.set_follow_location(true);
  3731. auto res = cli.Get("/304");
  3732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3733. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3734. res = cli.Get("/305");
  3735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3736. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3737. EXPECT_FALSE(followed);
  3738. }
  3739. TEST(RedirectFromPageWithContent, Redirect) {
  3740. Server svr;
  3741. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3742. res.set_content("___", "text/plain");
  3743. res.set_redirect("/2");
  3744. });
  3745. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3746. res.set_content("Hello World!", "text/plain");
  3747. });
  3748. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3749. auto se = detail::scope_exit([&] {
  3750. svr.stop();
  3751. th.join();
  3752. ASSERT_FALSE(svr.is_running());
  3753. });
  3754. svr.wait_until_ready();
  3755. {
  3756. Client cli("localhost", PORT);
  3757. cli.set_follow_location(true);
  3758. std::string body;
  3759. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3760. body.append(data, data_length);
  3761. return true;
  3762. });
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. EXPECT_EQ(StatusCode::OK_200, res->status);
  3765. EXPECT_EQ("Hello World!", body);
  3766. }
  3767. {
  3768. Client cli("localhost", PORT);
  3769. std::string body;
  3770. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3771. body.append(data, data_length);
  3772. return true;
  3773. });
  3774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3775. EXPECT_EQ(StatusCode::Found_302, res->status);
  3776. EXPECT_EQ("___", body);
  3777. }
  3778. }
  3779. // A server can close the connection after a request with "Connection: close"
  3780. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3781. // redirected request must go out on a new connection.
  3782. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3783. #ifndef _WIN32
  3784. signal(SIGPIPE, SIG_IGN);
  3785. #endif
  3786. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3787. default_socket_options(srv);
  3788. sockaddr_in addr{};
  3789. addr.sin_family = AF_INET;
  3790. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3791. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3792. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3793. ASSERT_EQ(0, ::listen(srv, 2));
  3794. auto send_text = [](socket_t sock, const std::string &text) {
  3795. ::send(sock,
  3796. #ifdef _WIN32
  3797. static_cast<const char *>(text.c_str()),
  3798. static_cast<int>(text.size()),
  3799. #else
  3800. text.c_str(), text.size(),
  3801. #endif
  3802. 0);
  3803. };
  3804. auto reused = false;
  3805. auto server_thread = std::thread([&] {
  3806. char buf[4096];
  3807. auto first = ::accept(srv, nullptr, nullptr);
  3808. if (first == INVALID_SOCKET) { return; }
  3809. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3810. ::recv(first, buf, sizeof(buf), 0);
  3811. send_text(
  3812. first,
  3813. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3814. auto next = first;
  3815. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3816. reused = true;
  3817. } else {
  3818. detail::close_socket(first);
  3819. next = ::accept(srv, nullptr, nullptr);
  3820. if (next == INVALID_SOCKET) { return; }
  3821. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3822. ::recv(next, buf, sizeof(buf), 0);
  3823. }
  3824. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3825. "Connection: close\r\n\r\nok");
  3826. detail::close_socket(next);
  3827. });
  3828. Client cli("127.0.0.1", PORT + 2);
  3829. cli.set_follow_location(true);
  3830. cli.set_read_timeout(5, 0);
  3831. auto res = cli.Get("/1");
  3832. server_thread.join();
  3833. detail::close_socket(srv);
  3834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3835. EXPECT_EQ(StatusCode::OK_200, res->status);
  3836. EXPECT_EQ("ok", res->body);
  3837. EXPECT_FALSE(reused);
  3838. }
  3839. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3840. Server svr;
  3841. auto port_str = std::to_string(PORT);
  3842. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3843. auto expected_host = "[::1]:" + port_str;
  3844. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3845. res.set_content("___", "text/plain");
  3846. // res.set_redirect("/2");
  3847. res.set_redirect(redirect_url);
  3848. });
  3849. svr.Get("/2", [&](const Request &req, Response &res) {
  3850. auto host_header = req.headers.find("Host");
  3851. ASSERT_TRUE(host_header != req.headers.end());
  3852. EXPECT_EQ(expected_host, host_header->second);
  3853. res.set_content("Hello World!", "text/plain");
  3854. });
  3855. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3856. auto se = detail::scope_exit([&] {
  3857. svr.stop();
  3858. th.join();
  3859. ASSERT_FALSE(svr.is_running());
  3860. });
  3861. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3862. // actually starts anything, so the condition !svr.is_running() will
  3863. // always remain true, and the loop never stops.
  3864. // This basically counts how many milliseconds have passed since the
  3865. // call to svr.listen(), and if after 5 seconds nothing started yet
  3866. // aborts the test.
  3867. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3868. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3869. ASSERT_LT(milliseconds, 5000U);
  3870. }
  3871. {
  3872. Client cli("::1", PORT);
  3873. cli.set_follow_location(true);
  3874. std::string body;
  3875. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3876. body.append(data, data_length);
  3877. return true;
  3878. });
  3879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3880. EXPECT_EQ(StatusCode::OK_200, res->status);
  3881. EXPECT_EQ("Hello World!", body);
  3882. }
  3883. {
  3884. Client cli("::1", PORT);
  3885. std::string body;
  3886. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3887. body.append(data, data_length);
  3888. return true;
  3889. });
  3890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3891. EXPECT_EQ(StatusCode::Found_302, res->status);
  3892. EXPECT_EQ("___", body);
  3893. }
  3894. }
  3895. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3896. Server svr;
  3897. svr.Get("/foo", [](const Request &req, Response &res) {
  3898. auto a = req.params.find("a");
  3899. if (a != req.params.end()) {
  3900. res.set_content((*a).second, "text/plain");
  3901. res.status = StatusCode::OK_200;
  3902. } else {
  3903. res.status = StatusCode::BadRequest_400;
  3904. }
  3905. });
  3906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3907. auto se = detail::scope_exit([&] {
  3908. svr.stop();
  3909. thread.join();
  3910. ASSERT_FALSE(svr.is_running());
  3911. });
  3912. svr.wait_until_ready();
  3913. {
  3914. Client cli(HOST, PORT);
  3915. cli.set_path_encode(false);
  3916. auto res = cli.Get("/foo?a=explicitly+encoded");
  3917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3918. EXPECT_EQ(StatusCode::OK_200, res->status);
  3919. // This expects it back with a space, as the `+` won't have been
  3920. // url-encoded, and server-side the params get decoded turning `+`
  3921. // into spaces.
  3922. EXPECT_EQ("explicitly encoded", res->body);
  3923. }
  3924. }
  3925. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3926. // When path encoding is disabled the client must transmit the supplied
  3927. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3928. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3929. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3930. // than a space (0x20). Assert on the raw wire target to catch this.
  3931. Server svr;
  3932. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3933. svr.Get("/foo", [&](const Request &req, Response &res) {
  3934. EXPECT_EQ(expected_target, req.target);
  3935. res.status = StatusCode::OK_200;
  3936. });
  3937. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3938. auto se = detail::scope_exit([&] {
  3939. svr.stop();
  3940. thread.join();
  3941. ASSERT_FALSE(svr.is_running());
  3942. });
  3943. svr.wait_until_ready();
  3944. {
  3945. Client cli(HOST, PORT);
  3946. cli.set_path_encode(false);
  3947. auto res = cli.Get(expected_target.c_str());
  3948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3949. EXPECT_EQ(StatusCode::OK_200, res->status);
  3950. }
  3951. }
  3952. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3953. // `open_stream()` used to skip the path encoding that the buffered send
  3954. // path applies, so the same `path` produced different bytes in the request
  3955. // line depending on which API was used. Assert the two agree.
  3956. Server svr;
  3957. std::string target;
  3958. svr.Get(".*", [&](const Request &req, Response &res) {
  3959. target = req.target;
  3960. res.status = StatusCode::OK_200;
  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. struct {
  3971. const char *path;
  3972. const char *expected;
  3973. } cases[] = {
  3974. {"/a b?x=1", "/a%20b?x=1"},
  3975. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3976. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3977. };
  3978. for (const auto &c : cases) {
  3979. Client cli(HOST, port);
  3980. target.clear();
  3981. auto res = cli.Get(c.path);
  3982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3983. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3984. auto buffered_target = target;
  3985. target.clear();
  3986. auto handle = cli.open_stream("GET", c.path);
  3987. EXPECT_TRUE(handle.is_valid())
  3988. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3989. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3990. }
  3991. }
  3992. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3993. // The `set_path_encode(false)` contract — transmit the supplied target
  3994. // verbatim — must hold for the streaming API too.
  3995. Server svr;
  3996. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3997. std::string target;
  3998. svr.Get("/foo", [&](const Request &req, Response &res) {
  3999. target = req.target;
  4000. res.status = StatusCode::OK_200;
  4001. });
  4002. auto port = svr.bind_to_any_port(HOST);
  4003. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4004. auto se = detail::scope_exit([&] {
  4005. svr.stop();
  4006. thread.join();
  4007. ASSERT_FALSE(svr.is_running());
  4008. });
  4009. svr.wait_until_ready();
  4010. {
  4011. Client cli(HOST, port);
  4012. cli.set_path_encode(false);
  4013. auto handle = cli.open_stream("GET", expected_target);
  4014. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4015. EXPECT_EQ(expected_target, target);
  4016. }
  4017. }
  4018. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4019. // With path encoding enabled a CR/LF in the target is percent-encoded
  4020. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4021. // write_request_line still backstops `set_path_encode(false)`, which is
  4022. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4023. Server svr;
  4024. // Captured before routing: the decoded path contains a newline, which a
  4025. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4026. std::string target;
  4027. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4028. target = req.target;
  4029. res.status = StatusCode::OK_200;
  4030. return Server::HandlerResponse::Handled;
  4031. });
  4032. auto port = svr.bind_to_any_port(HOST);
  4033. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4034. auto se = detail::scope_exit([&] {
  4035. svr.stop();
  4036. thread.join();
  4037. ASSERT_FALSE(svr.is_running());
  4038. });
  4039. svr.wait_until_ready();
  4040. {
  4041. Client cli(HOST, port);
  4042. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4043. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4044. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4045. }
  4046. }
  4047. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4048. // Every control character is percent-encoded, not just CR/LF, so the target
  4049. // passes the request-target check in write_request_line.
  4050. Server svr;
  4051. std::string target;
  4052. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4053. target = req.target;
  4054. res.status = StatusCode::OK_200;
  4055. return Server::HandlerResponse::Handled;
  4056. });
  4057. auto port = svr.bind_to_any_port(HOST);
  4058. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4059. auto se = detail::scope_exit([&] {
  4060. svr.stop();
  4061. thread.join();
  4062. ASSERT_FALSE(svr.is_running());
  4063. });
  4064. svr.wait_until_ready();
  4065. {
  4066. Client cli(HOST, port);
  4067. auto res = cli.Get("/a\tb\x1b\x7f");
  4068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4069. EXPECT_EQ("/a%09b%1B%7F", target);
  4070. }
  4071. }
  4072. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4073. // Nothing may reach the wire: a raw CR/LF target would split the request
  4074. // line and inject headers.
  4075. Server svr;
  4076. // Pre-routing so that "not called" means nothing reached the server at all,
  4077. // rather than merely failing to match a handler pattern.
  4078. auto handler_called = false;
  4079. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4080. handler_called = true;
  4081. res.status = StatusCode::OK_200;
  4082. return Server::HandlerResponse::Handled;
  4083. });
  4084. auto port = svr.bind_to_any_port(HOST);
  4085. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4086. auto se = detail::scope_exit([&] {
  4087. svr.stop();
  4088. thread.join();
  4089. ASSERT_FALSE(svr.is_running());
  4090. });
  4091. svr.wait_until_ready();
  4092. {
  4093. Client cli(HOST, port);
  4094. cli.set_path_encode(false);
  4095. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4096. EXPECT_FALSE(handle.is_valid());
  4097. EXPECT_EQ(Error::Write, handle.error);
  4098. EXPECT_FALSE(handler_called);
  4099. }
  4100. }
  4101. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4102. // Which of the two branches runs is decided by whether the query component
  4103. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4104. // an empty query and must still fall back to building one from
  4105. // `req.params`, while a non-empty query must win over `req.params`.
  4106. Server svr;
  4107. std::string target;
  4108. svr.Get("/foo", [&](const Request &req, Response &res) {
  4109. target = req.target;
  4110. res.status = StatusCode::OK_200;
  4111. });
  4112. auto port = svr.bind_to_any_port(HOST);
  4113. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4114. auto se = detail::scope_exit([&] {
  4115. svr.stop();
  4116. thread.join();
  4117. ASSERT_FALSE(svr.is_running());
  4118. });
  4119. svr.wait_until_ready();
  4120. {
  4121. // Trailing `?` -> empty query component -> `req.params` is used.
  4122. Client cli(HOST, port);
  4123. Request req;
  4124. req.method = "GET";
  4125. req.path = "/foo?";
  4126. req.params.emplace("a", "1");
  4127. target.clear();
  4128. auto res = cli.send(req);
  4129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4130. EXPECT_EQ("/foo?a=1", target);
  4131. }
  4132. {
  4133. // Non-empty query in `req.path` -> `req.params` is not appended.
  4134. Client cli(HOST, port);
  4135. Request req;
  4136. req.method = "GET";
  4137. req.path = "/foo?b=2";
  4138. req.params.emplace("a", "1");
  4139. target.clear();
  4140. auto res = cli.send(req);
  4141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4142. EXPECT_EQ("/foo?b=2", target);
  4143. }
  4144. }
  4145. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4146. Server svr;
  4147. svr.Get("/", [](const Request &req, Response &) {
  4148. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4149. });
  4150. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4151. auto se = detail::scope_exit([&] {
  4152. svr.stop();
  4153. thread.join();
  4154. ASSERT_FALSE(svr.is_running());
  4155. });
  4156. svr.wait_until_ready();
  4157. {
  4158. Client cli(HOST, PORT);
  4159. cli.set_path_encode(false);
  4160. auto res = cli.Get("/?something=%0A");
  4161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4162. EXPECT_EQ(StatusCode::OK_200, res->status);
  4163. }
  4164. }
  4165. TEST(BindServerTest, BindDualStack) {
  4166. Server svr;
  4167. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4168. res.set_content("Hello World!", "text/plain");
  4169. });
  4170. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4171. auto se = detail::scope_exit([&] {
  4172. svr.stop();
  4173. thread.join();
  4174. ASSERT_FALSE(svr.is_running());
  4175. });
  4176. svr.wait_until_ready();
  4177. {
  4178. Client cli("127.0.0.1", PORT);
  4179. auto res = cli.Get("/1");
  4180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4181. EXPECT_EQ(StatusCode::OK_200, res->status);
  4182. EXPECT_EQ("Hello World!", res->body);
  4183. }
  4184. {
  4185. Client cli("::1", PORT);
  4186. auto res = cli.Get("/1");
  4187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4188. EXPECT_EQ(StatusCode::OK_200, res->status);
  4189. EXPECT_EQ("Hello World!", res->body);
  4190. }
  4191. }
  4192. TEST(BindServerTest, BindAndListenSeparately) {
  4193. Server svr;
  4194. int port = svr.bind_to_any_port("0.0.0.0");
  4195. ASSERT_TRUE(svr.is_valid());
  4196. ASSERT_TRUE(port > 0);
  4197. svr.stop();
  4198. }
  4199. // Reports whether anything is still listening on a loopback port. A plain
  4200. // connect() is used instead of a Client request because a socket left bound by
  4201. // mistake accepts the connection into its backlog and never answers, which
  4202. // would hang the test instead of failing it.
  4203. static bool is_loopback_port_accepting(int port) {
  4204. sockaddr_in addr{};
  4205. addr.sin_family = AF_INET;
  4206. addr.sin_port = htons(static_cast<uint16_t>(port));
  4207. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4208. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4209. EXPECT_NE(sock, INVALID_SOCKET);
  4210. if (sock == INVALID_SOCKET) { return false; }
  4211. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4212. static_cast<socklen_t>(sizeof(addr)));
  4213. detail::close_socket(sock);
  4214. return ret == 0;
  4215. }
  4216. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4217. Server svr;
  4218. auto port = svr.bind_to_any_port("127.0.0.1");
  4219. ASSERT_TRUE(port > 0);
  4220. svr.stop();
  4221. // bind_to_any_port() already called listen(2), so until stop() closed the
  4222. // descriptor the port kept accepting connections into the backlog. ASSERT
  4223. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4224. // below blocks forever in the accept loop.
  4225. ASSERT_FALSE(is_loopback_port_accepting(port));
  4226. // Nothing is left to accept on, so listen_after_bind() must report failure
  4227. // instead of returning success without ever serving.
  4228. EXPECT_FALSE(svr.listen_after_bind());
  4229. // The failed listen marks the server decommissioned, so a waiter returns
  4230. // instead of spinning forever.
  4231. svr.wait_until_ready();
  4232. }
  4233. #ifdef CPPHTTPLIB_SSL_ENABLED
  4234. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4236. CLIENT_CA_CERT_DIR);
  4237. int port = svr.bind_to_any_port("0.0.0.0");
  4238. ASSERT_TRUE(svr.is_valid());
  4239. ASSERT_TRUE(port > 0);
  4240. svr.stop();
  4241. }
  4242. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4243. // or a rejected CustomRoute() registration would not stop the server binding.
  4244. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4246. CLIENT_CA_CERT_DIR);
  4247. ASSERT_TRUE(svr.is_valid());
  4248. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4249. EXPECT_FALSE(svr.is_valid());
  4250. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4251. }
  4252. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4253. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4254. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4255. int port = svr.bind_to_any_port("0.0.0.0");
  4256. ASSERT_TRUE(svr.is_valid());
  4257. ASSERT_TRUE(port > 0);
  4258. svr.stop();
  4259. }
  4260. TEST(BindServerTest, UpdateCertsPem) {
  4261. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4262. int port = svr.bind_to_any_port("0.0.0.0");
  4263. ASSERT_TRUE(svr.is_valid());
  4264. ASSERT_TRUE(port > 0);
  4265. // Read PEM files
  4266. std::string cert_pem, key_pem, ca_pem;
  4267. read_file(SERVER_CERT_FILE, cert_pem);
  4268. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4269. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4270. // Update server certificates using PEM API
  4271. ASSERT_TRUE(
  4272. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4273. ASSERT_TRUE(svr.is_valid());
  4274. svr.stop();
  4275. }
  4276. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4277. // Start server with client CA (enables client auth)
  4278. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4279. ASSERT_TRUE(svr.is_valid());
  4280. bool handler_called = false;
  4281. svr.Get("/test", [&](const Request &req, Response &res) {
  4282. handler_called = true;
  4283. // Verify client certificate is present
  4284. auto cert = req.peer_cert();
  4285. EXPECT_TRUE(static_cast<bool>(cert));
  4286. res.set_content("ok", "text/plain");
  4287. });
  4288. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4289. auto se = detail::scope_exit([&] {
  4290. svr.stop();
  4291. t.join();
  4292. ASSERT_FALSE(svr.is_running());
  4293. });
  4294. svr.wait_until_ready();
  4295. // Read PEM files
  4296. std::string cert_pem, key_pem, ca_pem;
  4297. read_file(SERVER_CERT_FILE, cert_pem);
  4298. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4299. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4300. // Update server certificates and client CA using PEM API while server running
  4301. ASSERT_TRUE(
  4302. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4303. // Connect with client certificate
  4304. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4305. cli.enable_server_certificate_verification(false);
  4306. cli.set_connection_timeout(30);
  4307. auto res = cli.Get("/test");
  4308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4309. ASSERT_EQ(StatusCode::OK_200, res->status);
  4310. ASSERT_TRUE(handler_called);
  4311. EXPECT_EQ("ok", res->body);
  4312. }
  4313. // Puts a CA that did not sign the client's certificate in the old one's place.
  4314. static bool replace_client_ca(SSLServer &svr) {
  4315. std::string cert_pem, key_pem, ca_pem;
  4316. read_file(SERVER_CERT_FILE, cert_pem);
  4317. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4318. read_file(SERVER_CERT2_FILE, ca_pem);
  4319. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4320. ca_pem.c_str());
  4321. }
  4322. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4323. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4324. ASSERT_TRUE(svr.is_valid());
  4325. svr.Get("/test", [](const Request &, Response &res) {
  4326. res.set_content("ok", "text/plain");
  4327. });
  4328. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4329. auto se = detail::scope_exit([&] {
  4330. svr.stop();
  4331. t.join();
  4332. ASSERT_FALSE(svr.is_running());
  4333. });
  4334. svr.wait_until_ready();
  4335. auto get = [] {
  4336. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4337. cli.enable_server_certificate_verification(false);
  4338. return cli.Get("/test");
  4339. };
  4340. ASSERT_TRUE(get());
  4341. ASSERT_TRUE(replace_client_ca(svr));
  4342. EXPECT_FALSE(get());
  4343. }
  4344. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4345. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4346. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4347. ASSERT_TRUE(svr.is_valid());
  4348. tls::set_verify_callback(svr.tls_context(),
  4349. [](const tls::VerifyContext &) -> bool {
  4350. throw std::runtime_error("verify");
  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. auto get = [] {
  4363. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4364. cli.enable_server_certificate_verification(false);
  4365. return cli.Get("/test");
  4366. };
  4367. EXPECT_FALSE(get());
  4368. // The handshake is over, so an update does not wait for it.
  4369. std::string cert_pem, key_pem;
  4370. read_file(SERVER_CERT_FILE, cert_pem);
  4371. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4372. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4373. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4374. return v.preverify_ok;
  4375. });
  4376. auto res = get();
  4377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4378. EXPECT_EQ("ok", res->body);
  4379. }
  4380. #endif
  4381. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4382. // Sends each request over a new connection with a client certificate,
  4383. // resuming the session of the one before when there is one.
  4384. class ResumingClient {
  4385. public:
  4386. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4387. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4388. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4389. SSL_FILETYPE_PEM);
  4390. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4391. // callback, not through SSL_get1_session().
  4392. SSL_CTX_set_app_data(ctx_, this);
  4393. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4394. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4395. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4396. auto self = static_cast<ResumingClient *>(
  4397. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4398. SSL_SESSION_free(self->session_);
  4399. self->session_ = session;
  4400. return 1; // Keeps the reference
  4401. });
  4402. }
  4403. ~ResumingClient() {
  4404. SSL_SESSION_free(session_);
  4405. SSL_CTX_free(ctx_);
  4406. }
  4407. // Tells whether the request was answered.
  4408. bool get() {
  4409. auto error = Error::Success;
  4410. auto sock = detail::create_client_socket(
  4411. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4412. /*connection_timeout_sec=*/5, 0,
  4413. /*read_timeout_sec=*/5, 0,
  4414. /*write_timeout_sec=*/5, 0, std::string(), error);
  4415. if (sock == INVALID_SOCKET) { return false; }
  4416. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4417. auto ssl = SSL_new(ctx_);
  4418. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4419. SSL_set_fd(ssl, static_cast<int>(sock));
  4420. if (session_) { SSL_set_session(ssl, session_); }
  4421. if (SSL_connect(ssl) != 1) { return false; }
  4422. reused_ = SSL_session_reused(ssl) == 1;
  4423. // Reading the response also takes in a TLS 1.3 session ticket.
  4424. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4425. "Connection: close\r\n\r\n";
  4426. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4427. std::string res;
  4428. char buf[256];
  4429. int n;
  4430. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4431. res.append(buf, static_cast<size_t>(n));
  4432. }
  4433. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4434. SSL_shutdown(ssl);
  4435. return res.find("200 OK") != std::string::npos;
  4436. }
  4437. // Whether the last connection resumed a session
  4438. bool reused() const { return reused_; }
  4439. private:
  4440. SSL_CTX *ctx_;
  4441. SSL_SESSION *session_ = nullptr;
  4442. bool reused_ = false;
  4443. };
  4444. // A client that resumes its session gets through, but not once the client CA
  4445. // has changed, as a resumed session does not show the certificate again.
  4446. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4447. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4448. ASSERT_TRUE(svr.is_valid());
  4449. svr.Get("/test", [](const Request &, Response &res) {
  4450. res.set_content("ok", "text/plain");
  4451. });
  4452. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4453. auto se = detail::scope_exit([&] {
  4454. svr.stop();
  4455. t.join();
  4456. ASSERT_FALSE(svr.is_running());
  4457. });
  4458. svr.wait_until_ready();
  4459. ResumingClient cli;
  4460. ASSERT_TRUE(cli.get());
  4461. ASSERT_TRUE(cli.get());
  4462. EXPECT_TRUE(cli.reused());
  4463. ASSERT_TRUE(replace_client_ca(svr));
  4464. EXPECT_FALSE(cli.get());
  4465. }
  4466. // A resumed session does not show the certificate again, so the server does
  4467. // not resume one with a verify callback to run on it.
  4468. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4469. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4470. ASSERT_TRUE(svr.is_valid());
  4471. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4472. return v.preverify_ok;
  4473. });
  4474. svr.Get("/test", [](const Request &, Response &res) {
  4475. res.set_content("ok", "text/plain");
  4476. });
  4477. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4478. auto se = detail::scope_exit([&] {
  4479. svr.stop();
  4480. t.join();
  4481. ASSERT_FALSE(svr.is_running());
  4482. });
  4483. svr.wait_until_ready();
  4484. ResumingClient cli;
  4485. ASSERT_TRUE(cli.get());
  4486. ASSERT_TRUE(cli.get());
  4487. EXPECT_FALSE(cli.reused());
  4488. }
  4489. #endif
  4490. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4491. // wolfSSL shares its session cache between contexts, so a resumed session
  4492. // could carry a client certificate checked against another server's CA, or
  4493. // against a client CA since replaced.
  4494. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4496. ASSERT_TRUE(svr.is_valid());
  4497. // Trusts a CA that did not sign the client's certificate.
  4498. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4499. ASSERT_TRUE(other.is_valid());
  4500. for (auto s : {&svr, &other}) {
  4501. s->Get("/test", [](const Request &, Response &res) {
  4502. res.set_content("ok", "text/plain");
  4503. });
  4504. }
  4505. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4506. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4507. auto se = detail::scope_exit([&] {
  4508. other.stop();
  4509. svr.stop();
  4510. t2.join();
  4511. t.join();
  4512. });
  4513. svr.wait_until_ready();
  4514. other.wait_until_ready();
  4515. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4516. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4517. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4518. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4519. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4520. ASSERT_EQ(WOLFSSL_SUCCESS,
  4521. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4522. WOLFSSL_FILETYPE_PEM));
  4523. WOLFSSL_SESSION *session = nullptr;
  4524. auto session_se = detail::scope_exit([&] {
  4525. if (session) { wolfSSL_SESSION_free(session); }
  4526. });
  4527. // A request over a new connection, resuming `session` when there is one and
  4528. // keeping the connection's own in its place. Tells whether it was answered.
  4529. auto get = [&](int port) {
  4530. auto error = Error::Success;
  4531. auto sock = detail::create_client_socket(
  4532. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4533. /*connection_timeout_sec=*/5, 0,
  4534. /*read_timeout_sec=*/5, 0,
  4535. /*write_timeout_sec=*/5, 0, std::string(), error);
  4536. if (sock == INVALID_SOCKET) { return false; }
  4537. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4538. auto ssl = wolfSSL_new(ctx);
  4539. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4540. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4541. if (session) { wolfSSL_set_session(ssl, session); }
  4542. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4543. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4544. "Connection: close\r\n\r\n";
  4545. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4546. std::string res;
  4547. char buf[256];
  4548. int n;
  4549. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4550. res.append(buf, static_cast<size_t>(n));
  4551. }
  4552. wolfSSL_shutdown(ssl);
  4553. if (session) { wolfSSL_SESSION_free(session); }
  4554. session = wolfSSL_get1_session(ssl);
  4555. return res.find("200 OK") != std::string::npos;
  4556. };
  4557. ASSERT_TRUE(get(PORT));
  4558. EXPECT_FALSE(get(PORT + 1));
  4559. ASSERT_TRUE(get(PORT));
  4560. ASSERT_TRUE(replace_client_ca(svr));
  4561. EXPECT_FALSE(get(PORT));
  4562. }
  4563. #endif
  4564. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4566. ASSERT_TRUE(svr.is_valid());
  4567. svr.Get("/test", [](const Request &, Response &res) {
  4568. res.set_content("ok", "text/plain");
  4569. });
  4570. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4571. auto se = detail::scope_exit([&] {
  4572. svr.stop();
  4573. t.join();
  4574. ASSERT_FALSE(svr.is_running());
  4575. });
  4576. svr.wait_until_ready();
  4577. // A connection that sends no ClientHello keeps its handshake in progress,
  4578. // once the server has had a moment to start it.
  4579. auto error = Error::Success;
  4580. auto sock = detail::create_client_socket(
  4581. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4582. /*connection_timeout_sec=*/5, 0,
  4583. /*read_timeout_sec=*/5, 0,
  4584. /*write_timeout_sec=*/5, 0, std::string(), error);
  4585. ASSERT_NE(INVALID_SOCKET, sock);
  4586. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4587. std::string cert_pem, key_pem;
  4588. read_file(SERVER_CERT_FILE, cert_pem);
  4589. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4590. auto update = std::async(std::launch::async, [&]() {
  4591. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4592. });
  4593. EXPECT_EQ(std::future_status::timeout,
  4594. update.wait_for(std::chrono::milliseconds(200)));
  4595. detail::close_socket(sock);
  4596. EXPECT_TRUE(update.get());
  4597. SSLClient cli(HOST, PORT);
  4598. cli.enable_server_certificate_verification(false);
  4599. auto res = cli.Get("/test");
  4600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4601. EXPECT_EQ(StatusCode::OK_200, res->status);
  4602. }
  4603. #endif
  4604. TEST(ErrorHandlerTest, ContentLength) {
  4605. Server svr;
  4606. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4607. res.status = StatusCode::OK_200;
  4608. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4609. "text/html"); // <= Content-Length still 13
  4610. });
  4611. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4612. res.set_content("Hello World!\n", "text/plain");
  4613. res.status = 524;
  4614. });
  4615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4616. auto se = detail::scope_exit([&] {
  4617. svr.stop();
  4618. thread.join();
  4619. ASSERT_FALSE(svr.is_running());
  4620. });
  4621. svr.wait_until_ready();
  4622. {
  4623. Client cli(HOST, PORT);
  4624. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4626. EXPECT_EQ(StatusCode::OK_200, res->status);
  4627. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4628. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4629. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4630. }
  4631. }
  4632. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4633. TEST(ExceptionTest, WithoutExceptionHandler) {
  4634. Server svr;
  4635. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4636. throw std::runtime_error("exception...");
  4637. });
  4638. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4639. throw std::runtime_error("exception\r\n...");
  4640. });
  4641. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4642. auto se = detail::scope_exit([&] {
  4643. svr.stop();
  4644. listen_thread.join();
  4645. ASSERT_FALSE(svr.is_running());
  4646. });
  4647. svr.wait_until_ready();
  4648. Client cli("localhost", PORT);
  4649. {
  4650. auto res = cli.Get("/exception");
  4651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4652. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4653. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4654. }
  4655. {
  4656. auto res = cli.Get("/unknown");
  4657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4658. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4659. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4660. }
  4661. }
  4662. TEST(ExceptionTest, WithExceptionHandler) {
  4663. Server svr;
  4664. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4665. std::exception_ptr ep) {
  4666. EXPECT_FALSE(ep == nullptr);
  4667. try {
  4668. std::rethrow_exception(ep);
  4669. } catch (std::exception &e) {
  4670. EXPECT_EQ("abc", std::string(e.what()));
  4671. } catch (...) {}
  4672. res.status = StatusCode::InternalServerError_500;
  4673. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4674. "text/html"); // <= Content-Length still 13 at this point
  4675. });
  4676. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4677. res.set_content("Hello World!\n", "text/plain");
  4678. throw std::runtime_error("abc");
  4679. });
  4680. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4681. auto se = detail::scope_exit([&] {
  4682. svr.stop();
  4683. thread.join();
  4684. ASSERT_FALSE(svr.is_running());
  4685. });
  4686. svr.wait_until_ready();
  4687. for (size_t i = 0; i < 10; i++) {
  4688. Client cli(HOST, PORT);
  4689. for (size_t j = 0; j < 100; j++) {
  4690. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4692. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4693. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4694. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4695. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4696. }
  4697. cli.set_keep_alive(true);
  4698. for (size_t j = 0; j < 100; j++) {
  4699. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4701. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4702. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4703. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4704. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4705. }
  4706. }
  4707. }
  4708. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4709. Server svr;
  4710. svr.set_exception_handler(
  4711. [](const Request &, Response &res, std::exception_ptr) {
  4712. res.set_content("oops", "text/plain");
  4713. });
  4714. svr.Get("/throw", [](const Request &, Response &) {
  4715. throw std::runtime_error("throw");
  4716. });
  4717. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4718. res.status = StatusCode::Created_201;
  4719. throw std::runtime_error("created-then-throw");
  4720. });
  4721. auto port = svr.bind_to_any_port(HOST);
  4722. ASSERT_GT(port, 0);
  4723. thread t = thread([&] { svr.listen_after_bind(); });
  4724. auto se = detail::scope_exit([&] {
  4725. svr.stop();
  4726. t.join();
  4727. ASSERT_FALSE(svr.is_running());
  4728. });
  4729. svr.wait_until_ready();
  4730. Client cli(HOST, port);
  4731. for (auto path : {"/throw", "/created-then-throw"}) {
  4732. auto res = cli.Get(path);
  4733. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4734. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4735. }
  4736. }
  4737. TEST(ExceptionTest, AndErrorHandler) {
  4738. Server svr;
  4739. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4740. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4741. });
  4742. svr.set_exception_handler(
  4743. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4744. EXPECT_FALSE(ep == nullptr);
  4745. try {
  4746. std::rethrow_exception(ep);
  4747. } catch (std::exception &e) {
  4748. res.set_content(e.what(), "text/html");
  4749. } catch (...) {}
  4750. res.status = StatusCode::InternalServerError_500;
  4751. });
  4752. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4753. throw std::runtime_error("EXCEPTION");
  4754. });
  4755. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4756. res.set_content("ERROR", "text/html");
  4757. res.status = StatusCode::InternalServerError_500;
  4758. });
  4759. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4760. auto se = detail::scope_exit([&] {
  4761. svr.stop();
  4762. thread.join();
  4763. ASSERT_FALSE(svr.is_running());
  4764. });
  4765. svr.wait_until_ready();
  4766. Client cli(HOST, PORT);
  4767. {
  4768. auto res = cli.Get("/exception");
  4769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4770. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4771. EXPECT_EQ("EXCEPTION", res->body);
  4772. }
  4773. {
  4774. auto res = cli.Get("/error");
  4775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4776. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4777. EXPECT_EQ("ERROR", res->body);
  4778. }
  4779. {
  4780. auto res = cli.Get("/invalid");
  4781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4782. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4783. EXPECT_EQ("NOT_FOUND", res->body);
  4784. }
  4785. }
  4786. #endif
  4787. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4788. // An exception from a user callback outside process_request()'s try/catch
  4789. // used to unwind into the task queue - which does not catch - and terminate
  4790. // the process. Each test below runs the server on a single worker thread: a
  4791. // guard that catches the exception but still loses the thread would otherwise
  4792. // be hidden by a spare worker serving the follow-up request. Note that a
  4793. // regression here aborts the whole test binary rather than failing one test.
  4794. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4795. Server svr;
  4796. svr.new_task_queue = [] { return new ThreadPool(1); };
  4797. std::atomic<int> reported{0};
  4798. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4799. if (err == Error::UserCallbackException) { reported++; }
  4800. });
  4801. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4802. res.set_content_provider(
  4803. 1024, "text/plain",
  4804. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4805. sink.write("hello", 5);
  4806. throw std::runtime_error("from the content provider");
  4807. });
  4808. });
  4809. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4810. res.set_content("ok", "text/plain");
  4811. });
  4812. auto port = svr.bind_to_any_port(HOST);
  4813. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4814. auto se = detail::scope_exit([&] {
  4815. svr.stop();
  4816. listen_thread.join();
  4817. ASSERT_FALSE(svr.is_running());
  4818. });
  4819. svr.wait_until_ready();
  4820. {
  4821. Client cli(HOST, port);
  4822. cli.set_read_timeout(5, 0);
  4823. EXPECT_FALSE(cli.Get("/throw"));
  4824. }
  4825. EXPECT_TRUE(svr.is_running());
  4826. EXPECT_EQ(1, reported.load());
  4827. // A request on a fresh connection is still served.
  4828. {
  4829. Client cli(HOST, port);
  4830. auto res = cli.Get("/ok");
  4831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4832. EXPECT_EQ(StatusCode::OK_200, res->status);
  4833. EXPECT_EQ("ok", res->body);
  4834. }
  4835. }
  4836. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4837. Server svr;
  4838. svr.new_task_queue = [] { return new ThreadPool(1); };
  4839. std::atomic<bool> should_throw{true};
  4840. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4841. res.set_content("hi", "text/plain");
  4842. });
  4843. svr.set_post_routing_handler(
  4844. [&](const Request & /*req*/, Response & /*res*/) {
  4845. if (should_throw) {
  4846. throw std::runtime_error("from the post-routing handler");
  4847. }
  4848. });
  4849. auto port = svr.bind_to_any_port(HOST);
  4850. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4851. auto se = detail::scope_exit([&] {
  4852. svr.stop();
  4853. listen_thread.join();
  4854. ASSERT_FALSE(svr.is_running());
  4855. });
  4856. svr.wait_until_ready();
  4857. {
  4858. Client cli(HOST, port);
  4859. cli.set_read_timeout(5, 0);
  4860. EXPECT_FALSE(cli.Get("/hi"));
  4861. }
  4862. EXPECT_TRUE(svr.is_running());
  4863. should_throw = false;
  4864. {
  4865. Client cli(HOST, port);
  4866. auto res = cli.Get("/hi");
  4867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4868. EXPECT_EQ(StatusCode::OK_200, res->status);
  4869. EXPECT_EQ("hi", res->body);
  4870. }
  4871. }
  4872. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4873. // The guard reports the caught exception through the error logger, which is
  4874. // a user callback too. A logger that throws has to be contained as well, or
  4875. // the process would terminate from inside the catch.
  4876. Server svr;
  4877. svr.new_task_queue = [] { return new ThreadPool(1); };
  4878. std::atomic<int> reported{0};
  4879. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4880. if (err == Error::UserCallbackException) {
  4881. reported++;
  4882. throw std::runtime_error("from the error logger");
  4883. }
  4884. });
  4885. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4886. res.set_content_provider(
  4887. 1024, "text/plain",
  4888. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4889. sink.write("hello", 5);
  4890. throw std::runtime_error("from the content provider");
  4891. });
  4892. });
  4893. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4894. res.set_content("ok", "text/plain");
  4895. });
  4896. auto port = svr.bind_to_any_port(HOST);
  4897. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4898. auto se = detail::scope_exit([&] {
  4899. svr.stop();
  4900. listen_thread.join();
  4901. ASSERT_FALSE(svr.is_running());
  4902. });
  4903. svr.wait_until_ready();
  4904. {
  4905. Client cli(HOST, port);
  4906. cli.set_read_timeout(5, 0);
  4907. EXPECT_FALSE(cli.Get("/throw"));
  4908. }
  4909. EXPECT_TRUE(svr.is_running());
  4910. EXPECT_EQ(1, reported.load());
  4911. {
  4912. Client cli(HOST, port);
  4913. auto res = cli.Get("/ok");
  4914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4915. EXPECT_EQ(StatusCode::OK_200, res->status);
  4916. EXPECT_EQ("ok", res->body);
  4917. }
  4918. }
  4919. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4920. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4921. // so the exception unwinds through the ws::WebSocket object on its way to
  4922. // the guard. None of the HTTP cases above cross that.
  4923. Server svr;
  4924. svr.new_task_queue = [] { return new ThreadPool(1); };
  4925. std::atomic<int> reported{0};
  4926. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4927. if (err == Error::UserCallbackException) { reported++; }
  4928. });
  4929. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4930. throw std::runtime_error("from the WebSocket handler");
  4931. });
  4932. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4933. res.set_content("ok", "text/plain");
  4934. });
  4935. auto port = svr.bind_to_any_port(HOST);
  4936. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4937. auto se = detail::scope_exit([&] {
  4938. svr.stop();
  4939. listen_thread.join();
  4940. ASSERT_FALSE(svr.is_running());
  4941. });
  4942. svr.wait_until_ready();
  4943. {
  4944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4945. "/ws");
  4946. auto res = client.connect();
  4947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4948. // The server dropped the connection instead of dying.
  4949. std::string msg;
  4950. EXPECT_FALSE(client.read(msg));
  4951. client.close();
  4952. }
  4953. EXPECT_TRUE(svr.is_running());
  4954. EXPECT_EQ(1, reported.load());
  4955. {
  4956. Client cli(HOST, port);
  4957. auto res = cli.Get("/ok");
  4958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4959. EXPECT_EQ(StatusCode::OK_200, res->status);
  4960. EXPECT_EQ("ok", res->body);
  4961. }
  4962. }
  4963. #ifdef CPPHTTPLIB_SSL_ENABLED
  4964. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4965. // SSLServer::process_and_close_socket() is a separate overload with its own
  4966. // guard, so it is exercised on its own.
  4967. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4968. ASSERT_TRUE(svr.is_valid());
  4969. svr.new_task_queue = [] { return new ThreadPool(1); };
  4970. std::atomic<int> reported{0};
  4971. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4972. if (err == Error::UserCallbackException) { reported++; }
  4973. });
  4974. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4975. res.set_content_provider(
  4976. 1024, "text/plain",
  4977. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4978. sink.write("hello", 5);
  4979. throw std::runtime_error("from the content provider");
  4980. });
  4981. });
  4982. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4983. res.set_content("ok", "text/plain");
  4984. });
  4985. auto port = svr.bind_to_any_port(HOST);
  4986. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4987. auto se = detail::scope_exit([&] {
  4988. svr.stop();
  4989. listen_thread.join();
  4990. ASSERT_FALSE(svr.is_running());
  4991. });
  4992. svr.wait_until_ready();
  4993. {
  4994. SSLClient cli(HOST, port);
  4995. cli.enable_server_certificate_verification(false);
  4996. cli.set_read_timeout(5, 0);
  4997. EXPECT_FALSE(cli.Get("/throw"));
  4998. }
  4999. EXPECT_TRUE(svr.is_running());
  5000. EXPECT_EQ(1, reported.load());
  5001. {
  5002. SSLClient cli(HOST, port);
  5003. cli.enable_server_certificate_verification(false);
  5004. auto res = cli.Get("/ok");
  5005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5006. EXPECT_EQ(StatusCode::OK_200, res->status);
  5007. EXPECT_EQ("ok", res->body);
  5008. }
  5009. }
  5010. #endif
  5011. #endif
  5012. TEST(NoContentTest, ContentLength) {
  5013. Server svr;
  5014. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5015. res.status = StatusCode::NoContent_204;
  5016. });
  5017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5018. auto se = detail::scope_exit([&] {
  5019. svr.stop();
  5020. thread.join();
  5021. ASSERT_FALSE(svr.is_running());
  5022. });
  5023. svr.wait_until_ready();
  5024. {
  5025. Client cli(HOST, PORT);
  5026. auto res = cli.Get("/hi");
  5027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5028. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5029. // RFC 9110 8.6: none in a 204 response
  5030. EXPECT_FALSE(res->has_header("Content-Length"));
  5031. }
  5032. }
  5033. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5034. Server svr;
  5035. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5036. res.set_header("Content-Length", "5");
  5037. res.set_content("hello world", "text/plain");
  5038. });
  5039. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5040. // A body that reads as the last chunk, were it taken as chunked
  5041. res.set_header("Transfer-Encoding", "chunked");
  5042. res.set_content("0\r\n\r\n", "text/plain");
  5043. });
  5044. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5045. res.set_header("Content-Length", "2");
  5046. res.set_content_provider(5, "text/plain",
  5047. [](size_t offset, size_t length, DataSink &sink) {
  5048. sink.write(&"hello"[offset], length);
  5049. return true;
  5050. });
  5051. });
  5052. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5053. res.set_header("Content-Length", "1234");
  5054. });
  5055. thread t = thread([&] { svr.listen(HOST, PORT); });
  5056. auto se = detail::scope_exit([&] {
  5057. svr.stop();
  5058. t.join();
  5059. ASSERT_FALSE(svr.is_running());
  5060. });
  5061. svr.wait_until_ready();
  5062. Client cli(HOST, PORT);
  5063. cli.set_read_timeout(1, 0);
  5064. auto expect_body = [&](const Result &res, const std::string &body) {
  5065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5066. EXPECT_EQ(body, res->body);
  5067. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5068. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5069. };
  5070. Headers identity{{"Accept-Encoding", ""}};
  5071. expect_body(cli.Get("/body", identity), "hello world");
  5072. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5073. expect_body(cli.Get("/body",
  5074. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5075. "he");
  5076. expect_body(cli.Get("/provider", identity), "hello");
  5077. expect_body(cli.Get("/empty", identity), "");
  5078. // A HEAD response may give the length of the body a GET would get.
  5079. auto res = cli.Head("/empty");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5082. }
  5083. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5084. Server svr;
  5085. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5086. res.set_content("short", "text/plain");
  5087. });
  5088. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5089. res.body += " with a footer";
  5090. res.set_header("Transfer-Encoding", "chunked");
  5091. });
  5092. thread t = thread([&] { svr.listen(HOST, PORT); });
  5093. auto se = detail::scope_exit([&] {
  5094. svr.stop();
  5095. t.join();
  5096. ASSERT_FALSE(svr.is_running());
  5097. });
  5098. svr.wait_until_ready();
  5099. Client cli(HOST, PORT);
  5100. cli.set_read_timeout(1, 0);
  5101. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5103. EXPECT_EQ("short with a footer", res->body);
  5104. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5105. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5106. }
  5107. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5108. Server svr;
  5109. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5110. res.set_header("Content-Length", "3");
  5111. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5112. sink.write("abc", 3);
  5113. sink.done();
  5114. return true;
  5115. });
  5116. });
  5117. thread t = thread([&] { svr.listen(HOST, PORT); });
  5118. auto se = detail::scope_exit([&] {
  5119. svr.stop();
  5120. t.join();
  5121. ASSERT_FALSE(svr.is_running());
  5122. });
  5123. svr.wait_until_ready();
  5124. Client cli(HOST, PORT);
  5125. cli.set_keep_alive(true);
  5126. auto res = cli.Get("/");
  5127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5128. EXPECT_EQ("abc", res->body);
  5129. EXPECT_FALSE(res->has_header("Content-Length"));
  5130. EXPECT_EQ("close", res->get_header_value("Connection"));
  5131. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5132. // No body to delimit
  5133. auto head = cli.Head("/");
  5134. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5135. EXPECT_FALSE(head->has_header("Connection"));
  5136. }
  5137. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5138. #ifdef CPPHTTPLIB_SSL_ENABLED
  5139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5140. ASSERT_TRUE(svr.is_valid());
  5141. #else
  5142. Server svr;
  5143. #endif
  5144. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5145. if (req.path == "/routing_handler") {
  5146. res.set_header("PRE_ROUTING", "on");
  5147. res.set_content("Routing Handler", "text/plain");
  5148. return httplib::Server::HandlerResponse::Handled;
  5149. }
  5150. return httplib::Server::HandlerResponse::Unhandled;
  5151. });
  5152. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5153. res.set_content("Error", "text/html");
  5154. });
  5155. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5156. if (req.path == "/routing_handler") {
  5157. res.set_header("POST_ROUTING", "on");
  5158. }
  5159. });
  5160. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5161. res.set_content("Hello World!\n", "text/plain");
  5162. });
  5163. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5164. auto se = detail::scope_exit([&] {
  5165. svr.stop();
  5166. thread.join();
  5167. ASSERT_FALSE(svr.is_running());
  5168. });
  5169. svr.wait_until_ready();
  5170. {
  5171. #ifdef CPPHTTPLIB_SSL_ENABLED
  5172. SSLClient cli(HOST, PORT);
  5173. cli.enable_server_certificate_verification(false);
  5174. #else
  5175. Client cli(HOST, PORT);
  5176. #endif
  5177. auto res = cli.Get("/routing_handler");
  5178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("Routing Handler", res->body);
  5181. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5182. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5183. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5184. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5185. }
  5186. {
  5187. #ifdef CPPHTTPLIB_SSL_ENABLED
  5188. SSLClient cli(HOST, PORT);
  5189. cli.enable_server_certificate_verification(false);
  5190. #else
  5191. Client cli(HOST, PORT);
  5192. #endif
  5193. auto res = cli.Get("/hi");
  5194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5195. EXPECT_EQ(StatusCode::OK_200, res->status);
  5196. EXPECT_EQ("Hello World!\n", res->body);
  5197. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5198. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5199. }
  5200. {
  5201. #ifdef CPPHTTPLIB_SSL_ENABLED
  5202. SSLClient cli(HOST, PORT);
  5203. cli.enable_server_certificate_verification(false);
  5204. #else
  5205. Client cli(HOST, PORT);
  5206. #endif
  5207. auto res = cli.Get("/aaa");
  5208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5209. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5210. EXPECT_EQ("Error", res->body);
  5211. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5212. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5213. }
  5214. }
  5215. TEST(RequestHandlerTest, PreRequestHandler) {
  5216. auto route_path = "/user/:user";
  5217. Server svr;
  5218. svr.Get("/hi", [](const Request &, Response &res) {
  5219. res.set_content("hi", "text/plain");
  5220. });
  5221. svr.Get(route_path, [](const Request &req, Response &res) {
  5222. res.set_content(req.path_params.at("user"), "text/plain");
  5223. });
  5224. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5225. if (req.matched_route == route_path) {
  5226. auto user = req.path_params.at("user");
  5227. if (user != "john") {
  5228. res.status = StatusCode::Forbidden_403;
  5229. res.set_content("error", "text/html");
  5230. return Server::HandlerResponse::Handled;
  5231. }
  5232. }
  5233. return Server::HandlerResponse::Unhandled;
  5234. });
  5235. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5236. auto se = detail::scope_exit([&] {
  5237. svr.stop();
  5238. thread.join();
  5239. ASSERT_FALSE(svr.is_running());
  5240. });
  5241. svr.wait_until_ready();
  5242. Client cli(HOST, PORT);
  5243. {
  5244. auto res = cli.Get("/hi");
  5245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5246. EXPECT_EQ(StatusCode::OK_200, res->status);
  5247. EXPECT_EQ("hi", res->body);
  5248. }
  5249. {
  5250. auto res = cli.Get("/user/john");
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. EXPECT_EQ("john", res->body);
  5254. }
  5255. {
  5256. auto res = cli.Get("/user/invalid-user");
  5257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5258. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5259. EXPECT_EQ("error", res->body);
  5260. }
  5261. }
  5262. // The pre-request handler must run before the request body is read, so a
  5263. // rejected request never forces the server to buffer a (potentially large)
  5264. // body. Here the posted body is larger than the payload limit: if the body
  5265. // were read first the server would answer 413, but because the pre-request
  5266. // handler runs first it answers 403 and the body is never read.
  5267. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5268. Server svr;
  5269. svr.set_payload_max_length(8);
  5270. auto handler_ran = false;
  5271. svr.Post("/reject", [&](const Request &req, Response &res) {
  5272. handler_ran = true;
  5273. res.set_content(req.body, "text/plain");
  5274. });
  5275. svr.Post("/accept", [](const Request &req, Response &res) {
  5276. res.set_content(req.body, "text/plain");
  5277. });
  5278. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5279. if (req.matched_route == "/reject") {
  5280. res.status = StatusCode::Forbidden_403;
  5281. res.set_content("denied", "text/plain");
  5282. return Server::HandlerResponse::Handled;
  5283. }
  5284. return Server::HandlerResponse::Unhandled;
  5285. });
  5286. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5287. auto se = detail::scope_exit([&] {
  5288. svr.stop();
  5289. thread.join();
  5290. ASSERT_FALSE(svr.is_running());
  5291. });
  5292. svr.wait_until_ready();
  5293. Client cli(HOST, PORT);
  5294. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5295. // rejects with 403 before the body is read, so 413 is never reached.
  5296. {
  5297. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5300. EXPECT_EQ("denied", res->body);
  5301. EXPECT_FALSE(handler_ran);
  5302. }
  5303. // An approved route still reads the body and enforces the payload limit.
  5304. {
  5305. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5307. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5308. }
  5309. }
  5310. TEST(UserDataTest, BasicOperations) {
  5311. httplib::UserData ud;
  5312. // Initially empty
  5313. EXPECT_FALSE(ud.has("key"));
  5314. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5315. // set and get
  5316. ud.set("key", 42);
  5317. EXPECT_TRUE(ud.has("key"));
  5318. auto *p = ud.get<int>("key");
  5319. ASSERT_NE(nullptr, p);
  5320. EXPECT_EQ(42, *p);
  5321. // Type mismatch → nullptr
  5322. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5323. // Overwrite with different type
  5324. ud.set("key", std::string("hello"));
  5325. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5326. auto *s = ud.get<std::string>("key");
  5327. ASSERT_NE(nullptr, s);
  5328. EXPECT_EQ("hello", *s);
  5329. // erase
  5330. ud.erase("key");
  5331. EXPECT_FALSE(ud.has("key"));
  5332. // clear
  5333. ud.set("a", 1);
  5334. ud.set("b", 2);
  5335. ud.clear();
  5336. EXPECT_FALSE(ud.has("a"));
  5337. EXPECT_FALSE(ud.has("b"));
  5338. }
  5339. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5340. struct AuthCtx {
  5341. std::string user_id;
  5342. };
  5343. Server svr;
  5344. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5345. res.user_data.set("auth", AuthCtx{"alice"});
  5346. return Server::HandlerResponse::Unhandled;
  5347. });
  5348. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5349. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5350. ASSERT_NE(nullptr, ctx);
  5351. res.set_content("Hello " + ctx->user_id, "text/plain");
  5352. });
  5353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5354. auto se = detail::scope_exit([&] {
  5355. svr.stop();
  5356. thread.join();
  5357. ASSERT_FALSE(svr.is_running());
  5358. });
  5359. svr.wait_until_ready();
  5360. Client cli(HOST, PORT);
  5361. auto res = cli.Get("/me");
  5362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5363. EXPECT_EQ(StatusCode::OK_200, res->status);
  5364. EXPECT_EQ("Hello alice", res->body);
  5365. }
  5366. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5367. struct RoleCtx {
  5368. std::string role;
  5369. };
  5370. Server svr;
  5371. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5372. res.user_data.set("role", RoleCtx{"admin"});
  5373. return Server::HandlerResponse::Unhandled;
  5374. });
  5375. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5376. auto *ctx = res.user_data.get<RoleCtx>("role");
  5377. ASSERT_NE(nullptr, ctx);
  5378. res.set_content(ctx->role, "text/plain");
  5379. });
  5380. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5381. auto se = detail::scope_exit([&] {
  5382. svr.stop();
  5383. thread.join();
  5384. ASSERT_FALSE(svr.is_running());
  5385. });
  5386. svr.wait_until_ready();
  5387. Client cli(HOST, PORT);
  5388. auto res = cli.Get("/role");
  5389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5390. EXPECT_EQ(StatusCode::OK_200, res->status);
  5391. EXPECT_EQ("admin", res->body);
  5392. }
  5393. TEST(InvalidFormatTest, StatusCode) {
  5394. Server svr;
  5395. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5396. res.set_content("Hello World!\n", "text/plain");
  5397. res.status = 9999; // Status should be a three-digit code...
  5398. });
  5399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5400. auto se = detail::scope_exit([&] {
  5401. svr.stop();
  5402. thread.join();
  5403. ASSERT_FALSE(svr.is_running());
  5404. });
  5405. svr.wait_until_ready();
  5406. {
  5407. Client cli(HOST, PORT);
  5408. auto res = cli.Get("/hi");
  5409. ASSERT_FALSE(res);
  5410. }
  5411. }
  5412. TEST(URLFragmentTest, WithFragment) {
  5413. Server svr;
  5414. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5415. EXPECT_TRUE(req.target == "/hi");
  5416. });
  5417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5418. auto se = detail::scope_exit([&] {
  5419. svr.stop();
  5420. thread.join();
  5421. ASSERT_FALSE(svr.is_running());
  5422. });
  5423. svr.wait_until_ready();
  5424. {
  5425. Client cli(HOST, PORT);
  5426. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5427. EXPECT_TRUE(res);
  5428. EXPECT_EQ(StatusCode::OK_200, res->status);
  5429. res = cli.Get("/hi%23key1=val1=key2=val2");
  5430. EXPECT_TRUE(res);
  5431. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5432. }
  5433. }
  5434. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5435. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5436. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5437. Server svr;
  5438. std::vector<std::string> targets;
  5439. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5440. targets.push_back(req.target);
  5441. });
  5442. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5443. auto se = detail::scope_exit([&] {
  5444. svr.stop();
  5445. thread.join();
  5446. ASSERT_FALSE(svr.is_running());
  5447. });
  5448. svr.wait_until_ready();
  5449. Client cli(HOST, PORT);
  5450. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5451. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5452. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5453. // A '?' after the '#' belongs to the fragment, not to the query.
  5454. Request req;
  5455. req.method = "GET";
  5456. req.path = "/hi#f?x=1";
  5457. req.params.emplace("a", "1");
  5458. Response res;
  5459. auto error = Error::Success;
  5460. EXPECT_TRUE(cli.send(req, res, error));
  5461. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5462. "/hi?a=1"}),
  5463. targets);
  5464. }
  5465. TEST(HeaderWriter, SetHeaderWriter) {
  5466. Server svr;
  5467. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5468. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5469. return detail::write_headers(strm, hdrs);
  5470. });
  5471. svr.Get("/hi", [](const Request &req, Response &res) {
  5472. auto it = req.headers.find("CustomClientHeader");
  5473. EXPECT_TRUE(it != req.headers.end());
  5474. EXPECT_EQ(it->second, "CustomClientValue");
  5475. res.set_content("Hello World!\n", "text/plain");
  5476. });
  5477. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5478. auto se = detail::scope_exit([&] {
  5479. svr.stop();
  5480. thread.join();
  5481. ASSERT_FALSE(svr.is_running());
  5482. });
  5483. svr.wait_until_ready();
  5484. {
  5485. Client cli(HOST, PORT);
  5486. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5487. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5488. return detail::write_headers(strm, hdrs);
  5489. });
  5490. auto res = cli.Get("/hi");
  5491. EXPECT_TRUE(res);
  5492. EXPECT_EQ(StatusCode::OK_200, res->status);
  5493. auto it = res->headers.find("CustomServerHeader");
  5494. EXPECT_TRUE(it != res->headers.end());
  5495. EXPECT_EQ(it->second, "CustomServerValue");
  5496. }
  5497. }
  5498. class ServerTest : public ::testing::Test {
  5499. protected:
  5500. ServerTest()
  5501. : cli_(HOST, PORT)
  5502. #ifdef CPPHTTPLIB_SSL_ENABLED
  5503. ,
  5504. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5505. #endif
  5506. {
  5507. #ifdef CPPHTTPLIB_SSL_ENABLED
  5508. cli_.enable_server_certificate_verification(false);
  5509. #endif
  5510. // Allow LARGE_DATA (100MB) responses
  5511. cli_.set_payload_max_length(200 * 1024 * 1024);
  5512. }
  5513. virtual void SetUp() {
  5514. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5515. svr_.set_payload_max_length(200 * 1024 * 1024);
  5516. svr_.set_mount_point("/", "./www");
  5517. svr_.set_mount_point("/mount", "./www2");
  5518. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5519. svr_.Get("/hi",
  5520. [&](const Request & /*req*/, Response &res) {
  5521. res.set_content("Hello World!", "text/plain");
  5522. })
  5523. .Get("/file_content",
  5524. [&](const Request & /*req*/, Response &res) {
  5525. res.set_file_content("./www/dir/test.html");
  5526. })
  5527. .Get("/file_content_with_content_type",
  5528. [&](const Request & /*req*/, Response &res) {
  5529. res.set_file_content("./www/file", "text/plain");
  5530. })
  5531. .Get("/invalid_file_content",
  5532. [&](const Request & /*req*/, Response &res) {
  5533. res.set_file_content("./www/dir/invalid_file_path");
  5534. })
  5535. .Get("/http_response_splitting",
  5536. [&](const Request & /*req*/, Response &res) {
  5537. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5538. EXPECT_EQ(0U, res.headers.size());
  5539. EXPECT_FALSE(res.has_header("a"));
  5540. res.set_header("a", "1\nSet-Cookie: a=1");
  5541. EXPECT_EQ(0U, res.headers.size());
  5542. EXPECT_FALSE(res.has_header("a"));
  5543. res.set_header("a", "1\rSet-Cookie: a=1");
  5544. EXPECT_EQ(0U, res.headers.size());
  5545. EXPECT_FALSE(res.has_header("a"));
  5546. res.set_header("a\r\nb", "0");
  5547. EXPECT_EQ(0U, res.headers.size());
  5548. EXPECT_FALSE(res.has_header("a"));
  5549. res.set_header("a\rb", "0");
  5550. EXPECT_EQ(0U, res.headers.size());
  5551. EXPECT_FALSE(res.has_header("a"));
  5552. res.set_header("a\nb", "0");
  5553. EXPECT_EQ(0U, res.headers.size());
  5554. EXPECT_FALSE(res.has_header("a"));
  5555. res.set_redirect("1\r\nSet-Cookie: a=1");
  5556. EXPECT_EQ(0U, res.headers.size());
  5557. EXPECT_FALSE(res.has_header("Location"));
  5558. })
  5559. .Get("/slow",
  5560. [&](const Request & /*req*/, Response &res) {
  5561. std::this_thread::sleep_for(std::chrono::seconds(4));
  5562. res.set_content("slow", "text/plain");
  5563. })
  5564. #if 0
  5565. .Post("/slowpost",
  5566. [&](const Request & /*req*/, Response &res) {
  5567. std::this_thread::sleep_for(std::chrono::seconds(2));
  5568. res.set_content("slow", "text/plain");
  5569. })
  5570. #endif
  5571. .Get("/remote_addr",
  5572. [&](const Request &req, Response &res) {
  5573. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5574. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5575. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5576. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5577. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5578. #endif
  5579. res.set_content(req.remote_addr, "text/plain");
  5580. })
  5581. .Get("/local_addr",
  5582. [&](const Request &req, Response &res) {
  5583. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5584. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5585. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5586. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5587. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5588. #endif
  5589. auto local_addr = req.local_addr;
  5590. auto local_port = std::to_string(req.local_port);
  5591. res.set_content(local_addr.append(":").append(local_port),
  5592. "text/plain");
  5593. })
  5594. .Get("/endwith%",
  5595. [&](const Request & /*req*/, Response &res) {
  5596. res.set_content("Hello World!", "text/plain");
  5597. })
  5598. .Get("/a\\+\\+b",
  5599. [&](const Request &req, Response &res) {
  5600. ASSERT_TRUE(req.has_param("a +b"));
  5601. auto val = req.get_param_value("a +b");
  5602. res.set_content(val, "text/plain");
  5603. })
  5604. .Get("/", [&](const Request & /*req*/,
  5605. Response &res) { res.set_redirect("/hi"); })
  5606. .Post("/1",
  5607. [](const Request & /*req*/, Response &res) {
  5608. res.set_redirect("/2", StatusCode::SeeOther_303);
  5609. })
  5610. .Get("/2",
  5611. [](const Request & /*req*/, Response &res) {
  5612. res.set_content("redirected.", "text/plain");
  5613. res.status = StatusCode::OK_200;
  5614. })
  5615. .Post("/person",
  5616. [&](const Request &req, Response &res) {
  5617. if (req.has_param("name") && req.has_param("note")) {
  5618. persons_[req.get_param_value("name")] =
  5619. req.get_param_value("note");
  5620. } else {
  5621. res.status = StatusCode::BadRequest_400;
  5622. }
  5623. })
  5624. .Put("/person",
  5625. [&](const Request &req, Response &res) {
  5626. if (req.has_param("name") && req.has_param("note")) {
  5627. persons_[req.get_param_value("name")] =
  5628. req.get_param_value("note");
  5629. } else {
  5630. res.status = StatusCode::BadRequest_400;
  5631. }
  5632. })
  5633. .Get("/person/(.*)",
  5634. [&](const Request &req, Response &res) {
  5635. string name = req.matches[1];
  5636. if (persons_.find(name) != persons_.end()) {
  5637. auto note = persons_[name];
  5638. res.set_content(note, "text/plain");
  5639. } else {
  5640. res.status = StatusCode::NotFound_404;
  5641. }
  5642. })
  5643. .Delete("/person",
  5644. [&](const Request &req, Response &res) {
  5645. if (req.has_param("name")) {
  5646. string name = req.get_param_value("name");
  5647. if (persons_.find(name) != persons_.end()) {
  5648. persons_.erase(name);
  5649. res.set_content("DELETED", "text/plain");
  5650. } else {
  5651. res.status = StatusCode::NotFound_404;
  5652. }
  5653. } else {
  5654. res.status = StatusCode::BadRequest_400;
  5655. }
  5656. })
  5657. .Post("/x-www-form-urlencoded-json",
  5658. [&](const Request &req, Response &res) {
  5659. auto json = req.get_param_value("json");
  5660. ASSERT_EQ(JSON_DATA, json);
  5661. res.set_content(json, "appliation/json");
  5662. res.status = StatusCode::OK_200;
  5663. })
  5664. .Get("/streamed-chunked",
  5665. [&](const Request & /*req*/, Response &res) {
  5666. res.set_chunked_content_provider(
  5667. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5668. sink.os << "123";
  5669. sink.os << "456";
  5670. sink.os << "789";
  5671. sink.done();
  5672. return true;
  5673. });
  5674. })
  5675. .Get("/streamed-chunked-with-prohibited-trailer",
  5676. [&](const Request & /*req*/, Response &res) {
  5677. auto i = new int(0);
  5678. // Declare both a prohibited trailer (Content-Length) and an
  5679. // allowed one
  5680. res.set_header("Trailer", "Content-Length, X-Allowed");
  5681. res.set_chunked_content_provider(
  5682. "text/plain",
  5683. [i](size_t /*offset*/, DataSink &sink) {
  5684. switch (*i) {
  5685. case 0: sink.os << "123"; break;
  5686. case 1: sink.os << "456"; break;
  5687. case 2: sink.os << "789"; break;
  5688. case 3: {
  5689. sink.done_with_trailer(
  5690. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5691. } break;
  5692. }
  5693. (*i)++;
  5694. return true;
  5695. },
  5696. [i](bool success) {
  5697. EXPECT_TRUE(success);
  5698. delete i;
  5699. });
  5700. })
  5701. .Get("/streamed-chunked2",
  5702. [&](const Request & /*req*/, Response &res) {
  5703. auto i = new int(0);
  5704. res.set_chunked_content_provider(
  5705. "text/plain",
  5706. [i](size_t /*offset*/, DataSink &sink) {
  5707. switch (*i) {
  5708. case 0: sink.os << "123"; break;
  5709. case 1: sink.os << "456"; break;
  5710. case 2: sink.os << "789"; break;
  5711. case 3: sink.done(); break;
  5712. }
  5713. (*i)++;
  5714. return true;
  5715. },
  5716. [i](bool success) {
  5717. EXPECT_TRUE(success);
  5718. delete i;
  5719. });
  5720. })
  5721. .Get("/streamed-chunked-with-trailer",
  5722. [&](const Request & /*req*/, Response &res) {
  5723. auto i = new int(0);
  5724. res.set_header("Trailer", "Dummy1, Dummy2");
  5725. res.set_chunked_content_provider(
  5726. "text/plain",
  5727. [i](size_t /*offset*/, DataSink &sink) {
  5728. switch (*i) {
  5729. case 0: sink.os << "123"; break;
  5730. case 1: sink.os << "456"; break;
  5731. case 2: sink.os << "789"; break;
  5732. case 3: {
  5733. sink.done_with_trailer(
  5734. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5735. } break;
  5736. }
  5737. (*i)++;
  5738. return true;
  5739. },
  5740. [i](bool success) {
  5741. EXPECT_TRUE(success);
  5742. delete i;
  5743. });
  5744. })
  5745. .Get("/streamed",
  5746. [&](const Request & /*req*/, Response &res) {
  5747. res.set_content_provider(
  5748. 6, "text/plain",
  5749. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5750. sink.os << (offset < 3 ? "a" : "b");
  5751. return true;
  5752. });
  5753. })
  5754. .Get("/streamed-without-length",
  5755. [&](const Request & /*req*/, Response &res) {
  5756. auto data = new std::string("abcdefg");
  5757. res.set_content_provider(
  5758. "text/plain",
  5759. [data](size_t offset, DataSink &sink) {
  5760. if (offset < data->size()) {
  5761. sink.os << data->substr(offset);
  5762. }
  5763. sink.done();
  5764. return true;
  5765. },
  5766. [data](bool success) {
  5767. EXPECT_TRUE(success);
  5768. delete data;
  5769. });
  5770. })
  5771. .Get("/streamed-with-range",
  5772. [&](const Request &req, Response &res) {
  5773. auto data = new std::string("abcdefg");
  5774. // An explicit status keeps the server from picking the 206 it
  5775. // would otherwise choose for a ranged request, so the response
  5776. // is not a partial representation.
  5777. auto status = req.get_param_value("status");
  5778. if (status == "200") {
  5779. res.status = StatusCode::OK_200;
  5780. } else if (status == "403") {
  5781. res.status = StatusCode::Forbidden_403;
  5782. }
  5783. res.set_content_provider(
  5784. data->size(), "text/plain",
  5785. [data](size_t offset, size_t length, DataSink &sink) {
  5786. size_t DATA_CHUNK_SIZE = 4;
  5787. const auto &d = *data;
  5788. auto out_len =
  5789. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5790. auto ret =
  5791. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5792. EXPECT_TRUE(ret);
  5793. return true;
  5794. },
  5795. [data, &req](bool success) {
  5796. EXPECT_EQ(success, !req.has_param("error"));
  5797. delete data;
  5798. });
  5799. })
  5800. .Get("/streamed-cancel",
  5801. [&](const Request & /*req*/, Response &res) {
  5802. res.set_content_provider(
  5803. size_t(-1), "text/plain",
  5804. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5805. sink.os << "data_chunk";
  5806. return true;
  5807. });
  5808. })
  5809. .Get("/regex-with-delimiter",
  5810. [&](const Request &req, Response & /*res*/) {
  5811. ASSERT_TRUE(req.has_param("key"));
  5812. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5813. })
  5814. .Get("/with-range",
  5815. [&](const Request & /*req*/, Response &res) {
  5816. res.set_content("abcdefg", "text/plain");
  5817. })
  5818. .Get("/test-start-time",
  5819. [&](const Request &req, Response & /*res*/) {
  5820. EXPECT_NE(req.start_time_,
  5821. std::chrono::steady_clock::time_point::min());
  5822. })
  5823. .Get("/with-range-customized-response",
  5824. [&](const Request & /*req*/, Response &res) {
  5825. res.status = StatusCode::BadRequest_400;
  5826. res.set_content(JSON_DATA, "application/json");
  5827. })
  5828. .Post("/chunked",
  5829. [&](const Request &req, Response & /*res*/) {
  5830. EXPECT_EQ(req.body, "dechunked post body");
  5831. })
  5832. .Post("/large-chunked",
  5833. [&](const Request &req, Response & /*res*/) {
  5834. std::string expected(6 * 30 * 1024u, 'a');
  5835. EXPECT_EQ(req.body, expected);
  5836. })
  5837. .Post("/multipart",
  5838. [&](const Request &req, Response & /*res*/) {
  5839. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5840. req.form.get_field_count("text2") +
  5841. req.form.get_field_count("file3") +
  5842. req.form.get_field_count("file4"));
  5843. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5844. req.form.get_file_count("file2"));
  5845. ASSERT_TRUE(!req.form.has_file("???"));
  5846. ASSERT_TRUE(!req.form.has_field("???"));
  5847. ASSERT_TRUE(req.body.empty());
  5848. {
  5849. const auto &text = req.form.get_field("text1");
  5850. EXPECT_EQ("text default", text);
  5851. }
  5852. {
  5853. const auto &text = req.form.get_field("text2");
  5854. EXPECT_EQ("aωb", text);
  5855. }
  5856. {
  5857. const auto &file = req.form.get_file("file1");
  5858. EXPECT_EQ("hello.txt", file.filename);
  5859. EXPECT_EQ("text/plain", file.content_type);
  5860. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5861. }
  5862. {
  5863. const auto &file = req.form.get_file("file2");
  5864. EXPECT_EQ("world.json", file.filename);
  5865. EXPECT_EQ("application/json", file.content_type);
  5866. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5867. }
  5868. {
  5869. const auto &text = req.form.get_field("file3");
  5870. EXPECT_EQ(0u, text.size());
  5871. }
  5872. {
  5873. const auto &text = req.form.get_field("file4");
  5874. EXPECT_EQ(0u, text.size());
  5875. }
  5876. })
  5877. .Post("/multipart/multi_file_values",
  5878. [&](const Request &req, Response & /*res*/) {
  5879. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5880. req.form.get_field_count("multi_text1"));
  5881. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5882. ASSERT_TRUE(!req.form.has_file("???"));
  5883. ASSERT_TRUE(!req.form.has_field("???"));
  5884. ASSERT_TRUE(req.body.empty());
  5885. {
  5886. const auto &text = req.form.get_field("text");
  5887. EXPECT_EQ("default text", text);
  5888. }
  5889. {
  5890. const auto &text1_values = req.form.get_fields("multi_text1");
  5891. EXPECT_EQ(2u, text1_values.size());
  5892. EXPECT_EQ("aaaaa", text1_values[0]);
  5893. EXPECT_EQ("bbbbb", text1_values[1]);
  5894. }
  5895. {
  5896. const auto &file1_values = req.form.get_files("multi_file1");
  5897. EXPECT_EQ(2u, file1_values.size());
  5898. auto file1 = file1_values[0];
  5899. EXPECT_EQ(file1.filename, "hello.txt");
  5900. EXPECT_EQ(file1.content_type, "text/plain");
  5901. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5902. auto file2 = file1_values[1];
  5903. EXPECT_EQ(file2.filename, "world.json");
  5904. EXPECT_EQ(file2.content_type, "application/json");
  5905. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5906. }
  5907. })
  5908. .Post("/empty",
  5909. [&](const Request &req, Response &res) {
  5910. EXPECT_EQ(req.body, "");
  5911. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5912. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5913. res.set_content("empty", "text/plain");
  5914. })
  5915. .Post("/empty-no-content-type",
  5916. [&](const Request &req, Response &res) {
  5917. EXPECT_EQ(req.body, "");
  5918. EXPECT_FALSE(req.has_header("Content-Type"));
  5919. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5920. res.set_content("empty-no-content-type", "text/plain");
  5921. })
  5922. .Post("/path-only",
  5923. [&](const Request &req, Response &res) {
  5924. EXPECT_EQ(req.body, "");
  5925. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5926. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5927. res.set_content("path-only", "text/plain");
  5928. })
  5929. .Post("/path-headers-only",
  5930. [&](const Request &req, Response &res) {
  5931. EXPECT_EQ(req.body, "");
  5932. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5933. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5934. EXPECT_EQ("world", req.get_header_value("hello"));
  5935. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5936. res.set_content("path-headers-only", "text/plain");
  5937. })
  5938. .Post("/post-large",
  5939. [&](const Request &req, Response &res) {
  5940. EXPECT_EQ(req.body, LARGE_DATA);
  5941. res.set_content(req.body, "text/plain");
  5942. })
  5943. .Post("/post-loopback",
  5944. [&](const Request &, Response &res,
  5945. ContentReader const &content_reader) {
  5946. std::string body;
  5947. content_reader([&](const char *data, size_t data_length) {
  5948. body.append(data, data_length);
  5949. return true;
  5950. });
  5951. res.set_content(body, "text/plain");
  5952. })
  5953. .Put("/put-loopback",
  5954. [&](const Request &, Response &res,
  5955. ContentReader const &content_reader) {
  5956. std::string body;
  5957. content_reader([&](const char *data, size_t data_length) {
  5958. body.append(data, data_length);
  5959. return true;
  5960. });
  5961. res.set_content(body, "text/plain");
  5962. })
  5963. .Patch("/patch-loopback",
  5964. [&](const Request &, Response &res,
  5965. ContentReader const &content_reader) {
  5966. std::string body;
  5967. content_reader([&](const char *data, size_t data_length) {
  5968. body.append(data, data_length);
  5969. return true;
  5970. });
  5971. res.set_content(body, "text/plain");
  5972. })
  5973. .Put("/empty-no-content-type",
  5974. [&](const Request &req, Response &res) {
  5975. EXPECT_EQ(req.body, "");
  5976. EXPECT_FALSE(req.has_header("Content-Type"));
  5977. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5978. res.set_content("empty-no-content-type", "text/plain");
  5979. })
  5980. .Put("/put",
  5981. [&](const Request &req, Response &res) {
  5982. EXPECT_EQ(req.body, "PUT");
  5983. res.set_content(req.body, "text/plain");
  5984. })
  5985. .Put("/put-large",
  5986. [&](const Request &req, Response &res) {
  5987. EXPECT_EQ(req.body, LARGE_DATA);
  5988. res.set_content(req.body, "text/plain");
  5989. })
  5990. .Patch("/patch",
  5991. [&](const Request &req, Response &res) {
  5992. EXPECT_EQ(req.body, "PATCH");
  5993. res.set_content(req.body, "text/plain");
  5994. })
  5995. .Delete("/delete",
  5996. [&](const Request & /*req*/, Response &res) {
  5997. res.set_content("DELETE", "text/plain");
  5998. })
  5999. .Delete("/delete-body",
  6000. [&](const Request &req, Response &res) {
  6001. EXPECT_EQ(req.body, "content");
  6002. res.set_content(req.body, "text/plain");
  6003. })
  6004. .Options(R"(\*)",
  6005. [&](const Request & /*req*/, Response &res) {
  6006. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6007. })
  6008. .CustomRoute("PROPFIND", "/dav/:id",
  6009. [&](const Request &req, Response &res) {
  6010. res.set_header("x-body-size",
  6011. std::to_string(req.body.size()));
  6012. res.set_header("x-matched-route", req.matched_route);
  6013. res.set_header("x-dav-id", req.path_params.at("id"));
  6014. res.status = StatusCode::MultiStatus_207;
  6015. res.set_content(req.body, "application/xml");
  6016. })
  6017. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6018. [&](const Request &req, Response &res) {
  6019. res.set_header("x-dav-match", req.matches[1]);
  6020. res.status = StatusCode::MultiStatus_207;
  6021. })
  6022. .CustomRoute("MKCOL", "/dav-mkcol",
  6023. [&](const Request &req, Response &res) {
  6024. EXPECT_TRUE(req.body.empty());
  6025. res.status = StatusCode::Created_201;
  6026. })
  6027. .CustomRoute(
  6028. "REPORT", "/dav-report",
  6029. [&](const Request & /*req*/, Response &res,
  6030. const ContentReader &content_reader) {
  6031. std::string body;
  6032. content_reader([&](const char *data, size_t data_length) {
  6033. body.append(data, data_length);
  6034. return true;
  6035. });
  6036. res.set_header("x-body-size", std::to_string(body.size()));
  6037. res.status = StatusCode::MultiStatus_207;
  6038. res.set_content(body, "application/xml");
  6039. })
  6040. .Get("/request-target",
  6041. [&](const Request &req, Response & /*res*/) {
  6042. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6043. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6044. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6045. })
  6046. .Get("/long-query-value",
  6047. [&](const Request &req, Response & /*res*/) {
  6048. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6049. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6050. })
  6051. .Get("/too-long-query-value",
  6052. [&](const Request &req, Response & /*res*/) {
  6053. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6054. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6055. })
  6056. .Get("/array-param",
  6057. [&](const Request &req, Response & /*res*/) {
  6058. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6059. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6060. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6061. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6062. })
  6063. .Get("/array-param-values",
  6064. [&](const Request &req, Response & /*res*/) {
  6065. auto values = req.get_param_values("array");
  6066. EXPECT_EQ(3u, values.size());
  6067. EXPECT_EQ("value1", values[0]);
  6068. EXPECT_EQ("value2", values[1]);
  6069. EXPECT_EQ("value3", values[2]);
  6070. auto empty = req.get_param_values("nonexistent");
  6071. EXPECT_TRUE(empty.empty());
  6072. })
  6073. .Post("/validate-no-multiple-headers",
  6074. [&](const Request &req, Response & /*res*/) {
  6075. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6076. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6077. })
  6078. .Post("/content_receiver",
  6079. [&](const Request &req, Response &res,
  6080. const ContentReader &content_reader) {
  6081. if (req.is_multipart_form_data()) {
  6082. std::vector<FormData> items;
  6083. content_reader(
  6084. [&](const FormData &file) {
  6085. items.push_back(file);
  6086. return true;
  6087. },
  6088. [&](const char *data, size_t data_length) {
  6089. items.back().content.append(data, data_length);
  6090. return true;
  6091. });
  6092. EXPECT_EQ(5u, items.size());
  6093. {
  6094. const auto &file = get_file_value(items, "text1");
  6095. EXPECT_TRUE(file.filename.empty());
  6096. EXPECT_EQ("text default", file.content);
  6097. }
  6098. {
  6099. const auto &file = get_file_value(items, "text2");
  6100. EXPECT_TRUE(file.filename.empty());
  6101. EXPECT_EQ("aωb", file.content);
  6102. }
  6103. {
  6104. const auto &file = get_file_value(items, "file1");
  6105. EXPECT_EQ("hello.txt", file.filename);
  6106. EXPECT_EQ("text/plain", file.content_type);
  6107. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6108. }
  6109. {
  6110. const auto &file = get_file_value(items, "file2");
  6111. EXPECT_EQ("world.json", file.filename);
  6112. EXPECT_EQ("application/json", file.content_type);
  6113. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6114. }
  6115. {
  6116. const auto &file = get_file_value(items, "file3");
  6117. EXPECT_TRUE(file.filename.empty());
  6118. EXPECT_EQ("application/octet-stream", file.content_type);
  6119. EXPECT_EQ(0u, file.content.size());
  6120. }
  6121. } else {
  6122. std::string body;
  6123. content_reader([&](const char *data, size_t data_length) {
  6124. EXPECT_EQ(7U, data_length);
  6125. body.append(data, data_length);
  6126. return true;
  6127. });
  6128. EXPECT_EQ(body, "content");
  6129. res.set_content(body, "text/plain");
  6130. }
  6131. })
  6132. .Put("/content_receiver",
  6133. [&](const Request & /*req*/, Response &res,
  6134. const ContentReader &content_reader) {
  6135. std::string body;
  6136. content_reader([&](const char *data, size_t data_length) {
  6137. body.append(data, data_length);
  6138. return true;
  6139. });
  6140. EXPECT_EQ(body, "content");
  6141. res.set_content(body, "text/plain");
  6142. })
  6143. .Patch("/content_receiver",
  6144. [&](const Request & /*req*/, Response &res,
  6145. const ContentReader &content_reader) {
  6146. std::string body;
  6147. content_reader([&](const char *data, size_t data_length) {
  6148. body.append(data, data_length);
  6149. return true;
  6150. });
  6151. EXPECT_EQ(body, "content");
  6152. res.set_content(body, "text/plain");
  6153. })
  6154. .Post("/query-string-and-body",
  6155. [&](const Request &req, Response & /*res*/) {
  6156. ASSERT_TRUE(req.has_param("key"));
  6157. EXPECT_EQ(req.get_param_value("key"), "value");
  6158. EXPECT_EQ(req.body, "content");
  6159. })
  6160. .Get("/last-request",
  6161. [&](const Request &req, Response & /*res*/) {
  6162. EXPECT_EQ("close", req.get_header_value("Connection"));
  6163. })
  6164. .Get(R"(/redirect/(\d+))",
  6165. [&](const Request &req, Response &res) {
  6166. auto num = std::stoi(req.matches[1]) + 1;
  6167. std::string url = "/redirect/" + std::to_string(num);
  6168. res.set_redirect(url);
  6169. })
  6170. .Post("/binary",
  6171. [&](const Request &req, Response &res) {
  6172. EXPECT_EQ(4U, req.body.size());
  6173. EXPECT_EQ("application/octet-stream",
  6174. req.get_header_value("Content-Type"));
  6175. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6176. res.set_content(req.body, "application/octet-stream");
  6177. })
  6178. .Put("/binary",
  6179. [&](const Request &req, Response &res) {
  6180. EXPECT_EQ(4U, req.body.size());
  6181. EXPECT_EQ("application/octet-stream",
  6182. req.get_header_value("Content-Type"));
  6183. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6184. res.set_content(req.body, "application/octet-stream");
  6185. })
  6186. .Patch("/binary",
  6187. [&](const Request &req, Response &res) {
  6188. EXPECT_EQ(4U, req.body.size());
  6189. EXPECT_EQ("application/octet-stream",
  6190. req.get_header_value("Content-Type"));
  6191. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6192. res.set_content(req.body, "application/octet-stream");
  6193. })
  6194. .Delete("/binary",
  6195. [&](const Request &req, Response &res) {
  6196. EXPECT_EQ(4U, req.body.size());
  6197. EXPECT_EQ("application/octet-stream",
  6198. req.get_header_value("Content-Type"));
  6199. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6200. res.set_content(req.body, "application/octet-stream");
  6201. })
  6202. .Get("/issue1772",
  6203. [&](const Request & /*req*/, Response &res) {
  6204. res.status = 401;
  6205. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6206. })
  6207. .Delete("/issue609",
  6208. [](const httplib::Request &, httplib::Response &res,
  6209. const httplib::ContentReader &) {
  6210. res.set_content("ok", "text/plain");
  6211. })
  6212. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6213. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6214. .Get("/compress",
  6215. [&](const Request & /*req*/, Response &res) {
  6216. res.set_content(
  6217. "12345678901234567890123456789012345678901234567890123456789"
  6218. "01234567890123456789012345678901234567890",
  6219. "text/plain");
  6220. })
  6221. .Get("/compress-with-charset",
  6222. [&](const Request & /*req*/, Response &res) {
  6223. res.set_content(
  6224. "12345678901234567890123456789012345678901234567890123456789"
  6225. "01234567890123456789012345678901234567890",
  6226. "application/json; charset=utf-8");
  6227. })
  6228. .Get("/nocompress",
  6229. [&](const Request & /*req*/, Response &res) {
  6230. res.set_content(
  6231. "12345678901234567890123456789012345678901234567890123456789"
  6232. "01234567890123456789012345678901234567890",
  6233. "application/octet-stream");
  6234. })
  6235. .Post("/compress-multipart",
  6236. [&](const Request &req, Response & /*res*/) {
  6237. EXPECT_EQ(2u, req.form.fields.size());
  6238. ASSERT_TRUE(!req.form.has_field("???"));
  6239. {
  6240. const auto &text = req.form.get_field("key1");
  6241. EXPECT_EQ("test", text);
  6242. }
  6243. {
  6244. const auto &text = req.form.get_field("key2");
  6245. EXPECT_EQ("--abcdefg123", text);
  6246. }
  6247. })
  6248. #endif
  6249. ;
  6250. persons_["john"] = "programmer";
  6251. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6252. svr_.wait_until_ready();
  6253. }
  6254. virtual void TearDown() {
  6255. svr_.stop();
  6256. if (!request_threads_.empty()) {
  6257. std::this_thread::sleep_for(std::chrono::seconds(1));
  6258. for (auto &t : request_threads_) {
  6259. t.join();
  6260. }
  6261. }
  6262. t_.join();
  6263. }
  6264. map<string, string> persons_;
  6265. #ifdef CPPHTTPLIB_SSL_ENABLED
  6266. SSLClient cli_;
  6267. SSLServer svr_;
  6268. #else
  6269. Client cli_;
  6270. Server svr_;
  6271. #endif
  6272. thread t_;
  6273. std::vector<thread> request_threads_;
  6274. };
  6275. TEST_F(ServerTest, GetMethod200) {
  6276. auto res = cli_.Get("/hi");
  6277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6278. EXPECT_EQ("HTTP/1.1", res->version);
  6279. EXPECT_EQ(StatusCode::OK_200, res->status);
  6280. EXPECT_EQ("OK", res->reason);
  6281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6282. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6283. EXPECT_EQ("Hello World!", res->body);
  6284. }
  6285. TEST_F(ServerTest, GetEmptyFile) {
  6286. auto res = cli_.Get("/empty_file");
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. EXPECT_EQ(StatusCode::OK_200, res->status);
  6289. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6290. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6291. EXPECT_EQ("", res->body);
  6292. }
  6293. TEST_F(ServerTest, GetFileContent) {
  6294. auto res = cli_.Get("/file_content");
  6295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6296. EXPECT_EQ(StatusCode::OK_200, res->status);
  6297. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6298. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6299. EXPECT_EQ("test.html", res->body);
  6300. }
  6301. TEST_F(ServerTest, GetFileContentWithRange) {
  6302. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6305. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6306. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6307. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6308. EXPECT_EQ("est", res->body);
  6309. }
  6310. TEST_F(ServerTest, GetFileContentWithContentType) {
  6311. auto res = cli_.Get("/file_content_with_content_type");
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. EXPECT_EQ(StatusCode::OK_200, res->status);
  6314. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6315. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6316. EXPECT_EQ("file\n", res->body);
  6317. }
  6318. TEST_F(ServerTest, GetInvalidFileContent) {
  6319. auto res = cli_.Get("/invalid_file_content");
  6320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6321. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6322. }
  6323. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6324. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. EXPECT_EQ("HTTP/1.1", res->version);
  6327. EXPECT_EQ(StatusCode::OK_200, res->status);
  6328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6329. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6330. EXPECT_EQ("Hello World!", res->body);
  6331. }
  6332. TEST_F(ServerTest, GetMethod302) {
  6333. auto res = cli_.Get("/");
  6334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6335. EXPECT_EQ(StatusCode::Found_302, res->status);
  6336. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6337. }
  6338. TEST_F(ServerTest, GetMethod302Redirect) {
  6339. cli_.set_follow_location(true);
  6340. auto res = cli_.Get("/");
  6341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6342. EXPECT_EQ(StatusCode::OK_200, res->status);
  6343. EXPECT_EQ("Hello World!", res->body);
  6344. EXPECT_EQ("/hi", res->location);
  6345. }
  6346. TEST_F(ServerTest, GetMethod404) {
  6347. auto res = cli_.Get("/invalid");
  6348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6349. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6350. }
  6351. TEST_F(ServerTest, HeadMethod200) {
  6352. auto res = cli_.Head("/hi");
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. EXPECT_EQ(StatusCode::OK_200, res->status);
  6355. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6356. EXPECT_TRUE(res->body.empty());
  6357. }
  6358. TEST_F(ServerTest, HeadMethod200Static) {
  6359. auto res = cli_.Head("/mount/dir/index.html");
  6360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6361. EXPECT_EQ(StatusCode::OK_200, res->status);
  6362. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6363. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6364. EXPECT_TRUE(res->body.empty());
  6365. }
  6366. TEST_F(ServerTest, HeadMethod404) {
  6367. auto res = cli_.Head("/invalid");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6370. EXPECT_TRUE(res->body.empty());
  6371. }
  6372. TEST_F(ServerTest, GetMethodPersonJohn) {
  6373. auto res = cli_.Get("/person/john");
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. EXPECT_EQ(StatusCode::OK_200, res->status);
  6376. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6377. EXPECT_EQ("programmer", res->body);
  6378. }
  6379. TEST_F(ServerTest, PostMethod1) {
  6380. auto res = cli_.Get("/person/john1");
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6383. res = cli_.Post("/person", "name=john1&note=coder",
  6384. "application/x-www-form-urlencoded");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. ASSERT_EQ(StatusCode::OK_200, res->status);
  6387. res = cli_.Get("/person/john1");
  6388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6389. ASSERT_EQ(StatusCode::OK_200, res->status);
  6390. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6391. ASSERT_EQ("coder", res->body);
  6392. }
  6393. TEST_F(ServerTest, PostMethod2) {
  6394. auto res = cli_.Get("/person/john2");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6397. Params params;
  6398. params.emplace("name", "john2");
  6399. params.emplace("note", "coder");
  6400. res = cli_.Post("/person", params);
  6401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6402. ASSERT_EQ(StatusCode::OK_200, res->status);
  6403. res = cli_.Get("/person/john2");
  6404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6405. ASSERT_EQ(StatusCode::OK_200, res->status);
  6406. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6407. ASSERT_EQ("coder", res->body);
  6408. }
  6409. TEST_F(ServerTest, PutMethod3) {
  6410. auto res = cli_.Get("/person/john3");
  6411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6412. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6413. Params params;
  6414. params.emplace("name", "john3");
  6415. params.emplace("note", "coder");
  6416. res = cli_.Put("/person", params);
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. ASSERT_EQ(StatusCode::OK_200, res->status);
  6419. res = cli_.Get("/person/john3");
  6420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6421. ASSERT_EQ(StatusCode::OK_200, res->status);
  6422. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6423. ASSERT_EQ("coder", res->body);
  6424. }
  6425. TEST_F(ServerTest, DeleteMethod1) {
  6426. auto res = cli_.Get("/person/john4");
  6427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6428. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6429. Params params;
  6430. params.emplace("name", "john4");
  6431. params.emplace("note", "coder");
  6432. res = cli_.Post("/person", params);
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. ASSERT_EQ(StatusCode::OK_200, res->status);
  6435. res = cli_.Get("/person/john4");
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. ASSERT_EQ(StatusCode::OK_200, res->status);
  6438. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6439. ASSERT_EQ("coder", res->body);
  6440. Params delete_params;
  6441. delete_params.emplace("name", "john4");
  6442. res = cli_.Delete("/person", delete_params);
  6443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6444. ASSERT_EQ(StatusCode::OK_200, res->status);
  6445. ASSERT_EQ("DELETED", res->body);
  6446. res = cli_.Get("/person/john4");
  6447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6448. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6449. }
  6450. TEST_F(ServerTest, DeleteMethod2) {
  6451. auto res = cli_.Get("/person/john5");
  6452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6453. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6454. Params params;
  6455. params.emplace("name", "john5");
  6456. params.emplace("note", "developer");
  6457. res = cli_.Post("/person", params);
  6458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6459. ASSERT_EQ(StatusCode::OK_200, res->status);
  6460. res = cli_.Get("/person/john5");
  6461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6462. ASSERT_EQ(StatusCode::OK_200, res->status);
  6463. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6464. ASSERT_EQ("developer", res->body);
  6465. Params delete_params;
  6466. delete_params.emplace("name", "john5");
  6467. Headers headers;
  6468. headers.emplace("Custom-Header", "test-value");
  6469. res = cli_.Delete("/person", headers, delete_params);
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. ASSERT_EQ(StatusCode::OK_200, res->status);
  6472. ASSERT_EQ("DELETED", res->body);
  6473. res = cli_.Get("/person/john5");
  6474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6475. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6476. }
  6477. TEST_F(ServerTest, DeleteMethod3) {
  6478. auto res = cli_.Get("/person/john6");
  6479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6480. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6481. Params params;
  6482. params.emplace("name", "john6");
  6483. params.emplace("note", "tester");
  6484. res = cli_.Post("/person", params);
  6485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6486. ASSERT_EQ(StatusCode::OK_200, res->status);
  6487. res = cli_.Get("/person/john6");
  6488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6489. ASSERT_EQ(StatusCode::OK_200, res->status);
  6490. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6491. ASSERT_EQ("tester", res->body);
  6492. Params delete_params;
  6493. delete_params.emplace("name", "john6");
  6494. Headers headers;
  6495. headers.emplace("Custom-Header", "test-value");
  6496. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6498. ASSERT_EQ(StatusCode::OK_200, res->status);
  6499. ASSERT_EQ("DELETED", res->body);
  6500. res = cli_.Get("/person/john6");
  6501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6502. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6503. }
  6504. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6505. Params params;
  6506. params.emplace("json", JSON_DATA);
  6507. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. ASSERT_EQ(StatusCode::OK_200, res->status);
  6510. ASSERT_EQ(JSON_DATA, res->body);
  6511. }
  6512. TEST_F(ServerTest, PostEmptyContent) {
  6513. auto res = cli_.Post("/empty", "", "text/plain");
  6514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6515. ASSERT_EQ(StatusCode::OK_200, res->status);
  6516. ASSERT_EQ("empty", res->body);
  6517. }
  6518. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6519. auto res = cli_.Post("/empty-no-content-type");
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. ASSERT_EQ(StatusCode::OK_200, res->status);
  6522. ASSERT_EQ("empty-no-content-type", res->body);
  6523. }
  6524. TEST_F(ServerTest, PostPathOnly) {
  6525. auto res = cli_.Post("/path-only");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. ASSERT_EQ(StatusCode::OK_200, res->status);
  6528. ASSERT_EQ("path-only", res->body);
  6529. }
  6530. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6531. auto res = cli_.Post("/path-headers-only",
  6532. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6534. ASSERT_EQ(StatusCode::OK_200, res->status);
  6535. ASSERT_EQ("path-headers-only", res->body);
  6536. }
  6537. TEST_F(ServerTest, PostLarge) {
  6538. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. ASSERT_EQ(StatusCode::OK_200, res->status);
  6541. EXPECT_EQ(LARGE_DATA, res->body);
  6542. }
  6543. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6544. auto res = cli_.Put("/empty-no-content-type");
  6545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6546. ASSERT_EQ(StatusCode::OK_200, res->status);
  6547. ASSERT_EQ("empty-no-content-type", res->body);
  6548. }
  6549. TEST_F(ServerTest, GetMethodDir) {
  6550. auto res = cli_.Get("/dir/");
  6551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6552. EXPECT_EQ(StatusCode::OK_200, res->status);
  6553. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6554. auto body = R"(<html>
  6555. <head>
  6556. </head>
  6557. <body>
  6558. <a href="/dir/test.html">Test</a>
  6559. <a href="/hi">hi</a>
  6560. </body>
  6561. </html>
  6562. )";
  6563. EXPECT_EQ(body, res->body);
  6564. }
  6565. TEST_F(ServerTest, GetMethodDirTest) {
  6566. auto res = cli_.Get("/dir/test.html");
  6567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6568. EXPECT_EQ(StatusCode::OK_200, res->status);
  6569. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6570. EXPECT_EQ("test.html", res->body);
  6571. }
  6572. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6573. auto res = cli_.Get("/dir/../dir/test.html");
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6576. }
  6577. TEST_F(ServerTest, GetMethodInvalidPath) {
  6578. auto res = cli_.Get("/dir/../test.html");
  6579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6580. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6581. }
  6582. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6583. auto res = cli_.Get("/../www/dir/test.html");
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6586. }
  6587. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6588. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6590. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6591. }
  6592. TEST_F(ServerTest, GetMethodDirMountTest) {
  6593. auto res = cli_.Get("/mount/dir/test.html");
  6594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6595. EXPECT_EQ(StatusCode::OK_200, res->status);
  6596. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6597. EXPECT_EQ("test.html", res->body);
  6598. }
  6599. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6600. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6602. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6603. }
  6604. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6605. auto res = cli_.Get("/mount/dir/../test.html");
  6606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6607. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6608. }
  6609. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6610. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6612. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6613. }
  6614. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6615. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6617. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6618. }
  6619. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6620. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6622. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6623. }
  6624. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6625. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6627. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6628. }
  6629. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6630. auto res = cli_.Get("/mount/dir");
  6631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6632. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6633. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6634. }
  6635. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6636. auto res = cli_.Get("//dir");
  6637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6638. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6639. EXPECT_FALSE(res->has_header("Location"));
  6640. }
  6641. TEST_F(ServerTest, PostMethod303) {
  6642. auto res = cli_.Post("/1", "body", "text/plain");
  6643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6644. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6645. EXPECT_EQ("/2", res->get_header_value("Location"));
  6646. }
  6647. TEST_F(ServerTest, PostMethod303Redirect) {
  6648. cli_.set_follow_location(true);
  6649. auto res = cli_.Post("/1", "body", "text/plain");
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::OK_200, res->status);
  6652. EXPECT_EQ("redirected.", res->body);
  6653. EXPECT_EQ("/2", res->location);
  6654. }
  6655. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6656. auto res = cli_.Get("/dir/test.abcde");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::OK_200, res->status);
  6659. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6660. EXPECT_EQ("abcde", res->body);
  6661. }
  6662. TEST_F(ServerTest, StaticFileRange) {
  6663. auto res =
  6664. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6666. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6667. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6668. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6669. EXPECT_EQ(true, res->has_header("Content-Range"));
  6670. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6671. EXPECT_EQ(std::string("cd"), res->body);
  6672. }
  6673. TEST_F(ServerTest, StaticFileRanges) {
  6674. auto res = cli_.Get("/dir/test.abcde",
  6675. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6677. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6678. EXPECT_TRUE(
  6679. res->get_header_value("Content-Type")
  6680. .find(
  6681. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6682. 0);
  6683. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6684. }
  6685. TEST_F(ServerTest, StaticFileRangeHead) {
  6686. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6688. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6689. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6690. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6691. EXPECT_EQ(true, res->has_header("Content-Range"));
  6692. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6693. }
  6694. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6695. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6698. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6699. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6700. EXPECT_EQ(true, res->has_header("Content-Range"));
  6701. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6702. res->get_header_value("Content-Range"));
  6703. EXPECT_EQ("LAST\n", res->body);
  6704. }
  6705. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6706. auto res =
  6707. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6711. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6712. EXPECT_EQ(true, res->has_header("Content-Range"));
  6713. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6714. }
  6715. TEST_F(ServerTest, StaticFileBigFile) {
  6716. auto res = cli_.Get("/dir/1MB.txt");
  6717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6718. EXPECT_EQ(StatusCode::OK_200, res->status);
  6719. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6720. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6721. }
  6722. TEST_F(ServerTest, InvalidBaseDirMount) {
  6723. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6724. }
  6725. TEST_F(ServerTest, Binary) {
  6726. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6727. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6728. "application/octet-stream");
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. ASSERT_EQ(StatusCode::OK_200, res->status);
  6731. ASSERT_EQ(4U, res->body.size());
  6732. res = cli_.Put("/binary", binary.data(), binary.size(),
  6733. "application/octet-stream");
  6734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6735. ASSERT_EQ(StatusCode::OK_200, res->status);
  6736. ASSERT_EQ(4U, res->body.size());
  6737. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6738. "application/octet-stream");
  6739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6740. ASSERT_EQ(StatusCode::OK_200, res->status);
  6741. ASSERT_EQ(4U, res->body.size());
  6742. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6743. "application/octet-stream");
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. ASSERT_EQ(StatusCode::OK_200, res->status);
  6746. ASSERT_EQ(4U, res->body.size());
  6747. }
  6748. TEST_F(ServerTest, BinaryString) {
  6749. auto binary = std::string("\x00\x01\x02\x03", 4);
  6750. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. ASSERT_EQ(StatusCode::OK_200, res->status);
  6753. ASSERT_EQ(4U, res->body.size());
  6754. res = cli_.Put("/binary", binary, "application/octet-stream");
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. ASSERT_EQ(StatusCode::OK_200, res->status);
  6757. ASSERT_EQ(4U, res->body.size());
  6758. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. ASSERT_EQ(StatusCode::OK_200, res->status);
  6761. ASSERT_EQ(4U, res->body.size());
  6762. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6764. ASSERT_EQ(StatusCode::OK_200, res->status);
  6765. ASSERT_EQ(4U, res->body.size());
  6766. }
  6767. TEST_F(ServerTest, EmptyRequest) {
  6768. auto res = cli_.Get("");
  6769. ASSERT_TRUE(!res);
  6770. EXPECT_EQ(Error::Connection, res.error());
  6771. }
  6772. TEST_F(ServerTest, LongRequest) {
  6773. std::string request;
  6774. for (size_t i = 0; i < 545; i++) {
  6775. request += "/TooLongRequest";
  6776. }
  6777. request += "OK";
  6778. auto res = cli_.Get(request.c_str());
  6779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6780. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6781. }
  6782. TEST_F(ServerTest, TooLongRequest) {
  6783. std::string request;
  6784. for (size_t i = 0; i < 546; i++) {
  6785. request += "/TooLongRequest";
  6786. }
  6787. request += "_NG";
  6788. auto start = std::chrono::high_resolution_clock::now();
  6789. cli_.set_keep_alive(true);
  6790. auto res = cli_.Get(request.c_str());
  6791. auto end = std::chrono::high_resolution_clock::now();
  6792. auto elapsed =
  6793. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6794. .count();
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6797. EXPECT_LE(elapsed, 1000);
  6798. EXPECT_EQ("close", res->get_header_value("Connection"));
  6799. EXPECT_FALSE(cli_.is_socket_open());
  6800. }
  6801. TEST_F(ServerTest, AlmostTooLongRequest) {
  6802. // test for #2046 - URI length check shouldn't include other content on req
  6803. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6804. // leading /, space, HTTP/1.1)
  6805. std::string request =
  6806. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6807. auto res = cli_.Get(request.c_str());
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6810. }
  6811. TEST_F(ServerTest, LongHeader) {
  6812. Request req;
  6813. req.method = "GET";
  6814. req.path = "/hi";
  6815. std::string host_and_port;
  6816. host_and_port += HOST;
  6817. host_and_port += ":";
  6818. host_and_port += std::to_string(PORT);
  6819. req.headers.emplace("Host", host_and_port.c_str());
  6820. req.headers.emplace("Accept", "*/*");
  6821. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6822. req.headers.emplace(
  6823. "Header-Name",
  6824. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6825. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6826. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6827. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6828. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6829. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6830. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6831. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6832. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6833. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6834. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6835. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6836. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6837. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6838. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6839. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6840. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6841. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6842. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6843. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6844. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6845. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6846. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6847. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6848. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6849. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6850. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6851. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6852. "@@@@@@@@@@@@@@@@");
  6853. auto res = std::make_shared<Response>();
  6854. auto error = Error::Success;
  6855. auto ret = cli_.send(req, *res, error);
  6856. ASSERT_TRUE(ret);
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. }
  6859. TEST_F(ServerTest, LongQueryValue) {
  6860. auto start = std::chrono::high_resolution_clock::now();
  6861. cli_.set_keep_alive(true);
  6862. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6863. auto end = std::chrono::high_resolution_clock::now();
  6864. auto elapsed =
  6865. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6866. .count();
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6869. EXPECT_LE(elapsed, 1000);
  6870. EXPECT_EQ("close", res->get_header_value("Connection"));
  6871. EXPECT_FALSE(cli_.is_socket_open());
  6872. }
  6873. TEST_F(ServerTest, TooLongQueryValue) {
  6874. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6875. ASSERT_FALSE(res);
  6876. EXPECT_EQ(Error::Read, res.error());
  6877. }
  6878. TEST_F(ServerTest, TooLongHeader) {
  6879. Request req;
  6880. req.method = "GET";
  6881. req.path = "/hi";
  6882. std::string host_and_port;
  6883. host_and_port += HOST;
  6884. host_and_port += ":";
  6885. host_and_port += std::to_string(PORT);
  6886. req.headers.emplace("Host", host_and_port.c_str());
  6887. req.headers.emplace("Accept", "*/*");
  6888. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6889. req.headers.emplace(
  6890. "Header-Name",
  6891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6892. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6893. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6894. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6895. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6911. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6912. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6913. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6914. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6915. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6916. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6917. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6918. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6919. "@@@@@@@@@@@@@@@@@");
  6920. auto res = std::make_shared<Response>();
  6921. auto error = Error::Success;
  6922. auto ret = cli_.send(req, *res, error);
  6923. ASSERT_TRUE(ret);
  6924. EXPECT_EQ(StatusCode::OK_200, res->status);
  6925. }
  6926. TEST_F(ServerTest, HeaderCountAtLimit) {
  6927. // Test with headers just under the 100 limit
  6928. httplib::Headers headers;
  6929. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6930. // This should keep us just under the 100 header limit
  6931. for (int i = 0; i < 95; i++) {
  6932. std::string name = "X-Test-Header-" + std::to_string(i);
  6933. std::string value = "value" + std::to_string(i);
  6934. headers.emplace(name, value);
  6935. }
  6936. // This should work fine as we're under the limit
  6937. auto res = cli_.Get("/hi", headers);
  6938. EXPECT_TRUE(res);
  6939. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6940. }
  6941. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6942. // Test with many headers to exceed the 100 limit
  6943. httplib::Headers headers;
  6944. // Add 150 headers to definitely exceed the 100 limit
  6945. for (int i = 0; i < 150; i++) {
  6946. std::string name = "X-Test-Header-" + std::to_string(i);
  6947. std::string value = "value" + std::to_string(i);
  6948. headers.emplace(name, value);
  6949. }
  6950. // This should fail due to exceeding header count limit
  6951. cli_.set_keep_alive(true);
  6952. auto res = cli_.Get("/hi", headers);
  6953. // The server should respond with 400 Bad Request
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6956. EXPECT_EQ("close", res->get_header_value("Connection"));
  6957. EXPECT_FALSE(cli_.is_socket_open());
  6958. }
  6959. TEST_F(ServerTest, PercentEncoding) {
  6960. auto res = cli_.Get("/e%6edwith%");
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::OK_200, res->status);
  6963. }
  6964. TEST_F(ServerTest, PercentEncodingUnicode) {
  6965. auto res = cli_.Get("/e%u006edwith%");
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::OK_200, res->status);
  6968. }
  6969. TEST_F(ServerTest, InvalidPercentEncoding) {
  6970. auto res = cli_.Get("/%endwith%");
  6971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6973. }
  6974. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6975. auto res = cli_.Get("/%uendwith%");
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6978. }
  6979. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6980. auto res = cli_.Get("/hello?aaa=bbb%");
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6983. }
  6984. TEST_F(ServerTest, PlusSignEncoding) {
  6985. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. EXPECT_EQ(StatusCode::OK_200, res->status);
  6988. EXPECT_EQ("a +b", res->body);
  6989. }
  6990. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6991. // This test simulates a potential DoS attack using many headers
  6992. // to verify our security fix prevents memory exhaustion
  6993. httplib::Headers attack_headers;
  6994. // Attempt to add many headers like an attacker would (200 headers to far
  6995. // exceed limit)
  6996. for (int i = 0; i < 200; i++) {
  6997. std::string name = "X-Attack-Header-" + std::to_string(i);
  6998. std::string value = "attack_payload_" + std::to_string(i);
  6999. attack_headers.emplace(name, value);
  7000. }
  7001. // Try to POST with excessive headers
  7002. cli_.set_keep_alive(true);
  7003. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7004. // Should either fail or return 400 Bad Request due to security limit
  7005. if (res) {
  7006. // If we get a response, it should be 400 Bad Request
  7007. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7008. EXPECT_EQ("close", res->get_header_value("Connection"));
  7009. }
  7010. EXPECT_FALSE(cli_.is_socket_open());
  7011. }
  7012. TEST_F(ServerTest, MultipartFormData) {
  7013. UploadFormDataItems items = {
  7014. {"text1", "text default", "", ""},
  7015. {"text2", "aωb", "", ""},
  7016. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7017. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7018. {"file3", "", "", "application/octet-stream"},
  7019. {"file4", "", "", " application/json tmp-string "}};
  7020. auto res = cli_.Post("/multipart", items);
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. EXPECT_EQ(StatusCode::OK_200, res->status);
  7023. }
  7024. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7025. UploadFormDataItems items = {
  7026. {"text", "default text", "", ""},
  7027. {"multi_text1", "aaaaa", "", ""},
  7028. {"multi_text1", "bbbbb", "", ""},
  7029. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7030. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7031. "application/json"},
  7032. };
  7033. auto res = cli_.Post("/multipart/multi_file_values", items);
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. EXPECT_EQ(StatusCode::OK_200, res->status);
  7036. }
  7037. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7038. auto res = cli_.Get("/hi");
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. EXPECT_EQ(StatusCode::OK_200, res->status);
  7041. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7042. EXPECT_EQ("Hello World!", res->body);
  7043. }
  7044. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7045. Request req;
  7046. req.method = "POST";
  7047. req.path = "/chunked";
  7048. std::string host_and_port;
  7049. host_and_port += HOST;
  7050. host_and_port += ":";
  7051. host_and_port += std::to_string(PORT);
  7052. req.headers.emplace("Host", host_and_port.c_str());
  7053. req.headers.emplace("Accept", "*/*");
  7054. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7055. req.headers.emplace("Content-Type", "text/plain");
  7056. req.headers.emplace("Content-Length", "0");
  7057. req.headers.emplace(
  7058. "Transfer-Encoding",
  7059. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7060. // Client does not chunk, so make a chunked body manually.
  7061. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7062. auto res = std::make_shared<Response>();
  7063. auto error = Error::Success;
  7064. auto ret = cli_.send(req, *res, error);
  7065. ASSERT_TRUE(ret);
  7066. EXPECT_EQ(StatusCode::OK_200, res->status);
  7067. }
  7068. template <typename ClientT>
  7069. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7070. int expected_status) {
  7071. Request req;
  7072. req.method = "POST";
  7073. req.path = "/chunked";
  7074. std::string host_and_port;
  7075. host_and_port += HOST;
  7076. host_and_port += ":";
  7077. host_and_port += std::to_string(PORT);
  7078. req.headers.emplace("Host", host_and_port.c_str());
  7079. req.headers.emplace("Content-Length", "0");
  7080. req.headers.emplace("Transfer-Encoding", "chunked");
  7081. req.body = body;
  7082. auto res = std::make_shared<Response>();
  7083. auto error = Error::Success;
  7084. ASSERT_TRUE(cli.send(req, *res, error));
  7085. EXPECT_EQ(expected_status, res->status);
  7086. }
  7087. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7088. // rather than treat them as valid lengths.
  7089. template <typename ClientT>
  7090. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7091. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7092. }
  7093. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7094. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7095. }
  7096. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7097. expect_chunked_body_rejected(
  7098. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7099. }
  7100. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7101. // chunk-size line carries no CR, LF or other control character ahead of its
  7102. // terminator. Such a line must be refused rather than read as extension text.
  7103. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7104. expect_chunked_body_rejected(
  7105. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7106. }
  7107. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7108. expect_chunked_body_rejected(
  7109. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7110. }
  7111. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7112. expect_chunked_body_rejected(
  7113. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7114. }
  7115. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7116. // The literal stays split: a hex escape consumes every hex digit that
  7117. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7118. expect_chunked_body_rejected(
  7119. cli_, "4;a\x01"
  7120. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7121. }
  7122. // The bytes around chunk data are no payload, so they cannot ride on the
  7123. // payload limit
  7124. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7125. // Small enough that the whole request is sent before the server turns it
  7126. // down, yet past the limit by the last chunks
  7127. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7128. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7129. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7130. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7131. SCOPED_TRACE(size_line.substr(0, 2));
  7132. std::string body;
  7133. for (auto c : std::string("dechunked post body")) {
  7134. body += size_line + "\r\n" + c + "\r\n";
  7135. }
  7136. body += "0\r\n\r\n";
  7137. expect_chunked_body_rejected(cli_, body.c_str());
  7138. }
  7139. }
  7140. TEST_F(ServerTest, AcceptsChunkExtension) {
  7141. expect_chunked_body_status(cli_,
  7142. "4;name=value\r\ndech\r\n"
  7143. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7144. "0;last\r\n\r\n",
  7145. StatusCode::OK_200);
  7146. }
  7147. TEST_F(ServerTest, GetStreamed2) {
  7148. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7151. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(true, res->has_header("Content-Range"));
  7153. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7154. EXPECT_EQ(std::string("ab"), res->body);
  7155. }
  7156. TEST_F(ServerTest, GetStreamed) {
  7157. auto res = cli_.Get("/streamed");
  7158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7159. EXPECT_EQ(StatusCode::OK_200, res->status);
  7160. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7161. EXPECT_EQ(std::string("aaabbb"), res->body);
  7162. }
  7163. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7164. auto res = cli_.Get("/streamed-without-length",
  7165. Headers{make_range_header({{0, -1}})});
  7166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7167. EXPECT_EQ(StatusCode::OK_200, res->status);
  7168. EXPECT_EQ(false, res->has_header("Content-Length"));
  7169. EXPECT_EQ(false, res->has_header("Content-Range"));
  7170. EXPECT_EQ(std::string("abcdefg"), res->body);
  7171. }
  7172. TEST_F(ServerTest, GetStreamedWithRange1) {
  7173. auto res =
  7174. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7177. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7178. EXPECT_EQ(true, res->has_header("Content-Range"));
  7179. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7180. EXPECT_EQ(std::string("def"), res->body);
  7181. }
  7182. TEST_F(ServerTest, GetStreamedWithRange2) {
  7183. auto res =
  7184. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7186. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7187. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7188. EXPECT_EQ(true, res->has_header("Content-Range"));
  7189. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7190. EXPECT_EQ(std::string("bcdefg"), res->body);
  7191. }
  7192. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7193. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7195. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7196. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7197. EXPECT_EQ(true, res->has_header("Content-Range"));
  7198. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7199. EXPECT_EQ(std::string("efg"), res->body);
  7200. }
  7201. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7202. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7203. // the entire representation.
  7204. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7205. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7207. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7208. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7209. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7210. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7211. }
  7212. }
  7213. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7214. auto res =
  7215. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7217. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7218. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7219. EXPECT_EQ(false, res->has_header("Content-Range"));
  7220. EXPECT_EQ(0U, res->body.size());
  7221. }
  7222. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7223. // Only a 206 is served as a partial representation. Under any other status
  7224. // `apply_ranges()` reported the full content length, so the body must match
  7225. // that header, and the content provider must never be asked for an offset
  7226. // outside the representation.
  7227. auto check = [&](int status, const char *range) {
  7228. auto path =
  7229. std::string("/streamed-with-range?status=") + std::to_string(status);
  7230. auto ctx = path + " Range: " + range;
  7231. auto res = cli_.Get(path, Headers{{"Range", range}});
  7232. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7233. EXPECT_EQ(status, res->status) << ctx;
  7234. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7235. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7236. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7237. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7238. };
  7239. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7240. check(403, "bytes=3-5");
  7241. // The offset is far past the representation.
  7242. check(403, "bytes=100000-100200");
  7243. // `first_pos` is still -1 here, and the bounds asserts in
  7244. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7245. check(403, "bytes=-3");
  7246. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7247. // multipart branch would have written one that is empty.
  7248. check(403, "bytes=1-2, 4-5");
  7249. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7250. // covers the whole representation.
  7251. check(200, "bytes=3-5");
  7252. check(200, "bytes=1-2, 4-5");
  7253. }
  7254. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7255. auto res =
  7256. cli_.Get("/streamed-with-range",
  7257. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7258. "92233720368547758079223372036854775807"}});
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7261. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7262. EXPECT_EQ(false, res->has_header("Content-Range"));
  7263. EXPECT_EQ(0U, res->body.size());
  7264. }
  7265. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7266. auto res = cli_.Get(
  7267. "/with-range",
  7268. Headers{{"Range",
  7269. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7270. {"Accept-Encoding", ""}});
  7271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7272. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7273. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7274. EXPECT_EQ(true, res->has_header("Content-Range"));
  7275. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7276. EXPECT_EQ(std::string("abcdefg"), res->body);
  7277. }
  7278. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7279. auto res = cli_.Get("/with-range", Headers{
  7280. {"Range", "bytes=0-"},
  7281. {"Accept-Encoding", ""},
  7282. });
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7285. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7286. EXPECT_EQ(true, res->has_header("Content-Range"));
  7287. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7288. EXPECT_EQ(std::string("abcdefg"), res->body);
  7289. }
  7290. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7291. auto res = cli_.Get("/streamed-with-range",
  7292. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7295. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7296. EXPECT_EQ(false, res->has_header("Content-Range"));
  7297. EXPECT_EQ(267U, res->body.size());
  7298. // Check that both range contents are present
  7299. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7300. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7301. // Check that Content-Range headers are present for both ranges
  7302. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7303. std::string::npos);
  7304. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7305. std::string::npos);
  7306. }
  7307. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7308. Ranges ranges;
  7309. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7310. ranges.emplace_back(0, -1);
  7311. }
  7312. auto res = cli_.Get("/streamed-with-range?error",
  7313. Headers{{make_range_header(ranges)}});
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7316. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7317. EXPECT_EQ(false, res->has_header("Content-Range"));
  7318. EXPECT_EQ(0U, res->body.size());
  7319. }
  7320. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7321. auto res = cli_.Get("/streamed-with-range",
  7322. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7325. EXPECT_EQ(5U, res->body.size());
  7326. // Check that overlapping ranges are coalesced into a single range
  7327. EXPECT_EQ("bcdef", res->body);
  7328. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7329. // Should be single range, not multipart
  7330. EXPECT_TRUE(res->has_header("Content-Range"));
  7331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7332. }
  7333. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7334. auto res = cli_.Get("/streamed-with-range",
  7335. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7337. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7338. EXPECT_EQ(268U, res->body.size());
  7339. // Check that both range contents are present
  7340. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7341. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7342. // Check that Content-Range headers are present for both ranges
  7343. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7344. std::string::npos);
  7345. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7346. std::string::npos);
  7347. }
  7348. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7349. auto res = cli_.Get("/streamed-with-range",
  7350. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7353. EXPECT_EQ(269U, res->body.size());
  7354. // Check that both duplicate range contents are present
  7355. size_t first_abc = res->body.find("abc\r\n");
  7356. EXPECT_TRUE(first_abc != std::string::npos);
  7357. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7358. EXPECT_TRUE(second_abc != std::string::npos);
  7359. // Check that Content-Range headers are present for both ranges
  7360. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7361. EXPECT_TRUE(first_range != std::string::npos);
  7362. size_t second_range =
  7363. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7364. EXPECT_TRUE(second_range != std::string::npos);
  7365. }
  7366. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7367. auto res =
  7368. cli_.Get("/streamed-with-range?error",
  7369. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7371. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7372. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7373. EXPECT_EQ(false, res->has_header("Content-Range"));
  7374. EXPECT_EQ(0U, res->body.size());
  7375. }
  7376. TEST_F(ServerTest, GetStreamedEndless) {
  7377. uint64_t offset = 0;
  7378. auto res = cli_.Get("/streamed-cancel",
  7379. [&](const char * /*data*/, uint64_t data_length) {
  7380. if (offset < 100) {
  7381. offset += data_length;
  7382. return true;
  7383. }
  7384. return false;
  7385. });
  7386. ASSERT_TRUE(!res);
  7387. EXPECT_EQ(Error::Canceled, res.error());
  7388. }
  7389. TEST_F(ServerTest, ClientStop) {
  7390. std::atomic_size_t count{4};
  7391. std::vector<std::thread> threads;
  7392. for (auto i = count.load(); i != 0; --i) {
  7393. threads.emplace_back([&]() {
  7394. auto res = cli_.Get("/streamed-cancel",
  7395. [&](const char *, uint64_t) { return true; });
  7396. --count;
  7397. ASSERT_TRUE(!res);
  7398. EXPECT_TRUE(res.error() == Error::Canceled ||
  7399. res.error() == Error::Read || res.error() == Error::Write);
  7400. });
  7401. }
  7402. std::this_thread::sleep_for(std::chrono::seconds(2));
  7403. while (count != 0) {
  7404. cli_.stop();
  7405. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7406. }
  7407. for (auto &t : threads) {
  7408. t.join();
  7409. }
  7410. }
  7411. TEST_F(ServerTest, GetWithRange1) {
  7412. auto res = cli_.Get("/with-range", Headers{
  7413. make_range_header({{3, 5}}),
  7414. {"Accept-Encoding", ""},
  7415. });
  7416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7417. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7418. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7419. EXPECT_EQ(true, res->has_header("Content-Range"));
  7420. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7421. EXPECT_EQ(std::string("def"), res->body);
  7422. }
  7423. TEST_F(ServerTest, GetWithRange2) {
  7424. auto res = cli_.Get("/with-range", Headers{
  7425. make_range_header({{1, -1}}),
  7426. {"Accept-Encoding", ""},
  7427. });
  7428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7429. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7430. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7431. EXPECT_EQ(true, res->has_header("Content-Range"));
  7432. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7433. EXPECT_EQ(std::string("bcdefg"), res->body);
  7434. }
  7435. TEST_F(ServerTest, GetWithRange3) {
  7436. auto res = cli_.Get("/with-range", Headers{
  7437. make_range_header({{0, 0}}),
  7438. {"Accept-Encoding", ""},
  7439. });
  7440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7441. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7442. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7443. EXPECT_EQ(true, res->has_header("Content-Range"));
  7444. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7445. EXPECT_EQ(std::string("a"), res->body);
  7446. }
  7447. TEST_F(ServerTest, GetWithRange4) {
  7448. auto res = cli_.Get("/with-range", Headers{
  7449. make_range_header({{-1, 2}}),
  7450. {"Accept-Encoding", ""},
  7451. });
  7452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7454. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7455. EXPECT_EQ(true, res->has_header("Content-Range"));
  7456. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7457. EXPECT_EQ(std::string("fg"), res->body);
  7458. }
  7459. TEST_F(ServerTest, GetWithRange5) {
  7460. auto res = cli_.Get("/with-range", Headers{
  7461. make_range_header({{0, 5}}),
  7462. {"Accept-Encoding", ""},
  7463. });
  7464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7465. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7466. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7467. EXPECT_EQ(true, res->has_header("Content-Range"));
  7468. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7469. EXPECT_EQ(std::string("abcdef"), res->body);
  7470. }
  7471. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7472. auto res =
  7473. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7476. }
  7477. TEST_F(ServerTest, GetWithRangeMultipart) {
  7478. auto res =
  7479. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7482. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7483. EXPECT_EQ(false, res->has_header("Content-Range"));
  7484. EXPECT_EQ(267U, res->body.size());
  7485. }
  7486. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7487. auto res = cli_.Get("/with-range",
  7488. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7491. }
  7492. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7493. auto res = cli_.Get("/with-range-customized-response",
  7494. Headers{{make_range_header({{1, 2}})}});
  7495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7496. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7497. EXPECT_EQ(true, res->has_header("Content-Length"));
  7498. EXPECT_EQ(false, res->has_header("Content-Range"));
  7499. EXPECT_EQ(JSON_DATA, res->body);
  7500. }
  7501. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7502. auto res = cli_.Get("/with-range-customized-response",
  7503. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7505. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7506. EXPECT_EQ(true, res->has_header("Content-Length"));
  7507. EXPECT_EQ(false, res->has_header("Content-Range"));
  7508. EXPECT_EQ(JSON_DATA, res->body);
  7509. }
  7510. TEST_F(ServerTest, Issue1772) {
  7511. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7514. }
  7515. TEST_F(ServerTest, Issue609) {
  7516. auto res = cli_.Delete("/issue609");
  7517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7518. EXPECT_EQ(StatusCode::OK_200, res->status);
  7519. EXPECT_EQ(std::string("ok"), res->body);
  7520. }
  7521. TEST_F(ServerTest, GetStreamedChunked) {
  7522. auto res = cli_.Get("/streamed-chunked");
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::OK_200, res->status);
  7525. EXPECT_EQ(std::string("123456789"), res->body);
  7526. }
  7527. TEST_F(ServerTest, GetStreamedChunked2) {
  7528. auto res = cli_.Get("/streamed-chunked2");
  7529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7530. EXPECT_EQ(StatusCode::OK_200, res->status);
  7531. EXPECT_EQ(std::string("123456789"), res->body);
  7532. }
  7533. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7534. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. EXPECT_EQ(std::string("123456789"), res->body);
  7538. EXPECT_TRUE(res->has_header("Trailer"));
  7539. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7540. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7541. // Trailers are now stored separately from headers (security fix)
  7542. EXPECT_EQ(2U, res->trailers.size());
  7543. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7544. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7545. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7546. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7547. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7548. // Verify trailers are NOT in headers (security verification)
  7549. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7550. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7551. }
  7552. TEST_F(ServerTest, LargeChunkedPost) {
  7553. Request req;
  7554. req.method = "POST";
  7555. req.path = "/large-chunked";
  7556. std::string host_and_port;
  7557. host_and_port += HOST;
  7558. host_and_port += ":";
  7559. host_and_port += std::to_string(PORT);
  7560. req.headers.emplace("Host", host_and_port.c_str());
  7561. req.headers.emplace("Accept", "*/*");
  7562. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7563. req.headers.emplace("Content-Type", "text/plain");
  7564. req.headers.emplace("Content-Length", "0");
  7565. req.headers.emplace("Transfer-Encoding", "chunked");
  7566. std::string long_string(30 * 1024u, 'a');
  7567. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7568. // Attempt to make a large enough post to exceed OS buffers, to test that
  7569. // the server handles short reads if the full chunk data isn't available.
  7570. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7571. auto res = std::make_shared<Response>();
  7572. auto error = Error::Success;
  7573. auto ret = cli_.send(req, *res, error);
  7574. ASSERT_TRUE(ret);
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. }
  7577. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7578. auto res = cli_.Get("/remote_addr");
  7579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7580. EXPECT_EQ(StatusCode::OK_200, res->status);
  7581. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7582. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7583. }
  7584. TEST_F(ServerTest, GetMethodLocalAddr) {
  7585. auto res = cli_.Get("/local_addr");
  7586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7587. EXPECT_EQ(StatusCode::OK_200, res->status);
  7588. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7589. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7590. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7591. }
  7592. TEST_F(ServerTest, HTTPResponseSplitting) {
  7593. auto res = cli_.Get("/http_response_splitting");
  7594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7595. EXPECT_EQ(StatusCode::OK_200, res->status);
  7596. }
  7597. TEST_F(ServerTest, SlowRequest) {
  7598. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7599. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7600. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7601. }
  7602. #if 0
  7603. TEST_F(ServerTest, SlowPost) {
  7604. char buffer[64 * 1024];
  7605. memset(buffer, 0x42, sizeof(buffer));
  7606. auto res = cli_.Post(
  7607. "/slowpost", 64 * 1024 * 1024,
  7608. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7609. auto ret = sink.write(buffer, sizeof(buffer));
  7610. EXPECT_TRUE(ret);
  7611. return true;
  7612. },
  7613. "text/plain");
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::OK_200, res->status);
  7616. }
  7617. TEST_F(ServerTest, SlowPostFail) {
  7618. char buffer[64 * 1024];
  7619. memset(buffer, 0x42, sizeof(buffer));
  7620. cli_.set_write_timeout(std::chrono::seconds(0));
  7621. auto res = cli_.Post(
  7622. "/slowpost", 64 * 1024 * 1024,
  7623. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7624. sink.write(buffer, sizeof(buffer));
  7625. return true;
  7626. },
  7627. "text/plain");
  7628. ASSERT_TRUE(!res);
  7629. EXPECT_EQ(Error::Write, res.error());
  7630. }
  7631. #endif
  7632. TEST_F(ServerTest, Put) {
  7633. auto res = cli_.Put("/put", "PUT", "text/plain");
  7634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. EXPECT_EQ("PUT", res->body);
  7637. }
  7638. TEST_F(ServerTest, PutWithContentProvider) {
  7639. auto res = cli_.Put(
  7640. "/put", 3,
  7641. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7642. sink.os << "PUT";
  7643. return true;
  7644. },
  7645. "text/plain");
  7646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7647. EXPECT_EQ(StatusCode::OK_200, res->status);
  7648. EXPECT_EQ("PUT", res->body);
  7649. }
  7650. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7651. auto res = cli_.Post(
  7652. "/post", 42,
  7653. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7654. return false;
  7655. },
  7656. "text/plain");
  7657. ASSERT_TRUE(!res);
  7658. EXPECT_EQ(Error::Canceled, res.error());
  7659. }
  7660. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7661. auto res = cli_.Put(
  7662. "/put",
  7663. [](size_t /*offset*/, DataSink &sink) {
  7664. sink.os << "PUT";
  7665. sink.done();
  7666. return true;
  7667. },
  7668. "text/plain");
  7669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7670. EXPECT_EQ(StatusCode::OK_200, res->status);
  7671. EXPECT_EQ("PUT", res->body);
  7672. }
  7673. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7674. auto res = cli_.Post(
  7675. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7676. "text/plain");
  7677. ASSERT_TRUE(!res);
  7678. EXPECT_EQ(Error::Canceled, res.error());
  7679. }
  7680. TEST_F(ServerTest, PostLoopBack) {
  7681. std::string body;
  7682. auto res = cli_.Post(
  7683. "/post-loopback", 9,
  7684. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7685. EXPECT_EQ(9u, length);
  7686. sink.write("123", 3);
  7687. sink.write("456", 3);
  7688. sink.write("789", 3);
  7689. return true;
  7690. },
  7691. "text/plain",
  7692. [&body](const char *data, size_t data_length) {
  7693. body.append(data, data_length);
  7694. return true;
  7695. });
  7696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7697. EXPECT_EQ(StatusCode::OK_200, res->status);
  7698. EXPECT_EQ("123456789", body);
  7699. }
  7700. TEST_F(ServerTest, PutLoopBack) {
  7701. std::string body;
  7702. auto res = cli_.Put(
  7703. "/put-loopback", 9,
  7704. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7705. EXPECT_EQ(9u, length);
  7706. sink.write("123", 3);
  7707. sink.write("456", 3);
  7708. sink.write("789", 3);
  7709. return true;
  7710. },
  7711. "text/plain",
  7712. [&body](const char *data, size_t data_length) {
  7713. body.append(data, data_length);
  7714. return true;
  7715. });
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. EXPECT_EQ(StatusCode::OK_200, res->status);
  7718. EXPECT_EQ("123456789", body);
  7719. }
  7720. TEST_F(ServerTest, PatchLoopBack) {
  7721. std::string body;
  7722. auto res = cli_.Patch(
  7723. "/patch-loopback", 9,
  7724. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7725. EXPECT_EQ(9u, length);
  7726. sink.write("123", 3);
  7727. sink.write("456", 3);
  7728. sink.write("789", 3);
  7729. return true;
  7730. },
  7731. "text/plain",
  7732. [&body](const char *data, size_t data_length) {
  7733. body.append(data, data_length);
  7734. return true;
  7735. });
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. EXPECT_EQ(StatusCode::OK_200, res->status);
  7738. EXPECT_EQ("123456789", body);
  7739. }
  7740. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7741. std::string body;
  7742. auto res = cli_.Post(
  7743. "/post-loopback",
  7744. [](size_t /*offset*/, DataSink &sink) {
  7745. sink.write("123", 3);
  7746. sink.write("456", 3);
  7747. sink.write("789", 3);
  7748. sink.done();
  7749. return true;
  7750. },
  7751. "text/plain",
  7752. [&body](const char *data, size_t data_length) {
  7753. body.append(data, data_length);
  7754. return true;
  7755. });
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::OK_200, res->status);
  7758. EXPECT_EQ("123456789", body);
  7759. }
  7760. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7761. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7762. cli_.set_compress(true);
  7763. auto res = cli_.Put(
  7764. "/put", 3,
  7765. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7766. sink.os << "PUT";
  7767. return true;
  7768. },
  7769. "text/plain");
  7770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7771. EXPECT_EQ(StatusCode::OK_200, res->status);
  7772. EXPECT_EQ("PUT", res->body);
  7773. }
  7774. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7775. cli_.set_compress(true);
  7776. auto res = cli_.Post(
  7777. "/post", 42,
  7778. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7779. return false;
  7780. },
  7781. "text/plain");
  7782. ASSERT_TRUE(!res);
  7783. EXPECT_EQ(Error::Canceled, res.error());
  7784. }
  7785. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7786. cli_.set_compress(true);
  7787. auto res = cli_.Put(
  7788. "/put",
  7789. [](size_t /*offset*/, DataSink &sink) {
  7790. sink.os << "PUT";
  7791. sink.done();
  7792. return true;
  7793. },
  7794. "text/plain");
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::OK_200, res->status);
  7797. EXPECT_EQ("PUT", res->body);
  7798. }
  7799. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7800. cli_.set_compress(true);
  7801. auto res = cli_.Post(
  7802. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7803. "text/plain");
  7804. ASSERT_TRUE(!res);
  7805. EXPECT_EQ(Error::Canceled, res.error());
  7806. }
  7807. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7808. cli_.set_compress(true);
  7809. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7811. EXPECT_EQ(StatusCode::OK_200, res->status);
  7812. EXPECT_EQ(LARGE_DATA, res->body);
  7813. }
  7814. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7815. #ifdef CPPHTTPLIB_SSL_ENABLED
  7816. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7817. Client cli(s.c_str());
  7818. cli.enable_server_certificate_verification(false);
  7819. #else
  7820. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7821. Client cli(s.c_str());
  7822. #endif
  7823. cli.set_compress(true);
  7824. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::OK_200, res->status);
  7827. EXPECT_EQ(LARGE_DATA, res->body);
  7828. // The compressed size should be less than a 10th of the original. May vary
  7829. // depending on the zlib library.
  7830. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7831. static_cast<uint64_t>(10 * 1024 * 1024));
  7832. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7833. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7834. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7835. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7836. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7837. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7838. #endif
  7839. }
  7840. TEST_F(ServerTest, PutContentWithDeflate) {
  7841. cli_.set_compress(false);
  7842. Headers headers;
  7843. headers.emplace("Content-Encoding", "deflate");
  7844. // PUT in deflate format:
  7845. auto res = cli_.Put("/put", headers,
  7846. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7848. EXPECT_EQ(StatusCode::OK_200, res->status);
  7849. EXPECT_EQ("PUT", res->body);
  7850. }
  7851. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7852. Headers headers;
  7853. headers.emplace("Accept-Encoding", "gzip, deflate");
  7854. auto res = cli_.Get("/streamed-chunked", headers);
  7855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7856. EXPECT_EQ(StatusCode::OK_200, res->status);
  7857. EXPECT_EQ(std::string("123456789"), res->body);
  7858. }
  7859. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7860. Headers headers;
  7861. headers.emplace("Accept-Encoding", "gzip, deflate");
  7862. auto res = cli_.Get("/streamed-chunked2", headers);
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::OK_200, res->status);
  7865. EXPECT_EQ(std::string("123456789"), res->body);
  7866. }
  7867. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7868. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7870. EXPECT_EQ(StatusCode::OK_200, res->status);
  7871. }
  7872. TEST(GzipDecompressor, ChunkedDecompression) {
  7873. std::string data;
  7874. for (size_t i = 0; i < 32 * 1024; ++i) {
  7875. data.push_back(static_cast<char>('a' + i % 26));
  7876. }
  7877. std::string compressed_data;
  7878. {
  7879. httplib::detail::gzip_compressor compressor;
  7880. bool result = compressor.compress(
  7881. data.data(), data.size(),
  7882. /*last=*/true,
  7883. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7884. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7885. compressed_data_size);
  7886. return true;
  7887. });
  7888. ASSERT_TRUE(result);
  7889. }
  7890. std::string decompressed_data;
  7891. {
  7892. httplib::detail::gzip_decompressor decompressor;
  7893. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7894. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7895. size_t chunk_size = 130;
  7896. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7897. chunk_begin += chunk_size) {
  7898. size_t current_chunk_size =
  7899. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7900. bool result = decompressor.decompress(
  7901. compressed_data.data() + chunk_begin, current_chunk_size,
  7902. [&](const char *decompressed_data_chunk,
  7903. size_t decompressed_data_chunk_size) {
  7904. decompressed_data.insert(decompressed_data.size(),
  7905. decompressed_data_chunk,
  7906. decompressed_data_chunk_size);
  7907. return true;
  7908. });
  7909. ASSERT_TRUE(result);
  7910. }
  7911. }
  7912. ASSERT_EQ(data, decompressed_data);
  7913. }
  7914. TEST(GzipDecompressor, DeflateDecompression) {
  7915. std::string original_text = "Raw deflate without gzip";
  7916. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7917. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7918. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7919. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7920. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7921. std::string decompressed_data;
  7922. {
  7923. httplib::detail::gzip_decompressor decompressor;
  7924. bool result = decompressor.decompress(
  7925. compressed_data.data(), compressed_data.size(),
  7926. [&](const char *decompressed_data_chunk,
  7927. size_t decompressed_data_chunk_size) {
  7928. decompressed_data.insert(decompressed_data.size(),
  7929. decompressed_data_chunk,
  7930. decompressed_data_chunk_size);
  7931. return true;
  7932. });
  7933. ASSERT_TRUE(result);
  7934. }
  7935. ASSERT_EQ(original_text, decompressed_data);
  7936. }
  7937. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7938. std::string original_text = "Raw deflate without gzip";
  7939. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7940. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7941. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7942. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7943. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7944. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7945. std::string decompressed_data;
  7946. {
  7947. httplib::detail::gzip_decompressor decompressor;
  7948. bool result = decompressor.decompress(
  7949. compressed_data.data(), compressed_data.size(),
  7950. [&](const char *decompressed_data_chunk,
  7951. size_t decompressed_data_chunk_size) {
  7952. decompressed_data.insert(decompressed_data.size(),
  7953. decompressed_data_chunk,
  7954. decompressed_data_chunk_size);
  7955. return true;
  7956. });
  7957. ASSERT_TRUE(result);
  7958. }
  7959. ASSERT_EQ(original_text, decompressed_data);
  7960. }
  7961. #endif
  7962. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7963. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7964. Headers headers;
  7965. headers.emplace("Accept-Encoding", "br");
  7966. auto res = cli_.Get("/streamed-chunked", headers);
  7967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7968. EXPECT_EQ(StatusCode::OK_200, res->status);
  7969. EXPECT_EQ(std::string("123456789"), res->body);
  7970. }
  7971. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7972. Headers headers;
  7973. headers.emplace("Accept-Encoding", "br");
  7974. auto res = cli_.Get("/streamed-chunked2", headers);
  7975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7976. EXPECT_EQ(StatusCode::OK_200, res->status);
  7977. EXPECT_EQ(std::string("123456789"), res->body);
  7978. }
  7979. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7980. cli_.set_compress(true);
  7981. auto res = cli_.Put(
  7982. "/put", 3,
  7983. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7984. sink.os << "PUT";
  7985. return true;
  7986. },
  7987. "text/plain");
  7988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7989. EXPECT_EQ(StatusCode::OK_200, res->status);
  7990. EXPECT_EQ("PUT", res->body);
  7991. }
  7992. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7993. cli_.set_compress(true);
  7994. auto res = cli_.Put(
  7995. "/put",
  7996. [](size_t /*offset*/, DataSink &sink) {
  7997. sink.os << "PUT";
  7998. sink.done();
  7999. return true;
  8000. },
  8001. "text/plain");
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. EXPECT_EQ("PUT", res->body);
  8005. }
  8006. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8007. cli_.set_compress(true);
  8008. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8010. EXPECT_EQ(StatusCode::OK_200, res->status);
  8011. EXPECT_EQ(LARGE_DATA, res->body);
  8012. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8013. }
  8014. #endif
  8015. TEST_F(ServerTest, Patch) {
  8016. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. EXPECT_EQ("PATCH", res->body);
  8020. }
  8021. TEST_F(ServerTest, Delete) {
  8022. auto res = cli_.Delete("/delete");
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(StatusCode::OK_200, res->status);
  8025. EXPECT_EQ("DELETE", res->body);
  8026. }
  8027. TEST_F(ServerTest, DeleteContentReceiver) {
  8028. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8030. EXPECT_EQ(StatusCode::OK_200, res->status);
  8031. EXPECT_EQ("content", res->body);
  8032. }
  8033. TEST_F(ServerTest, Options) {
  8034. auto res = cli_.Options("*");
  8035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8038. EXPECT_TRUE(res->body.empty());
  8039. }
  8040. TEST_F(ServerTest, URL) {
  8041. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8043. EXPECT_EQ(StatusCode::OK_200, res->status);
  8044. }
  8045. TEST_F(ServerTest, ArrayParam) {
  8046. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8048. EXPECT_EQ(StatusCode::OK_200, res->status);
  8049. }
  8050. TEST_F(ServerTest, ArrayParamValues) {
  8051. auto res =
  8052. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8054. EXPECT_EQ(StatusCode::OK_200, res->status);
  8055. }
  8056. TEST_F(ServerTest, NoMultipleHeaders) {
  8057. Headers headers = {{"Content-Length", "5"}};
  8058. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8059. "text/plain");
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. }
  8063. TEST_F(ServerTest, PostContentReceiver) {
  8064. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8066. ASSERT_EQ(StatusCode::OK_200, res->status);
  8067. ASSERT_EQ("content", res->body);
  8068. }
  8069. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8070. UploadFormDataItems items = {
  8071. {"text1", "text default", "", ""},
  8072. {"text2", "aωb", "", ""},
  8073. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8074. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8075. {"file3", "", "", "application/octet-stream"},
  8076. };
  8077. auto res = cli_.Post("/content_receiver", items);
  8078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8079. EXPECT_EQ(StatusCode::OK_200, res->status);
  8080. }
  8081. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8082. UploadFormDataItems items = {
  8083. {"text1", "text default", "", ""},
  8084. {"text2", "aωb", "", ""},
  8085. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8086. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8087. {"file3", "", "", "application/octet-stream"},
  8088. };
  8089. auto boundary = std::string("+++++");
  8090. std::string body;
  8091. for (const auto &item : items) {
  8092. body += "--" + boundary + "\r\n";
  8093. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8094. if (!item.filename.empty()) {
  8095. body += "; filename=\"" + item.filename + "\"";
  8096. }
  8097. body += "\r\n";
  8098. if (!item.content_type.empty()) {
  8099. body += "Content-Type: " + item.content_type + "\r\n";
  8100. }
  8101. body += "\r\n";
  8102. body += item.content + "\r\n";
  8103. }
  8104. body += "--" + boundary + "--\r\n";
  8105. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8106. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. }
  8110. TEST(MultipartFormDataTest, FieldEscaping) {
  8111. Server svr;
  8112. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8113. const ContentReader &content_reader) {
  8114. ASSERT_TRUE(req.is_multipart_form_data());
  8115. std::vector<FormData> received;
  8116. content_reader(
  8117. [&](const FormData &file) {
  8118. received.push_back(file);
  8119. return true;
  8120. },
  8121. [&](const char *data, size_t data_length) {
  8122. received.back().content.append(data, data_length);
  8123. return true;
  8124. });
  8125. // '"', CR and LF in names and filenames are escaped following the
  8126. // WHATWG HTML standard, so each part still parses as a single part
  8127. // with no injected headers. Content types get CR/LF escaped too,
  8128. // while '"' (legal there, e.g. quoted charset) is preserved.
  8129. ASSERT_EQ(4U, received.size());
  8130. EXPECT_EQ("na%22me", received[0].name);
  8131. EXPECT_EQ("quoted name", received[0].content);
  8132. EXPECT_EQ("file", received[1].name);
  8133. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8134. received[1].filename);
  8135. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8136. EXPECT_EQ("injected", received[1].content);
  8137. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8138. EXPECT_EQ("my%22file.txt", received[2].filename);
  8139. EXPECT_EQ("cr lf name", received[2].content);
  8140. EXPECT_EQ("typed", received[3].name);
  8141. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8142. received[3].content_type);
  8143. EXPECT_EQ("typed content", received[3].content);
  8144. });
  8145. auto port = svr.bind_to_any_port("localhost");
  8146. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8147. auto se = detail::scope_exit([&] {
  8148. svr.stop();
  8149. t.join();
  8150. ASSERT_FALSE(svr.is_running());
  8151. });
  8152. svr.wait_until_ready();
  8153. Client cli("localhost", port);
  8154. UploadFormDataItems items = {
  8155. {"na\"me", "quoted name", "", ""},
  8156. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8157. "application/octet-stream"},
  8158. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8159. {"typed", "typed content", "",
  8160. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8161. };
  8162. auto res = cli.Post("/post", items);
  8163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8164. EXPECT_EQ(StatusCode::OK_200, res->status);
  8165. }
  8166. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8167. const UploadFormDataItems items = {
  8168. {"name1", "Content 1", "", ""},
  8169. {"name2", "Content 2", "file2.txt", "text/plain"},
  8170. };
  8171. Server svr;
  8172. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8173. const ContentReader &content_reader) {
  8174. ASSERT_TRUE(req.is_multipart_form_data());
  8175. std::vector<FormData> received;
  8176. content_reader(
  8177. [&](const FormData &file) {
  8178. received.push_back(file);
  8179. return true;
  8180. },
  8181. [&](const char *data, size_t data_length) {
  8182. received.back().content.append(data, data_length);
  8183. return true;
  8184. });
  8185. ASSERT_EQ(2U, received.size());
  8186. EXPECT_EQ("name1", received[0].name);
  8187. EXPECT_EQ("Content 1", received[0].content);
  8188. EXPECT_EQ("name2", received[1].name);
  8189. EXPECT_EQ("Content 2", received[1].content);
  8190. EXPECT_EQ("file2.txt", received[1].filename);
  8191. EXPECT_EQ("text/plain", received[1].content_type);
  8192. });
  8193. auto port = svr.bind_to_any_port("localhost");
  8194. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8195. auto se = detail::scope_exit([&] {
  8196. svr.stop();
  8197. t.join();
  8198. ASSERT_FALSE(svr.is_running());
  8199. });
  8200. svr.wait_until_ready();
  8201. Client cli("localhost", port);
  8202. // Whole-body serialization with a generated boundary
  8203. {
  8204. MultipartFormDataWriter writer;
  8205. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8206. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8207. writer.content_type());
  8208. auto body = writer.serialize(items);
  8209. EXPECT_EQ(body.size(), writer.content_length(items));
  8210. auto res = cli.Post("/post", body, writer.content_type());
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. }
  8214. // Per-part framing with a custom boundary via a content provider
  8215. {
  8216. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8217. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8218. MultipartFormDataWriter writer("custom-boundary_123");
  8219. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8220. std::string body;
  8221. for (const auto &item : items) {
  8222. body += writer.item_begin(item);
  8223. body += item.content;
  8224. body += MultipartFormDataWriter::item_end();
  8225. }
  8226. body += writer.finish();
  8227. EXPECT_EQ(body.size(), writer.content_length(items));
  8228. auto res = cli.Post(
  8229. "/post", body.size(),
  8230. [&](size_t offset, size_t length, DataSink &sink) {
  8231. sink.write(body.data() + offset, length);
  8232. return true;
  8233. },
  8234. writer.content_type());
  8235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8236. EXPECT_EQ(StatusCode::OK_200, res->status);
  8237. }
  8238. }
  8239. TEST_F(ServerTest, PostContentReceiverGzip) {
  8240. cli_.set_compress(true);
  8241. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8243. ASSERT_EQ(StatusCode::OK_200, res->status);
  8244. ASSERT_EQ("content", res->body);
  8245. }
  8246. TEST_F(ServerTest, PutContentReceiver) {
  8247. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. ASSERT_EQ(StatusCode::OK_200, res->status);
  8250. ASSERT_EQ("content", res->body);
  8251. }
  8252. TEST_F(ServerTest, PatchContentReceiver) {
  8253. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8255. ASSERT_EQ(StatusCode::OK_200, res->status);
  8256. ASSERT_EQ("content", res->body);
  8257. }
  8258. template <typename ClientType>
  8259. void TestWithHeadersAndContentReceiver(
  8260. ClientType &cli,
  8261. std::function<Result(ClientType &, const std::string &, const Headers &,
  8262. const std::string &, const std::string &,
  8263. ContentReceiver, DownloadProgress)>
  8264. request_func) {
  8265. Headers headers;
  8266. headers.emplace("X-Custom-Header", "test-value");
  8267. std::string received_body;
  8268. auto res = request_func(
  8269. cli, "/content_receiver", headers, "content", "application/json",
  8270. [&](const char *data, size_t data_length) {
  8271. received_body.append(data, data_length);
  8272. return true;
  8273. },
  8274. nullptr);
  8275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8276. EXPECT_EQ(StatusCode::OK_200, res->status);
  8277. EXPECT_EQ("content", received_body);
  8278. }
  8279. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8280. #ifdef CPPHTTPLIB_SSL_ENABLED
  8281. using ClientT = SSLClient;
  8282. #else
  8283. using ClientT = Client;
  8284. #endif
  8285. TestWithHeadersAndContentReceiver<ClientT>(
  8286. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8287. const std::string &body, const std::string &content_type,
  8288. ContentReceiver receiver, DownloadProgress progress) {
  8289. return cli.Post(path, headers, body, content_type, receiver, progress);
  8290. });
  8291. }
  8292. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8293. #ifdef CPPHTTPLIB_SSL_ENABLED
  8294. using ClientT = SSLClient;
  8295. #else
  8296. using ClientT = Client;
  8297. #endif
  8298. TestWithHeadersAndContentReceiver<ClientT>(
  8299. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8300. const std::string &body, const std::string &content_type,
  8301. ContentReceiver receiver, DownloadProgress progress) {
  8302. return cli.Put(path, headers, body, content_type, receiver, progress);
  8303. });
  8304. }
  8305. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8306. #ifdef CPPHTTPLIB_SSL_ENABLED
  8307. using ClientT = SSLClient;
  8308. #else
  8309. using ClientT = Client;
  8310. #endif
  8311. TestWithHeadersAndContentReceiver<ClientT>(
  8312. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8313. const std::string &body, const std::string &content_type,
  8314. ContentReceiver receiver, DownloadProgress progress) {
  8315. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8316. });
  8317. }
  8318. template <typename ClientType>
  8319. void TestWithHeadersAndContentReceiverWithProgress(
  8320. ClientType &cli,
  8321. std::function<Result(ClientType &, const std::string &, const Headers &,
  8322. const std::string &, const std::string &,
  8323. ContentReceiver, DownloadProgress)>
  8324. request_func) {
  8325. Headers headers;
  8326. headers.emplace("X-Test-Header", "progress-test");
  8327. std::string received_body;
  8328. auto progress_called = false;
  8329. auto res = request_func(
  8330. cli, "/content_receiver", headers, "content", "text/plain",
  8331. [&](const char *data, size_t data_length) {
  8332. received_body.append(data, data_length);
  8333. return true;
  8334. },
  8335. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8336. progress_called = true;
  8337. return true;
  8338. });
  8339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. EXPECT_EQ("content", received_body);
  8342. EXPECT_TRUE(progress_called);
  8343. }
  8344. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8345. #ifdef CPPHTTPLIB_SSL_ENABLED
  8346. using ClientT = SSLClient;
  8347. #else
  8348. using ClientT = Client;
  8349. #endif
  8350. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8351. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8352. const std::string &body, const std::string &content_type,
  8353. ContentReceiver receiver, DownloadProgress progress) {
  8354. return cli.Post(path, headers, body, content_type, receiver, progress);
  8355. });
  8356. }
  8357. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8358. #ifdef CPPHTTPLIB_SSL_ENABLED
  8359. using ClientT = SSLClient;
  8360. #else
  8361. using ClientT = Client;
  8362. #endif
  8363. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8364. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8365. const std::string &body, const std::string &content_type,
  8366. ContentReceiver receiver, DownloadProgress progress) {
  8367. return cli.Put(path, headers, body, content_type, receiver, progress);
  8368. });
  8369. }
  8370. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8371. #ifdef CPPHTTPLIB_SSL_ENABLED
  8372. using ClientT = SSLClient;
  8373. #else
  8374. using ClientT = Client;
  8375. #endif
  8376. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8377. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8378. const std::string &body, const std::string &content_type,
  8379. ContentReceiver receiver, DownloadProgress progress) {
  8380. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8381. });
  8382. }
  8383. template <typename ClientType>
  8384. void TestWithHeadersAndContentReceiverError(
  8385. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8386. const Headers &, const std::string &,
  8387. const std::string &, ContentReceiver)>
  8388. request_func) {
  8389. Headers headers;
  8390. headers.emplace("X-Error-Test", "true");
  8391. std::string received_body;
  8392. auto receiver_failed = false;
  8393. auto res =
  8394. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8395. [&](const char *data, size_t data_length) {
  8396. received_body.append(data, data_length);
  8397. receiver_failed = true;
  8398. return false;
  8399. });
  8400. ASSERT_FALSE(res);
  8401. EXPECT_TRUE(receiver_failed);
  8402. }
  8403. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8404. #ifdef CPPHTTPLIB_SSL_ENABLED
  8405. using ClientT = SSLClient;
  8406. #else
  8407. using ClientT = Client;
  8408. #endif
  8409. TestWithHeadersAndContentReceiverError<ClientT>(
  8410. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8411. const std::string &body, const std::string &content_type,
  8412. ContentReceiver receiver) {
  8413. return cli.Post(path, headers, body, content_type, receiver);
  8414. });
  8415. }
  8416. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8417. #ifdef CPPHTTPLIB_SSL_ENABLED
  8418. using ClientT = SSLClient;
  8419. #else
  8420. using ClientT = Client;
  8421. #endif
  8422. TestWithHeadersAndContentReceiverError<ClientT>(
  8423. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8424. const std::string &body, const std::string &content_type,
  8425. ContentReceiver receiver) {
  8426. return cli.Put(path, headers, body, content_type, receiver);
  8427. });
  8428. }
  8429. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8430. #ifdef CPPHTTPLIB_SSL_ENABLED
  8431. using ClientT = SSLClient;
  8432. #else
  8433. using ClientT = Client;
  8434. #endif
  8435. TestWithHeadersAndContentReceiverError<ClientT>(
  8436. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8437. const std::string &body, const std::string &content_type,
  8438. ContentReceiver receiver) {
  8439. return cli.Patch(path, headers, body, content_type, receiver);
  8440. });
  8441. }
  8442. TEST_F(ServerTest, PostQueryStringAndBody) {
  8443. auto res =
  8444. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8446. ASSERT_EQ(StatusCode::OK_200, res->status);
  8447. }
  8448. TEST_F(ServerTest, HTTP2Magic) {
  8449. Request req;
  8450. req.method = "PRI";
  8451. req.path = "*";
  8452. req.body = "SM";
  8453. auto res = std::make_shared<Response>();
  8454. auto error = Error::Success;
  8455. auto ret = cli_.send(req, *res, error);
  8456. ASSERT_TRUE(ret);
  8457. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8458. }
  8459. TEST_F(ServerTest, KeepAlive) {
  8460. auto res = cli_.Get("/hi");
  8461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8462. EXPECT_EQ(StatusCode::OK_200, res->status);
  8463. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8464. EXPECT_EQ("Hello World!", res->body);
  8465. res = cli_.Get("/hi");
  8466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8467. EXPECT_EQ(StatusCode::OK_200, res->status);
  8468. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8469. EXPECT_EQ("Hello World!", res->body);
  8470. res = cli_.Get("/hi");
  8471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8472. EXPECT_EQ(StatusCode::OK_200, res->status);
  8473. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8474. EXPECT_EQ("Hello World!", res->body);
  8475. res = cli_.Get("/not-exist");
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8478. res = cli_.Post("/empty", "", "text/plain");
  8479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8480. EXPECT_EQ(StatusCode::OK_200, res->status);
  8481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8482. EXPECT_EQ("empty", res->body);
  8483. EXPECT_EQ("close", res->get_header_value("Connection"));
  8484. res = cli_.Post(
  8485. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8486. "text/plain");
  8487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8488. EXPECT_EQ(StatusCode::OK_200, res->status);
  8489. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8490. EXPECT_EQ("empty", res->body);
  8491. cli_.set_keep_alive(false);
  8492. res = cli_.Get("/last-request");
  8493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8494. EXPECT_EQ(StatusCode::OK_200, res->status);
  8495. EXPECT_EQ("close", res->get_header_value("Connection"));
  8496. }
  8497. TEST_F(ServerTest, TooManyRedirect) {
  8498. cli_.set_follow_location(true);
  8499. auto res = cli_.Get("/redirect/0");
  8500. ASSERT_TRUE(!res);
  8501. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8502. }
  8503. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8504. Request req;
  8505. req.method = "FOOBAR";
  8506. req.path = "/hi";
  8507. cli_.set_keep_alive(true);
  8508. auto res = cli_.send(req);
  8509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8510. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8511. EXPECT_EQ("close", res->get_header_value("Connection"));
  8512. EXPECT_FALSE(cli_.is_socket_open());
  8513. }
  8514. TEST_F(ServerTest, CustomRouteReadsBody) {
  8515. const std::string xml =
  8516. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8517. Request req;
  8518. req.method = "PROPFIND";
  8519. req.path = "/dav/dir";
  8520. req.set_header("Depth", "1");
  8521. req.body = xml;
  8522. auto res = cli_.send(req);
  8523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8524. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8525. EXPECT_EQ(xml, res->body);
  8526. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8527. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8528. }
  8529. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8530. Request req;
  8531. req.method = "PROPFIND";
  8532. req.path = "/dav/42";
  8533. auto res = cli_.send(req);
  8534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8535. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8536. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8537. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8538. }
  8539. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8540. Request req;
  8541. req.method = "PROPFIND";
  8542. req.path = "/dav-re/123";
  8543. auto res = cli_.send(req);
  8544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8545. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8546. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8547. }
  8548. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8549. Request req;
  8550. req.method = "MKCOL";
  8551. req.path = "/dav-mkcol";
  8552. auto res = cli_.send(req);
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ(StatusCode::Created_201, res->status);
  8555. }
  8556. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8557. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8558. Request req;
  8559. req.method = "REPORT";
  8560. req.path = "/dav-report";
  8561. req.body = xml;
  8562. auto res = cli_.send(req);
  8563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8564. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8565. EXPECT_EQ(xml, res->body);
  8566. }
  8567. // A content reader route must fire even when the request carries no body,
  8568. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8569. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8570. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8571. Request req;
  8572. req.method = "REPORT";
  8573. req.path = "/dav-report";
  8574. auto res = cli_.send(req);
  8575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8576. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8577. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8578. }
  8579. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8580. Request req;
  8581. req.method = "PROPFIND";
  8582. req.path = "/not-dav";
  8583. auto res = cli_.send(req);
  8584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8585. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8586. }
  8587. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8588. Request req;
  8589. req.method = "UNLOCK";
  8590. req.path = "/dav/dir";
  8591. cli_.set_keep_alive(true);
  8592. auto res = cli_.send(req);
  8593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8594. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8595. EXPECT_EQ("close", res->get_header_value("Connection"));
  8596. EXPECT_FALSE(cli_.is_socket_open());
  8597. }
  8598. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8599. // The mount point serves this path, but only for GET and HEAD.
  8600. auto get_res = cli_.Get("/dir/index.html");
  8601. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8602. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8603. Request req;
  8604. req.method = "PROPFIND";
  8605. req.path = "/dir/index.html";
  8606. auto res = cli_.send(req);
  8607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8608. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8609. }
  8610. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8611. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8612. cli_.set_keep_alive(true);
  8613. for (auto i = 0; i < 2; i++) {
  8614. Request req;
  8615. req.method = "PROPFIND";
  8616. req.path = "/dav/dir";
  8617. req.body = xml;
  8618. auto res = cli_.send(req);
  8619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8620. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8621. EXPECT_EQ(xml, res->body);
  8622. EXPECT_TRUE(cli_.is_socket_open());
  8623. }
  8624. // A built-in method must still be served on the same connection.
  8625. cli_.set_keep_alive(false);
  8626. auto res = cli_.Get("/hi");
  8627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8628. EXPECT_EQ(StatusCode::OK_200, res->status);
  8629. EXPECT_EQ("close", res->get_header_value("Connection"));
  8630. }
  8631. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8632. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8633. Request req;
  8634. req.method = "PROPFIND";
  8635. req.path = "/dav/dir";
  8636. req.set_header("Expect", "100-continue");
  8637. req.body = xml;
  8638. auto res = cli_.send(req);
  8639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8640. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8641. EXPECT_EQ(xml, res->body);
  8642. }
  8643. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8644. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8645. TEST_F(ServerTest, Gzip) {
  8646. Headers headers;
  8647. headers.emplace("Accept-Encoding", "gzip, deflate");
  8648. auto res = cli_.Get("/compress", headers);
  8649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8650. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8651. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8652. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8653. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8654. "7890123456789012345678901234567890",
  8655. res->body);
  8656. EXPECT_EQ(StatusCode::OK_200, res->status);
  8657. }
  8658. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8659. Headers headers;
  8660. headers.emplace("Accept-Encoding", "gzip, deflate");
  8661. auto res = cli_.Get("/compress-with-charset", headers);
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8664. EXPECT_EQ("application/json; charset=utf-8",
  8665. res->get_header_value("Content-Type"));
  8666. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8667. "7890123456789012345678901234567890",
  8668. res->body);
  8669. EXPECT_EQ(StatusCode::OK_200, res->status);
  8670. }
  8671. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8672. Headers headers;
  8673. headers.emplace("Accept-Encoding", "");
  8674. auto res = cli_.Get("/compress", headers);
  8675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8676. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8677. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8678. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8679. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8680. "7890123456789012345678901234567890",
  8681. res->body);
  8682. EXPECT_EQ(StatusCode::OK_200, res->status);
  8683. }
  8684. TEST_F(ServerTest, GzipWithContentReceiver) {
  8685. Headers headers;
  8686. headers.emplace("Accept-Encoding", "gzip, deflate");
  8687. std::string body;
  8688. auto res =
  8689. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8690. EXPECT_EQ(100U, data_length);
  8691. body.append(data, data_length);
  8692. return true;
  8693. });
  8694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8695. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8696. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8697. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8698. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8699. "7890123456789012345678901234567890",
  8700. body);
  8701. EXPECT_EQ(StatusCode::OK_200, res->status);
  8702. }
  8703. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8704. Headers headers;
  8705. headers.emplace("Accept-Encoding", "gzip, deflate");
  8706. cli_.set_decompress(false);
  8707. auto res = cli_.Get("/compress", headers);
  8708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8709. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8711. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8712. EXPECT_EQ(33U, res->body.size());
  8713. EXPECT_EQ(StatusCode::OK_200, res->status);
  8714. }
  8715. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8716. Headers headers;
  8717. headers.emplace("Accept-Encoding", "");
  8718. std::string body;
  8719. auto res =
  8720. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8721. EXPECT_EQ(100U, data_length);
  8722. body.append(data, data_length);
  8723. return true;
  8724. });
  8725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8726. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8727. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8728. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8729. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8730. "7890123456789012345678901234567890",
  8731. body);
  8732. EXPECT_EQ(StatusCode::OK_200, res->status);
  8733. }
  8734. TEST_F(ServerTest, NoGzip) {
  8735. Headers headers;
  8736. headers.emplace("Accept-Encoding", "gzip, deflate");
  8737. auto res = cli_.Get("/nocompress", headers);
  8738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8739. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8740. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8741. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8742. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8743. "7890123456789012345678901234567890",
  8744. res->body);
  8745. EXPECT_EQ(StatusCode::OK_200, res->status);
  8746. }
  8747. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8748. Headers headers;
  8749. headers.emplace("Accept-Encoding", "gzip, deflate");
  8750. std::string body;
  8751. auto res = cli_.Get("/nocompress", headers,
  8752. [&](const char *data, size_t data_length) {
  8753. EXPECT_EQ(100U, data_length);
  8754. body.append(data, data_length);
  8755. return true;
  8756. });
  8757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8758. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8759. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8760. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8761. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8762. "7890123456789012345678901234567890",
  8763. body);
  8764. EXPECT_EQ(StatusCode::OK_200, res->status);
  8765. }
  8766. TEST_F(ServerTest, MultipartFormDataGzip) {
  8767. UploadFormDataItems items = {
  8768. {"key1", "test", "", ""},
  8769. {"key2", "--abcdefg123", "", ""},
  8770. };
  8771. cli_.set_compress(true);
  8772. auto res = cli_.Post("/compress-multipart", items);
  8773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8774. EXPECT_EQ(StatusCode::OK_200, res->status);
  8775. }
  8776. #endif
  8777. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8778. // Static file compression is opt-in, so these run their own server rather than
  8779. // flipping it on for the shared ServerTest fixture, which would silently
  8780. // rewrite what every other static file test is asserting.
  8781. class StaticFileCompressionTest : public ::testing::Test {
  8782. protected:
  8783. void TearDown() override {
  8784. if (t_.joinable()) {
  8785. svr_.stop();
  8786. t_.join();
  8787. }
  8788. }
  8789. int start(const std::function<void(Server &)> &configure = nullptr) {
  8790. // Serves the same tree as a directory of build-time compressed assets
  8791. // would be served: the mount point names the coding the files are already
  8792. // stored in. Registered before "/" so it is the one that matches.
  8793. svr_.set_mount_point("/pre-encoded", "./www",
  8794. {{"Content-Encoding", "gzip"}});
  8795. svr_.set_mount_point("/", "./www");
  8796. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8797. res.set_file_content("./www/dir/index.html", "text/html");
  8798. });
  8799. svr_.Get("/pre-encoded-file-content",
  8800. [](const Request & /*req*/, Response &res) {
  8801. res.set_header("Content-Encoding", "gzip");
  8802. res.set_file_content("./www/dir/index.html", "text/html");
  8803. });
  8804. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8805. res.set_content_provider(
  8806. 6, "text/plain",
  8807. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8808. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8809. return true;
  8810. });
  8811. });
  8812. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8813. res.set_content_provider(
  8814. 1000, "text/plain",
  8815. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8816. if (offset < 100) {
  8817. std::string data(100, 'A');
  8818. sink.write(data.data(), data.size());
  8819. return true;
  8820. }
  8821. std::this_thread::sleep_for(std::chrono::seconds(2));
  8822. std::string data(900, 'B');
  8823. sink.write(data.data(), data.size());
  8824. return true;
  8825. });
  8826. });
  8827. if (configure) { configure(svr_); }
  8828. auto port = svr_.bind_to_any_port(HOST);
  8829. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8830. svr_.wait_until_ready();
  8831. return port;
  8832. }
  8833. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8834. // Every file under ./www except 1MB.txt is smaller than the default
  8835. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8836. // it out of the way.
  8837. static void enable_without_floor(Server &svr) {
  8838. svr.set_static_file_compression(true);
  8839. svr.set_static_file_compression_min_length(0);
  8840. }
  8841. Server svr_;
  8842. std::thread t_;
  8843. };
  8844. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8845. auto port = start();
  8846. Client cli(HOST, port);
  8847. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8851. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8852. EXPECT_EQ(1048576U, res->body.size());
  8853. }
  8854. TEST_F(StaticFileCompressionTest, MountPoint) {
  8855. auto port = start(enable);
  8856. Client cli(HOST, port);
  8857. cli.set_decompress(false);
  8858. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8860. EXPECT_EQ(StatusCode::OK_200, res->status);
  8861. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8862. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8863. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8864. // The response stays self-delimiting: a length, not a chunked body.
  8865. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8866. EXPECT_EQ(std::to_string(res->body.size()),
  8867. res->get_header_value("Content-Length"));
  8868. EXPECT_LT(res->body.size(), 1048576U);
  8869. EXPECT_FALSE(res->body.empty());
  8870. }
  8871. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8872. auto port = start(enable);
  8873. Client cli(HOST, port);
  8874. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ(StatusCode::OK_200, res->status);
  8877. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8878. EXPECT_EQ(1048576U, res->body.size());
  8879. }
  8880. TEST_F(StaticFileCompressionTest, FileContent) {
  8881. auto port = start(enable_without_floor);
  8882. Client cli(HOST, port);
  8883. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8885. EXPECT_EQ(StatusCode::OK_200, res->status);
  8886. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8887. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8888. EXPECT_EQ(104U, res->body.size());
  8889. }
  8890. // A handler that serves an already-encoded file names the coding itself. The
  8891. // file-backed path decided its coding from Accept-Encoding and the content
  8892. // type alone, so it compressed the stored bytes a second time and appended a
  8893. // second Content-Encoding field line.
  8894. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8895. auto port = start(enable_without_floor);
  8896. Client cli(HOST, port);
  8897. cli.set_decompress(false);
  8898. auto res = cli.Get("/pre-encoded-file-content",
  8899. Headers{{"Accept-Encoding", "gzip"}});
  8900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8903. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8904. // Vary belongs to a coding the server chose, and it chose none here.
  8905. EXPECT_FALSE(res->has_header("Vary"));
  8906. // The file travels exactly as it is stored on disk.
  8907. EXPECT_EQ(104U, res->body.size());
  8908. }
  8909. // The 1MB file clears the default floor, so this one runs the configuration a
  8910. // deployment would actually have.
  8911. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8912. auto port = start(enable);
  8913. Client cli(HOST, port);
  8914. cli.set_decompress(false);
  8915. auto res =
  8916. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8918. EXPECT_EQ(StatusCode::OK_200, res->status);
  8919. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8920. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8921. EXPECT_FALSE(res->has_header("Vary"));
  8922. EXPECT_EQ(1048576U, res->body.size());
  8923. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8924. }
  8925. TEST_F(StaticFileCompressionTest, Head) {
  8926. auto port = start(enable);
  8927. Client cli(HOST, port);
  8928. cli.set_decompress(false);
  8929. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8930. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8931. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8933. EXPECT_EQ(StatusCode::OK_200, res->status);
  8934. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8935. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8936. // HEAD still reports the size a GET would return.
  8937. EXPECT_EQ(get->get_header_value("Content-Length"),
  8938. res->get_header_value("Content-Length"));
  8939. EXPECT_TRUE(res->body.empty());
  8940. }
  8941. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8942. auto port = start(enable);
  8943. Client cli(HOST, port);
  8944. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8945. {"Accept-Encoding", "gzip"}});
  8946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8948. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8949. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8950. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8951. EXPECT_EQ("cd", res->body);
  8952. }
  8953. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8954. auto port = start(enable);
  8955. Client cli(HOST, port);
  8956. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::OK_200, res->status);
  8959. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8960. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8961. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8962. }
  8963. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8964. auto port = start(enable);
  8965. Client cli(HOST, port);
  8966. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8968. EXPECT_EQ(StatusCode::OK_200, res->status);
  8969. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8970. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8971. EXPECT_TRUE(res->body.empty());
  8972. }
  8973. TEST_F(StaticFileCompressionTest, MinLength) {
  8974. auto port = start(enable);
  8975. Client cli(HOST, port);
  8976. // 104 bytes, well under the default floor. Compressing it would add the
  8977. // gzip header and trailer to a body that already fits in one packet.
  8978. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8980. EXPECT_EQ(StatusCode::OK_200, res->status);
  8981. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8982. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8983. }
  8984. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8985. auto port = start([](Server &svr) {
  8986. svr.set_static_file_compression(true);
  8987. svr.set_static_file_compression_min_length(1);
  8988. });
  8989. Client cli(HOST, port);
  8990. cli.set_decompress(false);
  8991. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8993. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8994. // A 9-byte file comes back larger than it went in, because gzip's header and
  8995. // trailer outweigh anything deflate can save. That is the end of the range
  8996. // the floor exists to keep out.
  8997. EXPECT_GT(res->body.size(), 9U);
  8998. }
  8999. TEST_F(StaticFileCompressionTest, MaxLength) {
  9000. auto port = start([](Server &svr) {
  9001. svr.set_static_file_compression(true);
  9002. svr.set_static_file_compression_min_length(0);
  9003. svr.set_static_file_compression_max_length(1024);
  9004. });
  9005. Client cli(HOST, port);
  9006. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9007. // defines `small` as a macro on Windows.
  9008. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9009. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9010. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9011. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9012. // Under it: compressed.
  9013. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9014. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9015. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9016. }
  9017. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9018. auto port = start(enable_without_floor);
  9019. Client cli(HOST, port);
  9020. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9021. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9022. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9023. auto identity_etag = identity->get_header_value("ETag");
  9024. ASSERT_FALSE(identity_etag.empty());
  9025. auto gzipped =
  9026. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9027. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9028. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9029. auto gzip_etag = gzipped->get_header_value("ETag");
  9030. ASSERT_FALSE(gzip_etag.empty());
  9031. // Two representations, two validators.
  9032. EXPECT_NE(identity_etag, gzip_etag);
  9033. // Each one revalidates against the request that would produce it...
  9034. auto fresh =
  9035. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9036. {"If-None-Match", gzip_etag}});
  9037. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9038. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9039. auto fresh_identity =
  9040. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9041. {"If-None-Match", identity_etag}});
  9042. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9043. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9044. // ...and not against the other representation.
  9045. auto crossed =
  9046. cli.Get("/dir/index.html",
  9047. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9048. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9049. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9050. }
  9051. // The opt-in covers responses the server reads off disk itself. A caller's own
  9052. // known-length provider keeps its Content-Length and, more importantly, keeps
  9053. // delivering incrementally: routing it through a compressor would hold every
  9054. // write back until zlib's window filled.
  9055. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9056. auto port = start(enable);
  9057. Client cli(HOST, port);
  9058. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9060. EXPECT_EQ(StatusCode::OK_200, res->status);
  9061. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9062. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9063. EXPECT_EQ("aaabbb", res->body);
  9064. }
  9065. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9066. auto port = start(enable);
  9067. Client cli(HOST, port);
  9068. cli.set_read_timeout(1, 0);
  9069. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9070. Headers{{"Accept-Encoding", "gzip"}});
  9071. ASSERT_TRUE(handle.is_valid());
  9072. // The provider writes 100 bytes and then stalls for longer than the read
  9073. // timeout. Those first bytes have to arrive anyway: run the response through
  9074. // a compressor and zlib holds them until its window fills, so the read would
  9075. // come back empty instead.
  9076. char buf[256];
  9077. auto n = handle.read(buf, sizeof(buf));
  9078. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9079. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9080. }
  9081. #endif
  9082. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9083. TEST_F(ServerTest, Brotli) {
  9084. Headers headers;
  9085. headers.emplace("Accept-Encoding", "br");
  9086. auto res = cli_.Get("/compress", headers);
  9087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9088. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9089. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9090. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9091. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9092. "7890123456789012345678901234567890",
  9093. res->body);
  9094. EXPECT_EQ(StatusCode::OK_200, res->status);
  9095. }
  9096. #endif
  9097. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9098. TEST_F(ServerTest, Zstd) {
  9099. Headers headers;
  9100. headers.emplace("Accept-Encoding", "zstd");
  9101. auto res = cli_.Get("/compress", headers);
  9102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9103. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9104. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9105. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9106. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9107. "7890123456789012345678901234567890",
  9108. res->body);
  9109. EXPECT_EQ(StatusCode::OK_200, res->status);
  9110. }
  9111. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9112. Headers headers;
  9113. headers.emplace("Accept-Encoding", "");
  9114. auto res = cli_.Get("/compress", headers);
  9115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9116. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9118. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9120. "7890123456789012345678901234567890",
  9121. res->body);
  9122. EXPECT_EQ(StatusCode::OK_200, res->status);
  9123. }
  9124. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9125. Headers headers;
  9126. headers.emplace("Accept-Encoding", "zstd");
  9127. std::string body;
  9128. auto res =
  9129. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9130. EXPECT_EQ(100U, data_length);
  9131. body.append(data, data_length);
  9132. return true;
  9133. });
  9134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9135. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9136. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9137. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9138. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9139. "7890123456789012345678901234567890",
  9140. body);
  9141. EXPECT_EQ(StatusCode::OK_200, res->status);
  9142. }
  9143. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9144. Headers headers;
  9145. headers.emplace("Accept-Encoding", "zstd");
  9146. cli_.set_decompress(false);
  9147. auto res = cli_.Get("/compress", headers);
  9148. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9149. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9150. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9151. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9153. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9154. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9155. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9156. EXPECT_EQ(StatusCode::OK_200, res->status);
  9157. ASSERT_EQ(26U, res->body.size());
  9158. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9159. 0);
  9160. }
  9161. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9162. Headers headers;
  9163. headers.emplace("Accept-Encoding", "");
  9164. std::string body;
  9165. auto res =
  9166. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9167. EXPECT_EQ(100U, data_length);
  9168. body.append(data, data_length);
  9169. return true;
  9170. });
  9171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9172. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9173. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9174. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9175. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9176. "7890123456789012345678901234567890",
  9177. body);
  9178. EXPECT_EQ(StatusCode::OK_200, res->status);
  9179. }
  9180. TEST_F(ServerTest, NoZstd) {
  9181. Headers headers;
  9182. headers.emplace("Accept-Encoding", "zstd");
  9183. auto res = cli_.Get("/nocompress", headers);
  9184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9185. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9186. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9187. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9188. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9189. "7890123456789012345678901234567890",
  9190. res->body);
  9191. EXPECT_EQ(StatusCode::OK_200, res->status);
  9192. }
  9193. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9194. Headers headers;
  9195. headers.emplace("Accept-Encoding", "zstd");
  9196. std::string body;
  9197. auto res = cli_.Get("/nocompress", headers,
  9198. [&](const char *data, size_t data_length) {
  9199. EXPECT_EQ(100U, data_length);
  9200. body.append(data, data_length);
  9201. return true;
  9202. });
  9203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9204. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9205. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9206. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9207. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9208. "7890123456789012345678901234567890",
  9209. body);
  9210. EXPECT_EQ(StatusCode::OK_200, res->status);
  9211. }
  9212. // TODO: How to enable zstd ??
  9213. TEST_F(ServerTest, MultipartFormDataZstd) {
  9214. UploadFormDataItems items = {
  9215. {"key1", "test", "", ""},
  9216. {"key2", "--abcdefg123", "", ""},
  9217. };
  9218. Headers headers;
  9219. headers.emplace("Accept-Encoding", "zstd");
  9220. cli_.set_compress(true);
  9221. auto res = cli_.Post("/compress-multipart", headers, items);
  9222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9223. EXPECT_EQ(StatusCode::OK_200, res->status);
  9224. }
  9225. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9226. Headers headers;
  9227. headers.emplace("Accept-Encoding", "zstd");
  9228. cli_.set_compress(true);
  9229. auto res = cli_.Put(
  9230. "/put", headers, 3,
  9231. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9232. sink.os << "PUT";
  9233. return true;
  9234. },
  9235. "text/plain");
  9236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9237. EXPECT_EQ(StatusCode::OK_200, res->status);
  9238. EXPECT_EQ("PUT", res->body);
  9239. }
  9240. // Pre-compression logging tests
  9241. TEST_F(ServerTest, PreCompressionLogging) {
  9242. // Test data for compression (matches the actual /compress endpoint content)
  9243. const std::string test_content =
  9244. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9245. "3456789012345678901234567890";
  9246. // Variables to capture logging data
  9247. std::string pre_compression_body;
  9248. std::string pre_compression_content_type;
  9249. std::string pre_compression_content_encoding;
  9250. std::string post_compression_body;
  9251. std::string post_compression_content_type;
  9252. std::string post_compression_content_encoding;
  9253. // Set up pre-compression logger
  9254. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9255. const Response &res) {
  9256. pre_compression_body = res.body;
  9257. pre_compression_content_type = res.get_header_value("Content-Type");
  9258. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9259. });
  9260. // Set up post-compression logger
  9261. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9262. post_compression_body = res.body;
  9263. post_compression_content_type = res.get_header_value("Content-Type");
  9264. post_compression_content_encoding =
  9265. res.get_header_value("Content-Encoding");
  9266. });
  9267. // Test with gzip compression
  9268. Headers headers;
  9269. headers.emplace("Accept-Encoding", "gzip");
  9270. auto res = cli_.Get("/compress", headers);
  9271. // Verify response was compressed
  9272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9273. EXPECT_EQ(StatusCode::OK_200, res->status);
  9274. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9275. // Verify pre-compression logger captured uncompressed content
  9276. EXPECT_EQ(test_content, pre_compression_body);
  9277. EXPECT_EQ("text/plain", pre_compression_content_type);
  9278. EXPECT_TRUE(pre_compression_content_encoding
  9279. .empty()); // No encoding header before compression
  9280. // Verify post-compression logger captured compressed content
  9281. EXPECT_NE(test_content,
  9282. post_compression_body); // Should be different after compression
  9283. EXPECT_EQ("text/plain", post_compression_content_type);
  9284. EXPECT_EQ("gzip", post_compression_content_encoding);
  9285. // Verify compressed content is smaller
  9286. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9287. }
  9288. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9289. const std::string test_content =
  9290. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9291. "3456789012345678901234567890";
  9292. std::string pre_compression_body;
  9293. std::string post_compression_body;
  9294. svr_.set_pre_compression_logger(
  9295. [&](const Request & /*req*/, const Response &res) {
  9296. pre_compression_body = res.body;
  9297. });
  9298. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9299. post_compression_body = res.body;
  9300. });
  9301. Headers headers;
  9302. headers.emplace("Accept-Encoding", "br");
  9303. auto res = cli_.Get("/compress", headers);
  9304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9305. EXPECT_EQ(StatusCode::OK_200, res->status);
  9306. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9307. // Verify pre-compression content is uncompressed
  9308. EXPECT_EQ(test_content, pre_compression_body);
  9309. // Verify post-compression content is compressed
  9310. EXPECT_NE(test_content, post_compression_body);
  9311. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9312. }
  9313. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9314. const std::string test_content =
  9315. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9316. "3456789012345678901234567890";
  9317. std::string pre_compression_body;
  9318. std::string post_compression_body;
  9319. svr_.set_pre_compression_logger(
  9320. [&](const Request & /*req*/, const Response &res) {
  9321. pre_compression_body = res.body;
  9322. });
  9323. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9324. post_compression_body = res.body;
  9325. });
  9326. // Request without compression (use /nocompress endpoint)
  9327. Headers headers;
  9328. auto res = cli_.Get("/nocompress", headers);
  9329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9330. EXPECT_EQ(StatusCode::OK_200, res->status);
  9331. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9332. // Pre-compression logger should not be called when no compression is applied
  9333. EXPECT_TRUE(
  9334. pre_compression_body.empty()); // Pre-compression logger not called
  9335. EXPECT_EQ(
  9336. test_content,
  9337. post_compression_body); // Post-compression logger captures final content
  9338. }
  9339. TEST_F(ServerTest, LoggerSeesContentLength) {
  9340. size_t logged_content_length = 0;
  9341. std::string logged_content_length_header;
  9342. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9343. logged_content_length = res.content_length_;
  9344. logged_content_length_header = res.get_header_value("Content-Length");
  9345. });
  9346. auto res = cli_.Get("/nocompress");
  9347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9348. EXPECT_EQ(StatusCode::OK_200, res->status);
  9349. EXPECT_EQ(res->body.size(), logged_content_length);
  9350. EXPECT_EQ(std::to_string(logged_content_length),
  9351. logged_content_length_header);
  9352. }
  9353. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9354. const std::string test_content =
  9355. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9356. "3456789012345678901234567890";
  9357. std::string pre_compression_body;
  9358. bool pre_logger_called = false;
  9359. // Set only pre-compression logger
  9360. svr_.set_pre_compression_logger(
  9361. [&](const Request & /*req*/, const Response &res) {
  9362. pre_compression_body = res.body;
  9363. pre_logger_called = true;
  9364. });
  9365. Headers headers;
  9366. headers.emplace("Accept-Encoding", "gzip");
  9367. auto res = cli_.Get("/compress", headers);
  9368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9369. EXPECT_EQ(StatusCode::OK_200, res->status);
  9370. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9371. // Verify pre-compression logger was called
  9372. EXPECT_TRUE(pre_logger_called);
  9373. EXPECT_EQ(test_content, pre_compression_body);
  9374. }
  9375. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9376. {
  9377. // Test with Expect: 100-continue header - success case
  9378. // Server returns 100 Continue, client sends body, server returns 200 OK
  9379. Request req;
  9380. req.method = "POST";
  9381. req.path = "/post-large";
  9382. req.set_header("Expect", "100-continue");
  9383. req.body = LARGE_DATA;
  9384. Response res;
  9385. auto error = Error::Success;
  9386. cli_.set_keep_alive(true);
  9387. auto ret = cli_.send(req, res, error);
  9388. EXPECT_TRUE(ret);
  9389. EXPECT_EQ(StatusCode::OK_200, res.status);
  9390. EXPECT_EQ(LARGE_DATA, res.body);
  9391. }
  9392. {
  9393. // Test with Expect: 100-continue header - error case
  9394. // Client should not send the body when server returns an error
  9395. Request req;
  9396. req.method = "POST";
  9397. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9398. req.set_header("Expect", "100-continue");
  9399. req.body = LARGE_DATA;
  9400. Response res;
  9401. auto error = Error::Success;
  9402. auto start = std::chrono::high_resolution_clock::now();
  9403. cli_.set_keep_alive(true);
  9404. auto ret = cli_.send(req, res, error);
  9405. auto end = std::chrono::high_resolution_clock::now();
  9406. auto elapsed =
  9407. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9408. .count();
  9409. // With Expect: 100-continue, request completes successfully but with error
  9410. EXPECT_TRUE(ret);
  9411. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9412. EXPECT_EQ("close", res.get_header_value("Connection"));
  9413. EXPECT_FALSE(cli_.is_socket_open());
  9414. EXPECT_LE(elapsed, 2000);
  9415. }
  9416. {
  9417. // Send an extra GET request to ensure error recovery without hanging
  9418. Request req;
  9419. req.method = "GET";
  9420. req.path = "/hi";
  9421. auto start = std::chrono::high_resolution_clock::now();
  9422. auto res = cli_.send(req);
  9423. auto end = std::chrono::high_resolution_clock::now();
  9424. auto elapsed =
  9425. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9426. .count();
  9427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9428. EXPECT_EQ(StatusCode::OK_200, res->status);
  9429. EXPECT_EQ("Hello World!", res->body);
  9430. EXPECT_LE(elapsed, 500);
  9431. }
  9432. }
  9433. TEST(ZstdDecompressor, ChunkedDecompression) {
  9434. std::string data;
  9435. for (size_t i = 0; i < 32 * 1024; ++i) {
  9436. data.push_back(static_cast<char>('a' + i % 26));
  9437. }
  9438. std::string compressed_data;
  9439. {
  9440. httplib::detail::zstd_compressor compressor;
  9441. bool result = compressor.compress(
  9442. data.data(), data.size(),
  9443. /*last=*/true,
  9444. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9445. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9446. compressed_data_size);
  9447. return true;
  9448. });
  9449. ASSERT_TRUE(result);
  9450. }
  9451. std::string decompressed_data;
  9452. {
  9453. httplib::detail::zstd_decompressor decompressor;
  9454. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9455. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9456. size_t chunk_size = 130;
  9457. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9458. chunk_begin += chunk_size) {
  9459. size_t current_chunk_size =
  9460. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9461. bool result = decompressor.decompress(
  9462. compressed_data.data() + chunk_begin, current_chunk_size,
  9463. [&](const char *decompressed_data_chunk,
  9464. size_t decompressed_data_chunk_size) {
  9465. decompressed_data.insert(decompressed_data.size(),
  9466. decompressed_data_chunk,
  9467. decompressed_data_chunk_size);
  9468. return true;
  9469. });
  9470. ASSERT_TRUE(result);
  9471. }
  9472. }
  9473. ASSERT_EQ(data, decompressed_data);
  9474. }
  9475. TEST(ZstdDecompressor, Decompress) {
  9476. std::string original_text = "Compressed with ZSTD";
  9477. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9478. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9479. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9480. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9481. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9482. std::string decompressed_data;
  9483. {
  9484. httplib::detail::zstd_decompressor decompressor;
  9485. bool result = decompressor.decompress(
  9486. compressed_data.data(), compressed_data.size(),
  9487. [&](const char *decompressed_data_chunk,
  9488. size_t decompressed_data_chunk_size) {
  9489. decompressed_data.insert(decompressed_data.size(),
  9490. decompressed_data_chunk,
  9491. decompressed_data_chunk_size);
  9492. return true;
  9493. });
  9494. ASSERT_TRUE(result);
  9495. }
  9496. ASSERT_EQ(original_text, decompressed_data);
  9497. }
  9498. #endif
  9499. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9500. // separate chunks so that the server sees each part in its own read(). Used to
  9501. // place a read boundary at a specific offset of a request body.
  9502. static bool send_request_in_parts(time_t read_timeout_sec,
  9503. const std::vector<std::string> &parts,
  9504. std::string *resp = nullptr,
  9505. int port = PORT) {
  9506. auto error = Error::Success;
  9507. auto client_sock = detail::create_client_socket(
  9508. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9509. /*connection_timeout_sec=*/5, 0,
  9510. /*read_timeout_sec=*/5, 0,
  9511. /*write_timeout_sec=*/5, 0, std::string(), error);
  9512. if (client_sock == INVALID_SOCKET) { return false; }
  9513. auto ret = detail::process_client_socket(
  9514. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9515. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9516. for (size_t i = 0; i < parts.size(); i++) {
  9517. const auto &part = parts[i];
  9518. if (part.size() !=
  9519. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9520. return false;
  9521. }
  9522. if (i + 1 < parts.size()) {
  9523. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9524. }
  9525. }
  9526. char buf[512];
  9527. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9528. while (line_reader.getline()) {
  9529. if (resp) { *resp += line_reader.ptr(); }
  9530. }
  9531. return true;
  9532. });
  9533. detail::close_socket(client_sock);
  9534. return ret;
  9535. }
  9536. // Sends a raw request to a server listening at HOST:PORT.
  9537. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9538. std::string *resp = nullptr, int port = PORT) {
  9539. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9540. }
  9541. #ifdef CPPHTTPLIB_SSL_ENABLED
  9542. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9543. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9544. ASSERT_TRUE(svr.is_valid());
  9545. svr.set_read_timeout(1, 0);
  9546. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9547. auto se = detail::scope_exit([&] {
  9548. svr.stop();
  9549. t.join();
  9550. ASSERT_FALSE(svr.is_running());
  9551. });
  9552. svr.wait_until_ready();
  9553. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9554. // keeps each wait well within the read timeout. The server gives up a
  9555. // second in, so the bytes sent after that fail.
  9556. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9557. parts.resize(26, std::string(1, '\0'));
  9558. EXPECT_FALSE(send_request_in_parts(5, parts));
  9559. }
  9560. #endif
  9561. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9562. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9563. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9564. const std::vector<std::string> &parts,
  9565. std::string *resp = nullptr,
  9566. int port = PORT) {
  9567. auto error = Error::Success;
  9568. auto sock = detail::create_client_socket(
  9569. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9570. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9571. /*write_timeout_sec=*/5, 0, std::string(), error);
  9572. if (sock == INVALID_SOCKET) { return false; }
  9573. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9574. auto ctx = SSL_CTX_new(TLS_client_method());
  9575. auto ssl = SSL_new(ctx);
  9576. auto ssl_se = detail::scope_exit([&] {
  9577. SSL_free(ssl);
  9578. SSL_CTX_free(ctx);
  9579. });
  9580. SSL_set_fd(ssl, static_cast<int>(sock));
  9581. if (SSL_connect(ssl) != 1) { return false; }
  9582. for (size_t i = 0; i < parts.size(); i++) {
  9583. const auto &part = parts[i];
  9584. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9585. static_cast<int>(part.size())) {
  9586. return false;
  9587. }
  9588. if (i + 1 < parts.size()) {
  9589. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9590. }
  9591. }
  9592. char buf[512];
  9593. int n;
  9594. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9595. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9596. }
  9597. return true;
  9598. }
  9599. #endif
  9600. // The request line, then a header value a byte at a time.
  9601. static std::vector<std::string> slow_request_head_parts() {
  9602. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9603. parts.resize(26, "a");
  9604. parts.emplace_back("\r\n\r\n");
  9605. return parts;
  9606. }
  9607. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9608. // within the one-second read timeout. The server gives up a second in, before
  9609. // the head is complete.
  9610. static void
  9611. expect_slow_request_head_dropped(Server &svr,
  9612. const std::function<std::string()> &send) {
  9613. std::atomic<bool> handled(false);
  9614. svr.Get("/", [&](const Request &, Response &res) {
  9615. handled = true;
  9616. res.set_content("ok", "text/plain");
  9617. });
  9618. svr.set_read_timeout(1, 0);
  9619. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9620. auto se = detail::scope_exit([&] {
  9621. svr.stop();
  9622. t.join();
  9623. ASSERT_FALSE(svr.is_running());
  9624. });
  9625. svr.wait_until_ready();
  9626. auto resp = send();
  9627. EXPECT_FALSE(handled);
  9628. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9629. }
  9630. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9631. Server svr;
  9632. expect_slow_request_head_dropped(svr, [] {
  9633. std::string resp;
  9634. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9635. return resp;
  9636. });
  9637. }
  9638. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9639. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9640. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9641. ASSERT_TRUE(svr.is_valid());
  9642. expect_slow_request_head_dropped(svr, [] {
  9643. std::string resp;
  9644. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9645. return resp;
  9646. });
  9647. }
  9648. #endif
  9649. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9650. Server svr;
  9651. std::string header_value;
  9652. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9653. header_value = req.get_header_value("foo");
  9654. res.set_content("ok", "text/plain");
  9655. });
  9656. thread t = thread([&] { svr.listen(HOST, PORT); });
  9657. auto se = detail::scope_exit([&] {
  9658. svr.stop();
  9659. t.join();
  9660. ASSERT_FALSE(svr.is_running());
  9661. });
  9662. svr.wait_until_ready();
  9663. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9664. // like characters are not treated the same - use vertical tab and escape.
  9665. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9666. "foo: \t \v bar \x1B\t \r\n"
  9667. "Connection: close\r\n"
  9668. "\r\n";
  9669. std::string res;
  9670. ASSERT_TRUE(send_request(5, req, &res));
  9671. EXPECT_EQ(header_value, "");
  9672. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9673. }
  9674. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9675. Server svr;
  9676. std::string received;
  9677. svr.Get("/order", [&](const Request &req, Response &res) {
  9678. received = entries_to_string(req.headers);
  9679. res.set_content("ok", "text/plain");
  9680. });
  9681. auto port = svr.bind_to_any_port(HOST);
  9682. thread t = thread([&] { svr.listen_after_bind(); });
  9683. auto se = detail::scope_exit([&] {
  9684. svr.stop();
  9685. t.join();
  9686. ASSERT_FALSE(svr.is_running());
  9687. });
  9688. svr.wait_until_ready();
  9689. const std::string req = "GET /order HTTP/1.1\r\n"
  9690. "Host: localhost\r\n"
  9691. "X-First: 1\r\n"
  9692. "X-Dup: a\r\n"
  9693. "X-Second: 2\r\n"
  9694. "X-Dup: b\r\n"
  9695. "Connection: close\r\n"
  9696. "\r\n";
  9697. std::string res;
  9698. ASSERT_TRUE(send_request(5, req, &res, port));
  9699. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9700. EXPECT_EQ(
  9701. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9702. received);
  9703. }
  9704. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9705. Server svr;
  9706. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9707. res.set_header("Set-Cookie", "first=1");
  9708. res.set_header("X-Between", "y");
  9709. res.set_header("Set-Cookie", "second=2");
  9710. res.set_content("ok", "text/plain");
  9711. });
  9712. auto port = svr.bind_to_any_port(HOST);
  9713. thread t = thread([&] { svr.listen_after_bind(); });
  9714. auto se = detail::scope_exit([&] {
  9715. svr.stop();
  9716. t.join();
  9717. ASSERT_FALSE(svr.is_running());
  9718. });
  9719. svr.wait_until_ready();
  9720. Client cli(HOST, port);
  9721. auto res = cli.Get("/cookies");
  9722. ASSERT_TRUE(res);
  9723. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9724. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9725. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9726. }
  9727. // A stream may send a byte at a time with a small extension on each chunk,
  9728. // however long it runs
  9729. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9730. Server svr;
  9731. svr.Post("/count", [](const Request &req, Response &res) {
  9732. res.set_content(std::to_string(req.body.size()), "text/plain");
  9733. });
  9734. auto port = svr.bind_to_any_port(HOST);
  9735. ASSERT_LT(0, port);
  9736. thread t = thread([&] { svr.listen_after_bind(); });
  9737. auto se = detail::scope_exit([&] {
  9738. svr.stop();
  9739. t.join();
  9740. ASSERT_FALSE(svr.is_running());
  9741. });
  9742. svr.wait_until_ready();
  9743. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9744. "\r\nTransfer-Encoding: chunked\r\n"
  9745. "Connection: close\r\n\r\n";
  9746. for (auto i = 0; i < 4096; i++) {
  9747. req += "1;a=b\r\nx\r\n";
  9748. }
  9749. req += "0\r\n\r\n";
  9750. std::string res;
  9751. ASSERT_TRUE(send_request(5, req, &res, port));
  9752. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9753. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9754. }
  9755. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9756. Server svr;
  9757. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9758. auto i = new int(0);
  9759. res.set_header("Trailer", "X-Safe, X-Reflected");
  9760. res.set_chunked_content_provider(
  9761. "text/plain",
  9762. [i](size_t /*offset*/, DataSink &sink) {
  9763. if (*i == 0) {
  9764. sink.os << "body";
  9765. } else {
  9766. Headers trailer;
  9767. // A valid trailer that must survive.
  9768. trailer.emplace("X-Safe", "safe");
  9769. // Attacker-controlled value carrying CR/LF (response splitting).
  9770. trailer.emplace("X-Reflected",
  9771. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9772. // Attacker-controlled name carrying CR/LF.
  9773. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9774. sink.done_with_trailer(trailer);
  9775. }
  9776. (*i)++;
  9777. return true;
  9778. },
  9779. [i](bool /*success*/) { delete i; });
  9780. });
  9781. thread t = thread([&] { svr.listen(HOST, PORT); });
  9782. auto se = detail::scope_exit([&] {
  9783. svr.stop();
  9784. t.join();
  9785. ASSERT_FALSE(svr.is_running());
  9786. });
  9787. svr.wait_until_ready();
  9788. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9789. "Host: " + HOST +
  9790. "\r\n"
  9791. "Connection: close\r\n"
  9792. "\r\n";
  9793. std::string res;
  9794. ASSERT_TRUE(send_request(5, req, &res));
  9795. // The injected fields must not appear anywhere in the raw response.
  9796. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9797. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9798. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9799. // Invalid trailers are dropped entirely, matching set_header().
  9800. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9801. // The valid trailer still passes through.
  9802. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9803. }
  9804. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9805. // A custom header writer gets only the fields the default one writes
  9806. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9807. std::string s;
  9808. for (const auto &h : hdrs) {
  9809. s += h.first + ": " + h.second + "\r\n";
  9810. }
  9811. s += "\r\n";
  9812. return strm.write(s.data(), s.size());
  9813. };
  9814. for (auto custom_writer : {false, true}) {
  9815. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9816. Server svr;
  9817. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9818. svr.set_post_routing_handler([](const Request &, Response &res) {
  9819. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9820. });
  9821. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9822. // res.headers is a public field an application can populate directly,
  9823. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9824. // A valid header that must survive.
  9825. res.headers.emplace("X-Safe", "safe");
  9826. // Attacker-controlled value carrying CR/LF (response splitting).
  9827. res.headers.emplace("X-Reflected",
  9828. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9829. // Attacker-controlled name carrying CR/LF.
  9830. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9831. res.set_content("body", "text/plain");
  9832. });
  9833. thread t = thread([&] { svr.listen(HOST, PORT); });
  9834. auto se = detail::scope_exit([&] {
  9835. svr.stop();
  9836. t.join();
  9837. ASSERT_FALSE(svr.is_running());
  9838. });
  9839. svr.wait_until_ready();
  9840. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9841. "Host: " + HOST +
  9842. "\r\n"
  9843. "Connection: close\r\n"
  9844. "\r\n";
  9845. std::string res;
  9846. ASSERT_TRUE(send_request(5, req, &res));
  9847. // The injected fields must not appear anywhere in the raw response.
  9848. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9849. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9850. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9851. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9852. // Invalid headers are dropped entirely, matching set_header().
  9853. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9854. // The valid header still passes through.
  9855. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9856. }
  9857. }
  9858. // Forward declaration: in split builds split.py strips `inline` and moves the
  9859. // definition into httplib.cc, so detail::write_request_line is not visible from
  9860. // the public httplib.h. Re-declaring it here lets the tests link against the
  9861. // symbol in both header-only and split builds.
  9862. namespace httplib {
  9863. namespace detail {
  9864. ssize_t write_request_line(Stream &strm, const std::string &method,
  9865. const std::string &path);
  9866. } // namespace detail
  9867. } // namespace httplib
  9868. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9869. // A well-formed target is written verbatim.
  9870. {
  9871. detail::BufferStream strm;
  9872. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9873. EXPECT_GT(n, 0);
  9874. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9875. }
  9876. // A target carrying CR/LF, SP or other control octets must be rejected
  9877. // before anything reaches the wire, otherwise it splits the request line and
  9878. // injects a header or a whole request.
  9879. const std::string evil_targets[] = {
  9880. "/a\r\nInjected: pwned",
  9881. "/a\rInjected",
  9882. "/a\nInjected",
  9883. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9884. "/a b",
  9885. "/a\tb",
  9886. "/a\x7f",
  9887. };
  9888. for (const auto &evil : evil_targets) {
  9889. detail::BufferStream strm;
  9890. auto n = detail::write_request_line(strm, "GET", evil);
  9891. EXPECT_LT(n, 0);
  9892. EXPECT_TRUE(strm.get_buffer().empty());
  9893. }
  9894. }
  9895. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9896. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9897. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9898. // target reaches write_request. The client must fail cleanly with
  9899. // Error::Write instead of putting a request-line-less, header-injecting
  9900. // request on the wire.
  9901. Server svr;
  9902. svr.Get("/a", [](const Request &, Response &res) {
  9903. res.set_content("ok", "text/plain");
  9904. });
  9905. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9906. auto se = detail::scope_exit([&] {
  9907. svr.stop();
  9908. thread.join();
  9909. ASSERT_FALSE(svr.is_running());
  9910. });
  9911. svr.wait_until_ready();
  9912. {
  9913. Client cli(HOST, PORT);
  9914. cli.set_path_encode(false);
  9915. // The request is rejected before anything is written, so the connection
  9916. // stays silent and the subsequent response read would otherwise block for
  9917. // the full default read timeout. Shorten it -- the assertion is on the
  9918. // error, not the timeout.
  9919. cli.set_read_timeout(1, 0);
  9920. auto res = cli.Get("/a\r\nInjected: pwned");
  9921. EXPECT_FALSE(res);
  9922. EXPECT_EQ(Error::Write, res.error());
  9923. }
  9924. }
  9925. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9926. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9927. // including extension methods.
  9928. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9929. for (const auto &method : good_methods) {
  9930. detail::BufferStream strm;
  9931. auto n = detail::write_request_line(strm, method, "/");
  9932. EXPECT_GT(n, 0);
  9933. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9934. }
  9935. // A method carrying CR/LF would split the request line and smuggle a whole
  9936. // request ahead of the real one. A space or an empty method corrupts the
  9937. // request line. All must be rejected before anything reaches the wire.
  9938. const std::string evil_methods[] = {
  9939. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9940. "GET\r\nInjected: pwned",
  9941. "GET\r",
  9942. "GET\n",
  9943. "GE T",
  9944. "",
  9945. };
  9946. for (const auto &evil : evil_methods) {
  9947. detail::BufferStream strm;
  9948. auto n = detail::write_request_line(strm, evil, "/");
  9949. EXPECT_LT(n, 0);
  9950. EXPECT_TRUE(strm.get_buffer().empty());
  9951. }
  9952. }
  9953. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9954. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9955. // through Client::send must fail with Error::Write and no request, neither
  9956. // the smuggled one nor the real one, may reach the server.
  9957. Server svr;
  9958. std::atomic<int> request_count(0);
  9959. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9960. request_count++;
  9961. res.status = StatusCode::OK_200;
  9962. return Server::HandlerResponse::Handled;
  9963. });
  9964. auto port = svr.bind_to_any_port(HOST);
  9965. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9966. auto se = detail::scope_exit([&] {
  9967. svr.stop();
  9968. thread.join();
  9969. ASSERT_FALSE(svr.is_running());
  9970. });
  9971. svr.wait_until_ready();
  9972. {
  9973. Client cli(HOST, port);
  9974. const std::string evil_methods[] = {
  9975. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9976. "GE T",
  9977. "",
  9978. };
  9979. for (const auto &evil : evil_methods) {
  9980. Request req;
  9981. req.method = evil;
  9982. req.path = "/";
  9983. auto res = cli.send(req);
  9984. EXPECT_FALSE(res);
  9985. EXPECT_EQ(Error::Write, res.error());
  9986. }
  9987. auto handle =
  9988. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9989. EXPECT_FALSE(handle.is_valid());
  9990. EXPECT_EQ(Error::Write, handle.error);
  9991. // A valid request on the same client still goes through.
  9992. auto res = cli.Get("/");
  9993. ASSERT_TRUE(res);
  9994. EXPECT_EQ(StatusCode::OK_200, res->status);
  9995. }
  9996. EXPECT_EQ(1, request_count.load());
  9997. }
  9998. // Sends a raw request and verifies that there isn't a crash or exception.
  9999. static void test_raw_request(const std::string &req,
  10000. std::string *out = nullptr) {
  10001. Server svr;
  10002. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10003. res.set_content("ok", "text/plain");
  10004. });
  10005. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10006. res.set_content("ok", "text/plain");
  10007. });
  10008. svr.Get("/header_field_value_check",
  10009. [&](const Request & /*req*/, Response &res) {
  10010. res.set_content("ok", "text/plain");
  10011. });
  10012. svr.CustomRoute("PROPFIND", "/dav",
  10013. [&](const Request & /*req*/, Response &res) {
  10014. res.status = StatusCode::MultiStatus_207;
  10015. });
  10016. // Server read timeout must be longer than the client read timeout for the
  10017. // bug to reproduce, probably to force the server to process a request
  10018. // without a trailing blank line.
  10019. const time_t client_read_timeout_sec = 1;
  10020. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10021. bool listen_thread_ok = false;
  10022. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10023. auto se = detail::scope_exit([&] {
  10024. svr.stop();
  10025. t.join();
  10026. ASSERT_FALSE(svr.is_running());
  10027. EXPECT_TRUE(listen_thread_ok);
  10028. });
  10029. svr.wait_until_ready();
  10030. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10031. }
  10032. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10033. // A certain header line causes an exception if the header property is parsed
  10034. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10035. test_raw_request(
  10036. "GET /hi HTTP/1.1\r\n"
  10037. " : "
  10038. " "
  10039. " ");
  10040. }
  10041. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10042. // A certain header line causes an exception if the header property *name* is
  10043. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10044. // greedy matcher and requires backtracking when there are a lot of ":"
  10045. // characters.
  10046. // This occurs with libc++ but not libstdc++.
  10047. test_raw_request(
  10048. "GET /hi HTTP/1.1\r\n"
  10049. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10050. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10051. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10052. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10053. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10054. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10055. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10056. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10057. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10058. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10059. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10060. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10061. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10062. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10063. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10064. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10065. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10066. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10067. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10068. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10069. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10070. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10071. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10072. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10073. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10074. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10075. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10076. "&&&%%%");
  10077. }
  10078. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10079. // Make sure this doesn't crash the server.
  10080. // In a previous version of the header line regex, the "\r" rendered the line
  10081. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10082. // a new position where the leading white space ended and the field value
  10083. // began.
  10084. // The crash occurs with libc++ but not libstdc++.
  10085. test_raw_request("GET /hi HTTP/1.1\r\n"
  10086. "a:" +
  10087. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10088. "\r\n"
  10089. "\r\n");
  10090. }
  10091. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10092. const char *rejected[] = {
  10093. // RFC 9112 §3: one SP between the parts, and nothing else
  10094. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10095. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10096. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10097. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10098. // A request-target has no fragment
  10099. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10100. // An HTTP/1.1 request needs a Host
  10101. "GET /hi HTTP/1.1\r\n\r\n",
  10102. };
  10103. for (auto request : rejected) {
  10104. std::string out;
  10105. test_raw_request(request, &out);
  10106. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10107. }
  10108. std::string out;
  10109. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10110. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10111. }
  10112. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10113. // RFC 9112 §6.1
  10114. const char *requests[] = {
  10115. "PUT /put_hi HTTP/1.1\r\n"
  10116. "Host: localhost\r\n"
  10117. "Content-Length: 0\r\n"
  10118. "Transfer-Encoding: chunked\r\n"
  10119. "\r\n"
  10120. "0\r\n\r\n",
  10121. "PUT /put_hi HTTP/1.0\r\n"
  10122. "Connection: keep-alive\r\n"
  10123. "Transfer-Encoding: chunked\r\n"
  10124. "\r\n"
  10125. "0\r\n\r\n",
  10126. };
  10127. for (auto request : requests) {
  10128. std::string out;
  10129. test_raw_request(request, &out);
  10130. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10131. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10132. }
  10133. }
  10134. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10135. std::string out;
  10136. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10137. "Content-Type: text/plain\r\n"
  10138. "Transfer-Encoding: chunked\r\n"
  10139. "\r\n"
  10140. "nothex\r\n",
  10141. &out);
  10142. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10143. }
  10144. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10145. std::string out;
  10146. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10147. "Content-Type: text/plain\r\n"
  10148. "Transfer-Encoding: chunked\r\n"
  10149. "\r\n"
  10150. "3\r\n"
  10151. "xyz\r\n"
  10152. "NaN\r\n",
  10153. &out);
  10154. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10155. }
  10156. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10157. std::string out;
  10158. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10159. "Content-Type: text/plain\r\n"
  10160. "Transfer-Encoding: chunked\r\n"
  10161. "\r\n"
  10162. // Length is too large for 64 bits.
  10163. "1ffffffffffffffff\r\n"
  10164. "xyz\r\n",
  10165. &out);
  10166. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10167. }
  10168. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10169. test_raw_request("GET /hi HTTP/1.1\r\n"
  10170. "Content-Type: text/plain\r\n\r");
  10171. }
  10172. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10173. std::string out;
  10174. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10175. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10176. }
  10177. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10178. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10179. std::string out;
  10180. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10181. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10182. }
  10183. }
  10184. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10185. std::string out;
  10186. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10187. "Host: localhost\r\n"
  10188. "Connection: close\r\n\r\n",
  10189. &out);
  10190. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10191. }
  10192. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10193. Server svr;
  10194. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10195. EXPECT_TRUE(!req.remote_addr.empty());
  10196. });
  10197. thread t = thread([&] { svr.listen(HOST, PORT); });
  10198. auto se = detail::scope_exit([&] {
  10199. svr.stop();
  10200. t.join();
  10201. ASSERT_FALSE(svr.is_running());
  10202. });
  10203. svr.wait_until_ready();
  10204. // Send an invalid request line to trigger Bad Request
  10205. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10206. std::string out;
  10207. ASSERT_TRUE(send_request(5, bad_req, &out));
  10208. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10209. }
  10210. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10211. // answered right away rather than blocking on a read that waits for EOF.
  10212. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10213. std::string out;
  10214. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10215. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10216. }
  10217. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10218. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10219. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10220. for (const auto *method : methods) {
  10221. Server svr;
  10222. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10223. EXPECT_FALSE(svr.is_valid()) << method;
  10224. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10225. }
  10226. }
  10227. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10228. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10229. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10230. for (const auto *method : methods) {
  10231. Server svr;
  10232. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10233. EXPECT_FALSE(svr.is_valid()) << method;
  10234. }
  10235. }
  10236. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10237. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10238. "COPY", "MOVE", "LOCK",
  10239. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10240. Server svr;
  10241. for (const auto *method : methods) {
  10242. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10243. }
  10244. EXPECT_TRUE(svr.is_valid());
  10245. }
  10246. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10247. Server svr;
  10248. svr.CustomRoute("POST", "/x",
  10249. [](const Request &, Response &, const ContentReader &) {});
  10250. EXPECT_FALSE(svr.is_valid());
  10251. }
  10252. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10253. Server svr;
  10254. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10255. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10256. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10257. EXPECT_FALSE(svr.is_valid());
  10258. }
  10259. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10260. Server svr;
  10261. auto captured = Error::Success;
  10262. svr.set_error_logger(
  10263. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10264. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10265. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10266. }
  10267. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10268. std::string out;
  10269. std::string request(
  10270. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10271. test_raw_request(request, &out);
  10272. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10273. }
  10274. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10275. std::string out;
  10276. std::string request(
  10277. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10278. test_raw_request(request, &out);
  10279. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10280. }
  10281. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10282. std::string out;
  10283. std::string request(
  10284. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10285. test_raw_request(request, &out);
  10286. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10287. }
  10288. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10289. std::string out;
  10290. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10291. "Host: localhost\r\n"
  10292. "Test: \r\n\r\n",
  10293. &out);
  10294. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10295. }
  10296. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10297. Server svr;
  10298. std::string x_custom;
  10299. std::string cookie;
  10300. std::string xff;
  10301. std::string x_unicode;
  10302. std::string x_iis;
  10303. svr.Get("/check", [&](const Request &req, Response &res) {
  10304. x_custom = req.get_header_value("X-Custom");
  10305. cookie = req.get_header_value("Cookie");
  10306. xff = req.get_header_value("X-Forwarded-For");
  10307. x_unicode = req.get_header_value("X-Unicode");
  10308. x_iis = req.get_header_value("X-IIS");
  10309. res.set_content("ok", "text/plain");
  10310. });
  10311. thread t = thread([&] { svr.listen(HOST, PORT); });
  10312. auto se = detail::scope_exit([&] {
  10313. svr.stop();
  10314. t.join();
  10315. ASSERT_FALSE(svr.is_running());
  10316. });
  10317. svr.wait_until_ready();
  10318. const std::string req = "GET /check HTTP/1.1\r\n"
  10319. "Host: localhost\r\n"
  10320. "X-Custom: a%0D%0AInjected: b\r\n"
  10321. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10322. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10323. "X-Unicode: %E3%81%82\r\n"
  10324. "X-IIS: %u00E9\r\n"
  10325. "Connection: close\r\n"
  10326. "\r\n";
  10327. std::string res;
  10328. ASSERT_TRUE(send_request(5, req, &res));
  10329. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10330. // Every value must be returned verbatim (wire form), with no decoding.
  10331. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10332. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10333. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10334. EXPECT_EQ("%E3%81%82", x_unicode);
  10335. EXPECT_EQ("%u00E9", x_iis);
  10336. }
  10337. // Applications that previously relied on automatic percent-decoding can
  10338. // reproduce the old behavior by explicitly calling decode_path_component()
  10339. // or, for RFC 3986 conformance, decode_uri_component().
  10340. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10341. Server svr;
  10342. std::string decoded;
  10343. svr.Get("/check", [&](const Request &req, Response &res) {
  10344. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10345. res.set_content("ok", "text/plain");
  10346. });
  10347. thread t = thread([&] { svr.listen(HOST, PORT); });
  10348. auto se = detail::scope_exit([&] {
  10349. svr.stop();
  10350. t.join();
  10351. ASSERT_FALSE(svr.is_running());
  10352. });
  10353. svr.wait_until_ready();
  10354. const std::string req = "GET /check HTTP/1.1\r\n"
  10355. "Host: localhost\r\n"
  10356. "X-Custom: hello%20world\r\n"
  10357. "Connection: close\r\n"
  10358. "\r\n";
  10359. std::string res;
  10360. ASSERT_TRUE(send_request(5, req, &res));
  10361. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10362. EXPECT_EQ("hello world", decoded);
  10363. }
  10364. // Regression test for #2033. Browsers send Referer values that include
  10365. // percent-encoded characters such as %0A inside the URL. Decoding the
  10366. // header value would either trip the post-decode CR/LF/NUL guard (the
  10367. // original bug, returning 400) or, after that guard was relaxed, silently
  10368. // store a literal LF — both unacceptable. The wire form must round-trip.
  10369. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10370. Server svr;
  10371. std::string referer;
  10372. svr.Get("/check", [&](const Request &req, Response &res) {
  10373. referer = req.get_header_value("Referer");
  10374. res.set_content("ok", "text/plain");
  10375. });
  10376. thread t = thread([&] { svr.listen(HOST, PORT); });
  10377. auto se = detail::scope_exit([&] {
  10378. svr.stop();
  10379. t.join();
  10380. ASSERT_FALSE(svr.is_running());
  10381. });
  10382. svr.wait_until_ready();
  10383. const std::string req = "GET /check HTTP/1.1\r\n"
  10384. "Host: localhost\r\n"
  10385. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10386. "Connection: close\r\n"
  10387. "\r\n";
  10388. std::string res;
  10389. ASSERT_TRUE(send_request(5, req, &res));
  10390. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10391. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10392. }
  10393. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10394. Server svr;
  10395. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10396. res.set_header("Cache-Control", "no-cache");
  10397. res.set_chunked_content_provider(
  10398. "text/event-stream", [](size_t offset, DataSink &sink) {
  10399. std::string s = "data:";
  10400. s += std::to_string(offset);
  10401. s += "\n\n";
  10402. auto ret = sink.write(s.data(), s.size());
  10403. EXPECT_TRUE(ret);
  10404. std::this_thread::sleep_for(std::chrono::seconds(1));
  10405. return true;
  10406. });
  10407. });
  10408. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10409. svr.wait_until_ready();
  10410. Client client(HOST, PORT);
  10411. const Headers headers = {{"Accept", "text/event-stream"}};
  10412. auto get_thread = std::thread([&client, &headers]() {
  10413. auto res = client.Get(
  10414. "/events", headers,
  10415. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10416. });
  10417. auto se = detail::scope_exit([&] {
  10418. svr.stop();
  10419. get_thread.join();
  10420. listen_thread.join();
  10421. ASSERT_FALSE(svr.is_running());
  10422. });
  10423. // Give GET time to get a few messages.
  10424. std::this_thread::sleep_for(std::chrono::seconds(2));
  10425. }
  10426. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10427. httplib::Server svr;
  10428. svr.Post("/hi",
  10429. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10430. res.status = StatusCode::OK_200;
  10431. });
  10432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10433. svr.wait_until_ready();
  10434. Client cli(HOST, PORT);
  10435. auto res = cli.Post("/hi", "data", "text/plain");
  10436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10437. EXPECT_EQ(StatusCode::OK_200, res->status);
  10438. svr.stop();
  10439. thread.join();
  10440. ASSERT_FALSE(svr.is_running());
  10441. res = cli.Post("/hi", "data", "text/plain");
  10442. ASSERT_FALSE(res);
  10443. }
  10444. TEST(ServerStopTest, ListenFailure) {
  10445. Server svr;
  10446. auto t = thread([&]() {
  10447. auto ret = svr.listen("????", PORT);
  10448. EXPECT_FALSE(ret);
  10449. });
  10450. svr.wait_until_ready();
  10451. svr.stop();
  10452. t.join();
  10453. }
  10454. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10455. TEST(ServerStopTest, Decommision) {
  10456. Server svr;
  10457. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10458. for (int i = 0; i < 4; i++) {
  10459. auto is_even = !(i % 2);
  10460. std::thread t{[&] {
  10461. try {
  10462. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10463. if (is_even) {
  10464. throw std::runtime_error("Some thing that happens to go wrong.");
  10465. }
  10466. svr.listen(HOST, PORT);
  10467. } catch (...) { svr.decommission(); }
  10468. }};
  10469. svr.wait_until_ready();
  10470. // Server is up
  10471. {
  10472. Client cli(HOST, PORT);
  10473. auto res = cli.Get("/hi");
  10474. if (is_even) {
  10475. EXPECT_FALSE(res);
  10476. } else {
  10477. EXPECT_TRUE(res);
  10478. EXPECT_EQ("hi...", res->body);
  10479. }
  10480. }
  10481. svr.stop();
  10482. t.join();
  10483. // Server is down...
  10484. {
  10485. Client cli(HOST, PORT);
  10486. auto res = cli.Get("/hi");
  10487. EXPECT_FALSE(res);
  10488. }
  10489. }
  10490. }
  10491. #endif
  10492. // Helper function for string body upload progress tests
  10493. template <typename SetupHandler, typename ClientCall>
  10494. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10495. ClientCall &&client_call,
  10496. const string &body) {
  10497. Server svr;
  10498. setup_handler(svr);
  10499. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10500. auto se = detail::scope_exit([&] {
  10501. svr.stop();
  10502. t.join();
  10503. });
  10504. svr.wait_until_ready();
  10505. Client cli(HOST, PORT);
  10506. vector<uint64_t> progress_values;
  10507. bool progress_called = false;
  10508. auto res =
  10509. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10510. progress_values.push_back(current);
  10511. progress_called = true;
  10512. return true;
  10513. });
  10514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10515. EXPECT_EQ(200, res->status);
  10516. EXPECT_TRUE(progress_called);
  10517. }
  10518. TEST(UploadProgressTest, PostStringBodyBasic) {
  10519. TestStringBodyUploadProgress(
  10520. [](Server &svr) {
  10521. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10522. res.set_content("received", "text/plain");
  10523. });
  10524. },
  10525. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10526. return cli.Post("/test", body, "text/plain", progress_callback);
  10527. },
  10528. "test data for upload progress");
  10529. }
  10530. TEST(UploadProgressTest, PutStringBodyBasic) {
  10531. TestStringBodyUploadProgress(
  10532. [](Server &svr) {
  10533. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10534. res.set_content("put received", "text/plain");
  10535. });
  10536. },
  10537. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10538. return cli.Put("/test", body, "text/plain", progress_callback);
  10539. },
  10540. "put test data for upload progress");
  10541. }
  10542. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10543. TestStringBodyUploadProgress(
  10544. [](Server &svr) {
  10545. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10546. res.set_content("patch received", "text/plain");
  10547. });
  10548. },
  10549. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10550. return cli.Patch("/test", body, "text/plain", progress_callback);
  10551. },
  10552. "patch test data for upload progress");
  10553. }
  10554. // Helper function for content provider upload progress tests
  10555. template <typename SetupHandler, typename ClientCall>
  10556. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10557. ClientCall &&client_call) {
  10558. Server svr;
  10559. setup_handler(svr);
  10560. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10561. auto se = detail::scope_exit([&] {
  10562. svr.stop();
  10563. t.join();
  10564. });
  10565. svr.wait_until_ready();
  10566. Client cli(HOST, PORT);
  10567. vector<uint64_t> progress_values;
  10568. auto res =
  10569. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10570. progress_values.push_back(current);
  10571. return true;
  10572. });
  10573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10574. EXPECT_EQ(200, res->status);
  10575. EXPECT_FALSE(progress_values.empty());
  10576. }
  10577. TEST(UploadProgressTest, PostContentProviderProgress) {
  10578. TestContentProviderUploadProgress(
  10579. [](Server &svr) {
  10580. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10581. res.set_content("provider received", "text/plain");
  10582. });
  10583. },
  10584. [](Client &cli, UploadProgress progress_callback) {
  10585. return cli.Post(
  10586. "/test", 9,
  10587. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10588. sink.os << "test data";
  10589. return true;
  10590. },
  10591. "text/plain", progress_callback);
  10592. });
  10593. }
  10594. // Helper function for multipart upload progress tests
  10595. template <typename SetupHandler, typename ClientCall>
  10596. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10597. ClientCall &&client_call,
  10598. const string &endpoint) {
  10599. Server svr;
  10600. setup_handler(svr);
  10601. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10602. auto se = detail::scope_exit([&] {
  10603. svr.stop();
  10604. t.join();
  10605. });
  10606. svr.wait_until_ready();
  10607. Client cli(HOST, PORT);
  10608. vector<uint64_t> progress_values;
  10609. UploadFormDataItems items = {
  10610. {"field1", "value1", "", ""},
  10611. {"field2", "longer value for progress tracking test", "", ""},
  10612. {"file1", "file content data for upload progress", "test.txt",
  10613. "text/plain"}};
  10614. auto res = client_call(cli, endpoint, items,
  10615. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10616. progress_values.push_back(current);
  10617. return true;
  10618. });
  10619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10620. EXPECT_EQ(200, res->status);
  10621. EXPECT_FALSE(progress_values.empty());
  10622. }
  10623. TEST(UploadProgressTest, PostMultipartProgress) {
  10624. TestMultipartUploadProgress(
  10625. [](Server &svr) {
  10626. svr.Post("/multipart", [](const Request &req, Response &res) {
  10627. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10628. res.set_content("multipart received", "text/plain");
  10629. });
  10630. },
  10631. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10632. UploadProgress progress_callback) {
  10633. return cli.Post(endpoint, items, progress_callback);
  10634. },
  10635. "/multipart");
  10636. }
  10637. // Helper function for basic download progress tests
  10638. template <typename SetupHandler, typename ClientCall>
  10639. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10640. ClientCall &&client_call, const string &endpoint,
  10641. size_t expected_content_size) {
  10642. Server svr;
  10643. setup_handler(svr);
  10644. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10645. auto se = detail::scope_exit([&] {
  10646. svr.stop();
  10647. t.join();
  10648. });
  10649. svr.wait_until_ready();
  10650. Client cli(HOST, PORT);
  10651. vector<uint64_t> progress_values;
  10652. auto res = client_call(cli, endpoint,
  10653. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10654. progress_values.push_back(current);
  10655. return true;
  10656. });
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. EXPECT_EQ(200, res->status);
  10659. EXPECT_FALSE(progress_values.empty());
  10660. EXPECT_EQ(expected_content_size, res->body.size());
  10661. }
  10662. TEST(DownloadProgressTest, GetBasic) {
  10663. TestBasicDownloadProgress(
  10664. [](Server &svr) {
  10665. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10666. string content(1000, 'D');
  10667. res.set_content(content, "text/plain");
  10668. });
  10669. },
  10670. [](Client &cli, const string &endpoint,
  10671. DownloadProgress progress_callback) {
  10672. return cli.Get(endpoint, progress_callback);
  10673. },
  10674. "/download", 1000u);
  10675. }
  10676. // Helper function for content receiver download progress tests
  10677. template <typename SetupHandler, typename ClientCall>
  10678. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10679. ClientCall &&client_call,
  10680. const string &endpoint,
  10681. size_t expected_content_size) {
  10682. Server svr;
  10683. setup_handler(svr);
  10684. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10685. auto se = detail::scope_exit([&] {
  10686. svr.stop();
  10687. t.join();
  10688. });
  10689. svr.wait_until_ready();
  10690. Client cli(HOST, PORT);
  10691. vector<uint64_t> progress_values;
  10692. string received_body;
  10693. auto res = client_call(
  10694. cli, endpoint,
  10695. [&](const char *data, size_t data_length) -> bool {
  10696. received_body.append(data, data_length);
  10697. return true;
  10698. },
  10699. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10700. progress_values.push_back(current);
  10701. return true;
  10702. });
  10703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10704. EXPECT_EQ(200, res->status);
  10705. EXPECT_FALSE(progress_values.empty());
  10706. EXPECT_EQ(expected_content_size, received_body.size());
  10707. EXPECT_TRUE(res->body.empty());
  10708. }
  10709. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10710. TestContentReceiverDownloadProgress(
  10711. [](Server &svr) {
  10712. svr.Get("/download-receiver",
  10713. [](const Request & /*req*/, Response &res) {
  10714. string content(2000, 'R');
  10715. res.set_content(content, "text/plain");
  10716. });
  10717. },
  10718. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10719. DownloadProgress progress_callback) {
  10720. return cli.Get(endpoint, content_receiver, progress_callback);
  10721. },
  10722. "/download-receiver", 2000u);
  10723. }
  10724. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10725. // A provider reaching a pass with nothing to hand over - an empty buffer
  10726. // popped off a queue, say - must not be taken to mean the body is finished.
  10727. // It used to end the loop with the terminating chunk unwritten while the
  10728. // server still considered the response complete, so the peer waited for an
  10729. // end that never arrived.
  10730. Server svr;
  10731. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10732. auto step = std::make_shared<int>(0);
  10733. res.set_chunked_content_provider("text/plain",
  10734. [step](size_t /*offset*/, DataSink &sink) {
  10735. switch ((*step)++) {
  10736. case 0: sink.write("", 0); break;
  10737. case 1: sink.write("hello", 5); break;
  10738. default: sink.done(); break;
  10739. }
  10740. return true;
  10741. });
  10742. });
  10743. auto port = svr.bind_to_any_port(HOST);
  10744. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10745. auto listen_se = detail::scope_exit([&] {
  10746. svr.stop();
  10747. listen_thread.join();
  10748. ASSERT_FALSE(svr.is_running());
  10749. });
  10750. svr.wait_until_ready();
  10751. Client cli(HOST, port);
  10752. // Without the fix the body is never terminated, so bound the wait rather
  10753. // than letting the test hang on the default read timeout.
  10754. cli.set_read_timeout(5, 0);
  10755. auto res = cli.Get("/stream");
  10756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10757. EXPECT_EQ(StatusCode::OK_200, res->status);
  10758. EXPECT_EQ("hello", res->body);
  10759. }
  10760. TEST(StreamingTest, NoContentLengthStreaming) {
  10761. Server svr;
  10762. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10763. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10764. if (offset < 6) {
  10765. sink.os << (offset < 3 ? "a" : "b");
  10766. } else {
  10767. sink.done();
  10768. }
  10769. return true;
  10770. });
  10771. });
  10772. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10773. auto listen_se = detail::scope_exit([&] {
  10774. svr.stop();
  10775. listen_thread.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. svr.wait_until_ready();
  10779. Client client(HOST, PORT);
  10780. auto get_thread = std::thread([&client]() {
  10781. std::string s;
  10782. auto res =
  10783. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10784. s += std::string(data, len);
  10785. return true;
  10786. });
  10787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10788. EXPECT_EQ(StatusCode::OK_200, res->status);
  10789. EXPECT_EQ("aaabbb", s);
  10790. });
  10791. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10792. // Give GET time to get a few messages.
  10793. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10794. }
  10795. TEST(MountTest, Unmount) {
  10796. Server svr;
  10797. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10798. auto se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. listen_thread.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. Client cli("localhost", PORT);
  10805. svr.set_mount_point("/mount2", "./www2");
  10806. auto res = cli.Get("/");
  10807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10808. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10809. res = cli.Get("/mount2/dir/test.html");
  10810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10811. EXPECT_EQ(StatusCode::OK_200, res->status);
  10812. svr.set_mount_point("/", "./www");
  10813. res = cli.Get("/dir/");
  10814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10815. EXPECT_EQ(StatusCode::OK_200, res->status);
  10816. svr.remove_mount_point("/");
  10817. res = cli.Get("/dir/");
  10818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10819. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10820. svr.remove_mount_point("/mount2");
  10821. res = cli.Get("/mount2/dir/test.html");
  10822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10823. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10824. }
  10825. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10826. Server svr;
  10827. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10828. svr.Get("/api/hello", [](const Request &, Response &res) {
  10829. res.set_content("api", "text/plain");
  10830. });
  10831. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10832. auto se = detail::scope_exit([&] {
  10833. svr.stop();
  10834. listen_thread.join();
  10835. ASSERT_FALSE(svr.is_running());
  10836. });
  10837. svr.wait_until_ready();
  10838. Client cli(HOST, PORT);
  10839. auto res = cli.Get("/dir/test.html");
  10840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10841. EXPECT_EQ(StatusCode::OK_200, res->status);
  10842. res = cli.Get("/api/hello");
  10843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10844. EXPECT_EQ(StatusCode::OK_200, res->status);
  10845. EXPECT_EQ("api", res->body);
  10846. }
  10847. TEST(MountTest, PathSegmentBoundary) {
  10848. Server svr;
  10849. svr.set_mount_point("/mount2", "./www2");
  10850. svr.set_mount_point("/", "./www");
  10851. auto port = svr.bind_to_any_port(HOST);
  10852. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10853. auto se = detail::scope_exit([&] {
  10854. svr.stop();
  10855. listen_thread.join();
  10856. ASSERT_FALSE(svr.is_running());
  10857. });
  10858. svr.wait_until_ready();
  10859. Client cli(HOST, port);
  10860. auto res = cli.Get("/mount2/dir/test.html");
  10861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10862. EXPECT_EQ(StatusCode::OK_200, res->status);
  10863. // "/mount2" must not match part-way through a path segment.
  10864. res = cli.Get("/mount2dir/test.html");
  10865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10866. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10867. // A mount point ending in '/' keeps matching every path below it.
  10868. res = cli.Get("/dir/test.html");
  10869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10870. EXPECT_EQ(StatusCode::OK_200, res->status);
  10871. }
  10872. TEST(MountTest, Redicect) {
  10873. Server svr;
  10874. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10875. auto se = detail::scope_exit([&] {
  10876. svr.stop();
  10877. listen_thread.join();
  10878. ASSERT_FALSE(svr.is_running());
  10879. });
  10880. svr.set_mount_point("/", "./www");
  10881. svr.wait_until_ready();
  10882. Client cli("localhost", PORT);
  10883. auto res = cli.Get("/dir/");
  10884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10885. EXPECT_EQ(StatusCode::OK_200, res->status);
  10886. res = cli.Get("/dir");
  10887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10888. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10889. res = cli.Get("/file");
  10890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10891. EXPECT_EQ(StatusCode::OK_200, res->status);
  10892. res = cli.Get("/file/");
  10893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10894. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10895. cli.set_follow_location(true);
  10896. res = cli.Get("/dir");
  10897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10898. EXPECT_EQ(StatusCode::OK_200, res->status);
  10899. }
  10900. TEST(MountTest, MultibytesPathName) {
  10901. Server svr;
  10902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10903. auto se = detail::scope_exit([&] {
  10904. svr.stop();
  10905. listen_thread.join();
  10906. ASSERT_FALSE(svr.is_running());
  10907. });
  10908. svr.set_mount_point("/", "./www");
  10909. svr.wait_until_ready();
  10910. Client cli("localhost", PORT);
  10911. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10913. EXPECT_EQ(StatusCode::OK_200, res->status);
  10914. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10915. }
  10916. // A mount point serves no path with an empty segment or one ending in '.' or
  10917. // a space, so a guard in the pre-routing handler sees the path of every file
  10918. // that is served
  10919. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10920. Server svr;
  10921. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10922. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10923. if (req.path == "/dir/test.html") {
  10924. res.status = StatusCode::Unauthorized_401;
  10925. return Server::HandlerResponse::Handled;
  10926. }
  10927. return Server::HandlerResponse::Unhandled;
  10928. });
  10929. auto port = svr.bind_to_any_port(HOST);
  10930. ASSERT_LT(0, port);
  10931. thread t = thread([&] { svr.listen_after_bind(); });
  10932. auto se = detail::scope_exit([&] {
  10933. svr.stop();
  10934. t.join();
  10935. ASSERT_FALSE(svr.is_running());
  10936. });
  10937. svr.wait_until_ready();
  10938. Client cli(HOST, port);
  10939. for (auto path :
  10940. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10941. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10942. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  10943. "/dir/test.html%3A%3A$DATA"}) {
  10944. SCOPED_TRACE(path);
  10945. auto res = cli.Get(path);
  10946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10947. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10948. }
  10949. }
  10950. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10951. Server svr;
  10952. svr.set_mount_point("/", "./www");
  10953. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10954. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10955. auto port = svr.bind_to_any_port(HOST);
  10956. ASSERT_GT(port, 0);
  10957. thread t = thread([&] { svr.listen_after_bind(); });
  10958. auto se = detail::scope_exit([&] {
  10959. svr.stop();
  10960. t.join();
  10961. ASSERT_FALSE(svr.is_running());
  10962. });
  10963. svr.wait_until_ready();
  10964. Client cli(HOST, port);
  10965. auto res = cli.Get("/dir/test.abcde");
  10966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10967. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10968. res = cli.Get("/dir/test.html");
  10969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10970. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10971. }
  10972. #ifdef _WIN32
  10973. // Issue #2435: mmap::open() must succeed even when another handle holds
  10974. // the file open for writing (e.g. an active log file).
  10975. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10976. const char *path = "mmap_concurrent_writer_test.txt";
  10977. const char *content = "hello";
  10978. {
  10979. std::ofstream f(path, std::ios::binary);
  10980. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10981. }
  10982. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10983. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10984. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10985. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10986. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10987. detail::mmap m(path);
  10988. ASSERT_TRUE(m.is_open());
  10989. EXPECT_EQ(strlen(content), m.size());
  10990. char buf[8];
  10991. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10992. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10993. }
  10994. #endif
  10995. #ifndef _WIN32
  10996. // A directory or a device has no size to serve.
  10997. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10998. const char *path = "./mmap_not_regular_test_dir";
  10999. ASSERT_EQ(0, ::mkdir(path, 0755));
  11000. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11001. for (auto p : {path, "/dev/null"}) {
  11002. detail::mmap m(p);
  11003. EXPECT_FALSE(m.is_open()) << p;
  11004. EXPECT_EQ(0U, m.size()) << p;
  11005. }
  11006. Server svr;
  11007. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11008. res.set_file_content("/dev/null");
  11009. });
  11010. auto port = svr.bind_to_any_port(HOST);
  11011. thread t = thread([&] { svr.listen_after_bind(); });
  11012. auto se = detail::scope_exit([&] {
  11013. svr.stop();
  11014. t.join();
  11015. });
  11016. svr.wait_until_ready();
  11017. auto res = Client(HOST, port).Get("/null");
  11018. ASSERT_TRUE(res);
  11019. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11020. }
  11021. #endif
  11022. #ifdef __linux__
  11023. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11024. TEST(MmapTest, FileIsNotMapped) {
  11025. const char *path = "mmap_not_mapped_test.txt";
  11026. {
  11027. std::ofstream f(path, std::ios::binary);
  11028. f << "hello";
  11029. }
  11030. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11031. detail::mmap m(path);
  11032. ASSERT_TRUE(m.is_open());
  11033. std::ifstream maps("/proc/self/maps");
  11034. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11035. std::istreambuf_iterator<char>());
  11036. EXPECT_EQ(std::string::npos, mappings.find(path));
  11037. }
  11038. #endif
  11039. TEST(KeepAliveTest, ReadTimeout) {
  11040. Server svr;
  11041. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11042. std::this_thread::sleep_for(std::chrono::seconds(2));
  11043. res.set_content("a", "text/plain");
  11044. });
  11045. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11046. res.set_content("b", "text/plain");
  11047. });
  11048. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11049. auto se = detail::scope_exit([&] {
  11050. svr.stop();
  11051. listen_thread.join();
  11052. ASSERT_FALSE(svr.is_running());
  11053. });
  11054. svr.wait_until_ready();
  11055. Client cli("localhost", PORT);
  11056. cli.set_keep_alive(true);
  11057. cli.set_read_timeout(std::chrono::seconds(1));
  11058. auto resa = cli.Get("/a");
  11059. ASSERT_FALSE(resa);
  11060. EXPECT_EQ(Error::Read, resa.error());
  11061. auto resb = cli.Get("/b");
  11062. ASSERT_TRUE(resb);
  11063. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11064. EXPECT_EQ("b", resb->body);
  11065. }
  11066. TEST(KeepAliveTest, MaxCount) {
  11067. size_t keep_alive_max_count = 3;
  11068. Server svr;
  11069. svr.set_keep_alive_max_count(keep_alive_max_count);
  11070. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11071. res.set_content("Hello World!", "text/plain");
  11072. });
  11073. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11074. auto se = detail::scope_exit([&] {
  11075. svr.stop();
  11076. listen_thread.join();
  11077. ASSERT_FALSE(svr.is_running());
  11078. });
  11079. svr.wait_until_ready();
  11080. Client cli(HOST, PORT);
  11081. cli.set_keep_alive(true);
  11082. for (size_t i = 0; i < 5; i++) {
  11083. auto result = cli.Get("/hi");
  11084. ASSERT_TRUE(result);
  11085. EXPECT_EQ(StatusCode::OK_200, result->status);
  11086. if (i == keep_alive_max_count - 1) {
  11087. EXPECT_EQ("close", result->get_header_value("Connection"));
  11088. } else {
  11089. EXPECT_FALSE(result->has_header("Connection"));
  11090. }
  11091. }
  11092. }
  11093. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11094. // can pull the next one into the server's buffer. The server must serve it
  11095. // without waiting for the socket to become readable again. The keep-alive
  11096. // timeout outlasts the client's read timeout, so a request left waiting for it
  11097. // shows up as a missing response.
  11098. static void serve_pipelining_routes(Server &svr,
  11099. const std::function<void(int)> &client) {
  11100. svr.set_keep_alive_timeout(5);
  11101. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11102. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11103. });
  11104. svr.Post("/echo", [](const Request &req, Response &res) {
  11105. res.set_content("echo " + req.body, "text/plain");
  11106. });
  11107. auto port = svr.bind_to_any_port(HOST);
  11108. thread t = thread([&] { svr.listen_after_bind(); });
  11109. auto se = detail::scope_exit([&] {
  11110. svr.stop();
  11111. t.join();
  11112. });
  11113. svr.wait_until_ready();
  11114. client(port);
  11115. }
  11116. static std::string
  11117. send_pipelined_requests(const std::vector<std::string> &parts) {
  11118. Server svr;
  11119. std::string res;
  11120. serve_pipelining_routes(svr, [&](int port) {
  11121. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11122. });
  11123. return res;
  11124. }
  11125. static void expect_in_order(const std::string &res,
  11126. const std::vector<std::string> &bodies) {
  11127. size_t pos = 0;
  11128. for (const auto &body : bodies) {
  11129. pos = res.find(body, pos);
  11130. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11131. pos += body.size();
  11132. }
  11133. }
  11134. TEST(KeepAliveTest, PipelinedRequests) {
  11135. auto res = send_pipelined_requests(
  11136. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11137. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11138. "Content-Length: 4\r\n\r\nbody"
  11139. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11140. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11141. }
  11142. // The second request starts in the server's buffer and ends on the socket.
  11143. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11144. auto res =
  11145. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11146. "GET /hi/2 HTTP/1.1\r\nHo",
  11147. "st: localhost\r\nConnection: close\r\n\r\n"});
  11148. expect_in_order(res, {"hi 1", "hi 2"});
  11149. }
  11150. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11151. // CRLF after a body does not turn into a 400 for the next request.
  11152. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11153. auto res = send_pipelined_requests(
  11154. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11155. "Content-Length: 4\r\n\r\nbody\r\n"
  11156. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11157. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11158. expect_in_order(res, {"echo body", "hi 2"});
  11159. }
  11160. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11161. // must not be served as the next request.
  11162. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11163. auto res = send_pipelined_requests(
  11164. {"INVALID REQUEST LINE\r\n\r\n"
  11165. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11166. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11167. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11168. }
  11169. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11170. // Over TLS, the next request is held by the TLS library as already decrypted
  11171. // data rather than on the socket.
  11172. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11174. std::string res;
  11175. serve_pipelining_routes(svr, [&](int port) {
  11176. // One part, so all three requests arrive in one TLS record
  11177. EXPECT_TRUE(send_ssl_request_in_parts(
  11178. 2,
  11179. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11180. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11181. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11182. &res, port));
  11183. });
  11184. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11185. }
  11186. #endif
  11187. TEST(KeepAliveTest, Issue1041) {
  11188. Server svr;
  11189. svr.set_keep_alive_timeout(3);
  11190. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11191. res.set_content("Hello World!", "text/plain");
  11192. });
  11193. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11194. auto se = detail::scope_exit([&] {
  11195. svr.stop();
  11196. listen_thread.join();
  11197. ASSERT_FALSE(svr.is_running());
  11198. });
  11199. svr.wait_until_ready();
  11200. Client cli(HOST, PORT);
  11201. cli.set_keep_alive(true);
  11202. auto result = cli.Get("/hi");
  11203. ASSERT_TRUE(result);
  11204. EXPECT_EQ(StatusCode::OK_200, result->status);
  11205. std::this_thread::sleep_for(std::chrono::seconds(5));
  11206. result = cli.Get("/hi");
  11207. ASSERT_TRUE(result);
  11208. EXPECT_EQ(StatusCode::OK_200, result->status);
  11209. }
  11210. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11211. Server svr;
  11212. svr.set_keep_alive_max_count(0);
  11213. std::set<int> remote_ports;
  11214. svr.Get("/hi", [&](const Request &req, Response &res) {
  11215. remote_ports.insert(req.remote_port);
  11216. res.set_content("hi", "text/plain");
  11217. });
  11218. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11219. auto se = detail::scope_exit([&] {
  11220. svr.stop();
  11221. listen_thread.join();
  11222. ASSERT_FALSE(svr.is_running());
  11223. });
  11224. svr.wait_until_ready();
  11225. Client cli(HOST, PORT);
  11226. cli.set_keep_alive(true);
  11227. for (int i = 0; i < 3; i++) {
  11228. auto res = cli.Get("/hi");
  11229. ASSERT_TRUE(res);
  11230. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11231. }
  11232. // All three over one connection
  11233. EXPECT_EQ(1u, remote_ports.size());
  11234. }
  11235. TEST(KeepAliveTest, Issue1959) {
  11236. Server svr;
  11237. svr.set_keep_alive_timeout(5);
  11238. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11239. res.set_content("a", "text/plain");
  11240. });
  11241. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11242. auto se = detail::scope_exit([&] {
  11243. if (!svr.is_running()) return;
  11244. svr.stop();
  11245. listen_thread.join();
  11246. ASSERT_FALSE(svr.is_running());
  11247. });
  11248. svr.wait_until_ready();
  11249. Client cli("localhost", PORT);
  11250. cli.set_keep_alive(true);
  11251. using namespace std::chrono;
  11252. auto start = steady_clock::now();
  11253. cli.Get("/a");
  11254. svr.stop();
  11255. listen_thread.join();
  11256. auto end = steady_clock::now();
  11257. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11258. EXPECT_LT(elapsed, 5000);
  11259. }
  11260. #ifdef CPPHTTPLIB_SSL_ENABLED
  11261. TEST(KeepAliveTest, SSLClientReconnection) {
  11262. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11263. ASSERT_TRUE(svr.is_valid());
  11264. svr.set_keep_alive_timeout(1);
  11265. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11266. res.set_content("Hello World!", "text/plain");
  11267. });
  11268. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11269. auto se = detail::scope_exit([&] {
  11270. svr.stop();
  11271. listen_thread.join();
  11272. ASSERT_FALSE(svr.is_running());
  11273. });
  11274. svr.wait_until_ready();
  11275. SSLClient cli(HOST, PORT);
  11276. cli.enable_server_certificate_verification(false);
  11277. cli.set_keep_alive(true);
  11278. auto result = cli.Get("/hi");
  11279. ASSERT_TRUE(result);
  11280. EXPECT_EQ(StatusCode::OK_200, result->status);
  11281. result = cli.Get("/hi");
  11282. ASSERT_TRUE(result);
  11283. EXPECT_EQ(StatusCode::OK_200, result->status);
  11284. std::this_thread::sleep_for(std::chrono::seconds(2));
  11285. // Recoonect
  11286. result = cli.Get("/hi");
  11287. ASSERT_TRUE(result);
  11288. EXPECT_EQ(StatusCode::OK_200, result->status);
  11289. result = cli.Get("/hi");
  11290. ASSERT_TRUE(result);
  11291. EXPECT_EQ(StatusCode::OK_200, result->status);
  11292. }
  11293. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11295. ASSERT_TRUE(svr.is_valid());
  11296. svr.set_keep_alive_timeout(1);
  11297. std::string content = "reconnect";
  11298. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11299. res.set_content("Hello World!", "text/plain");
  11300. });
  11301. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11302. auto se = detail::scope_exit([&] {
  11303. svr.stop();
  11304. listen_thread.join();
  11305. ASSERT_FALSE(svr.is_running());
  11306. });
  11307. svr.wait_until_ready();
  11308. SSLClient cli(HOST, PORT);
  11309. cli.enable_server_certificate_verification(false);
  11310. cli.set_keep_alive(true);
  11311. auto result = cli.Post(
  11312. "/hi", content.size(),
  11313. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11314. sink.write(content.c_str(), content.size());
  11315. return true;
  11316. },
  11317. "text/plain");
  11318. ASSERT_TRUE(result);
  11319. EXPECT_EQ(200, result->status);
  11320. std::this_thread::sleep_for(std::chrono::seconds(2));
  11321. // Recoonect
  11322. result = cli.Post(
  11323. "/hi", content.size(),
  11324. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11325. sink.write(content.c_str(), content.size());
  11326. return true;
  11327. },
  11328. "text/plain");
  11329. ASSERT_TRUE(result);
  11330. EXPECT_EQ(200, result->status);
  11331. result = cli.Post(
  11332. "/hi", content.size(),
  11333. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11334. sink.write(content.c_str(), content.size());
  11335. return true;
  11336. },
  11337. "text/plain");
  11338. ASSERT_TRUE(result);
  11339. EXPECT_EQ(200, result->status);
  11340. }
  11341. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11342. using namespace httplib::tls;
  11343. {
  11344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11345. ASSERT_TRUE(svr.is_valid());
  11346. svr.Get("/sni", [&](const Request &req, Response &res) {
  11347. std::string expected = req.sni();
  11348. EXPECT_EQ(expected, req.get_param_value("expected"));
  11349. res.set_content("ok", "text/plain");
  11350. });
  11351. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11352. auto se = detail::scope_exit([&] {
  11353. svr.stop();
  11354. listen_thread.join();
  11355. ASSERT_FALSE(svr.is_running());
  11356. });
  11357. svr.wait_until_ready();
  11358. {
  11359. SSLClient cli("localhost", PORT);
  11360. cli.enable_server_certificate_verification(false);
  11361. auto res = cli.Get("/sni?expected=localhost");
  11362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11363. }
  11364. {
  11365. SSLClient cli("::1", PORT);
  11366. cli.enable_server_certificate_verification(false);
  11367. auto res = cli.Get("/sni?expected=");
  11368. // NOTE: This may fail if the server is listening on IPv4 only
  11369. // (e.g., when localhost resolves to 127.0.0.1 only)
  11370. if (res) {
  11371. EXPECT_EQ(StatusCode::OK_200, res->status);
  11372. } else {
  11373. EXPECT_EQ(Error::Connection, res.error());
  11374. }
  11375. }
  11376. }
  11377. }
  11378. // The SNI of a failed handshake does not reach the next connection that the
  11379. // same worker thread serves
  11380. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11381. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11382. ASSERT_TRUE(svr.is_valid());
  11383. svr.new_task_queue = [] { return new ThreadPool(1); };
  11384. svr.Get("/sni", [](const Request &req, Response &res) {
  11385. res.set_content(req.sni(), "text/plain");
  11386. });
  11387. auto port = svr.bind_to_any_port("127.0.0.1");
  11388. ASSERT_LT(0, port);
  11389. thread t = thread([&] { svr.listen_after_bind(); });
  11390. auto se = detail::scope_exit([&] {
  11391. svr.stop();
  11392. t.join();
  11393. ASSERT_FALSE(svr.is_running());
  11394. });
  11395. svr.wait_until_ready();
  11396. {
  11397. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11398. SSLClient cli("localhost", port);
  11399. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11400. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11401. auto res = cli.Get("/sni");
  11402. ASSERT_FALSE(res);
  11403. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11404. }
  11405. // An IP host sends no SNI (RFC 6066)
  11406. SSLClient cli("127.0.0.1", port);
  11407. cli.enable_server_certificate_verification(false);
  11408. auto res = cli.Get("/sni");
  11409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11410. EXPECT_EQ("", res->body);
  11411. }
  11412. #endif
  11413. TEST(ClientProblemDetectionTest, ContentProvider) {
  11414. Server svr;
  11415. size_t content_length = 1024 * 1024;
  11416. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11417. res.set_content_provider(
  11418. content_length, "text/plain",
  11419. [&](size_t offset, size_t length, DataSink &sink) {
  11420. auto out_len = std::min(length, static_cast<size_t>(1024));
  11421. std::string out(out_len, '@');
  11422. sink.write(out.data(), out_len);
  11423. return offset < 4096;
  11424. },
  11425. [](bool success) { ASSERT_FALSE(success); });
  11426. });
  11427. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11428. res.set_content_provider(
  11429. 0, "text/plain",
  11430. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11431. EXPECT_TRUE(false);
  11432. return true;
  11433. },
  11434. [](bool success) { ASSERT_FALSE(success); });
  11435. });
  11436. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11437. auto se = detail::scope_exit([&] {
  11438. svr.stop();
  11439. listen_thread.join();
  11440. ASSERT_FALSE(svr.is_running());
  11441. });
  11442. svr.wait_until_ready();
  11443. Client cli("localhost", PORT);
  11444. {
  11445. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11446. size_t /*data_length*/) { return false; });
  11447. ASSERT_FALSE(res);
  11448. }
  11449. {
  11450. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11451. size_t /*data_length*/) { return false; });
  11452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11453. }
  11454. }
  11455. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11456. // A provider that reports success without writing anything and without
  11457. // calling done() used to be handed the same offset and length again on every
  11458. // pass, so it spun for as long as the peer stayed connected.
  11459. Server svr;
  11460. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11461. res.set_content("ok", "text/plain");
  11462. });
  11463. auto port = svr.bind_to_any_port(HOST);
  11464. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11465. auto se = detail::scope_exit([&] {
  11466. svr.stop();
  11467. listen_thread.join();
  11468. ASSERT_FALSE(svr.is_running());
  11469. });
  11470. svr.wait_until_ready();
  11471. std::atomic<int> call_count{0};
  11472. Client cli(HOST, port);
  11473. auto res = cli.Post(
  11474. "/", 1024,
  11475. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11476. // Give up after enough passes to show the spin, so that losing the
  11477. // check below fails this test instead of hanging it.
  11478. return ++call_count < 100;
  11479. },
  11480. "text/plain");
  11481. ASSERT_FALSE(res);
  11482. EXPECT_EQ(Error::Write, res.error());
  11483. EXPECT_EQ(1, call_count.load());
  11484. }
  11485. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11486. // A writer only has to assign `write`. The other three used to be left as
  11487. // empty std::functions, so a provider calling one threw
  11488. // std::bad_function_call out of the thread running it and took the whole
  11489. // process down.
  11490. DataSink sink;
  11491. std::string written;
  11492. sink.write = [&](const char *data, size_t data_len) {
  11493. written.append(data, data_len);
  11494. return true;
  11495. };
  11496. EXPECT_TRUE(sink.is_writable());
  11497. sink.done();
  11498. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11499. EXPECT_TRUE(written.empty());
  11500. }
  11501. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11502. // A sink that cannot carry trailers still has to finish.
  11503. DataSink sink;
  11504. auto done_count = 0;
  11505. sink.done = [&]() { done_count++; };
  11506. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11507. EXPECT_EQ(1, done_count);
  11508. }
  11509. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11510. Server svr;
  11511. const std::string body(4096, 'x');
  11512. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11513. res.set_content_provider(body.size(), "text/plain",
  11514. [&](size_t offset, size_t length, DataSink &sink) {
  11515. sink.write(body.data() + offset, length);
  11516. sink.done();
  11517. return true;
  11518. });
  11519. });
  11520. auto port = svr.bind_to_any_port(HOST);
  11521. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11522. auto se = detail::scope_exit([&] {
  11523. svr.stop();
  11524. listen_thread.join();
  11525. ASSERT_FALSE(svr.is_running());
  11526. });
  11527. svr.wait_until_ready();
  11528. Client cli(HOST, port);
  11529. auto res = cli.Get("/");
  11530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11531. EXPECT_EQ(StatusCode::OK_200, res->status);
  11532. EXPECT_EQ(body, res->body);
  11533. }
  11534. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11535. Server svr;
  11536. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11537. res.set_content_provider(
  11538. 1024, "text/plain",
  11539. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11540. sink.write("hello", 5);
  11541. sink.done(); // short of the 1024 bytes the response promised
  11542. return true;
  11543. });
  11544. });
  11545. auto port = svr.bind_to_any_port(HOST);
  11546. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11547. auto se = detail::scope_exit([&] {
  11548. svr.stop();
  11549. listen_thread.join();
  11550. ASSERT_FALSE(svr.is_running());
  11551. });
  11552. svr.wait_until_ready();
  11553. Client cli(HOST, port);
  11554. cli.set_read_timeout(5, 0);
  11555. // The response is short of its Content-Length, so the client cannot read a
  11556. // complete body. What matters is that this returns at all: a no-op done()
  11557. // would leave the writer looping over a provider that never makes progress.
  11558. auto res = cli.Get("/");
  11559. EXPECT_FALSE(res);
  11560. }
  11561. // Read as the next response by a peer that sees it after a framed body.
  11562. static const std::string smuggled_response =
  11563. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11564. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11565. Server svr;
  11566. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11567. res.set_content_provider(
  11568. 5, "text/plain",
  11569. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11570. auto data = "AAAAA" + smuggled_response;
  11571. sink.write(data.data(), data.size());
  11572. return true;
  11573. });
  11574. });
  11575. thread t = thread([&] { svr.listen(HOST, PORT); });
  11576. auto se = detail::scope_exit([&] {
  11577. svr.stop();
  11578. t.join();
  11579. ASSERT_FALSE(svr.is_running());
  11580. });
  11581. svr.wait_until_ready();
  11582. std::string resp;
  11583. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11584. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11585. resp.clear();
  11586. ASSERT_TRUE(send_request(
  11587. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11588. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11589. }
  11590. TEST(NoContentTest, BodyIsNotSent) {
  11591. Server svr;
  11592. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11593. res.status = StatusCode::NoContent_204;
  11594. res.set_content(smuggled_response, "text/plain");
  11595. });
  11596. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11597. res.status = StatusCode::NotModified_304;
  11598. res.set_chunked_content_provider(
  11599. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11600. sink.write(smuggled_response.data(), smuggled_response.size());
  11601. sink.done();
  11602. return true;
  11603. });
  11604. });
  11605. thread t = thread([&] { svr.listen(HOST, PORT); });
  11606. auto se = detail::scope_exit([&] {
  11607. svr.stop();
  11608. t.join();
  11609. ASSERT_FALSE(svr.is_running());
  11610. });
  11611. svr.wait_until_ready();
  11612. for (auto path : {"/204", "/304"}) {
  11613. std::string resp;
  11614. ASSERT_TRUE(send_request(
  11615. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11616. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11617. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11618. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11619. }
  11620. }
  11621. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11622. Server svr;
  11623. std::atomic<bool> smuggled(false);
  11624. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11625. res.set_content("ok", "text/plain");
  11626. });
  11627. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11628. smuggled = true;
  11629. });
  11630. auto port = svr.bind_to_any_port(HOST);
  11631. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11632. auto se = detail::scope_exit([&] {
  11633. svr.stop();
  11634. listen_thread.join();
  11635. ASSERT_FALSE(svr.is_running());
  11636. });
  11637. svr.wait_until_ready();
  11638. // What follows the body would be read as the next request.
  11639. Client cli(HOST, port);
  11640. auto res = cli.Post(
  11641. "/", 5,
  11642. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11643. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11644. sink.write(data.data(), data.size());
  11645. return true;
  11646. },
  11647. "text/plain");
  11648. ASSERT_FALSE(res);
  11649. EXPECT_EQ(Error::Write, res.error());
  11650. EXPECT_FALSE(smuggled);
  11651. }
  11652. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11653. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11654. // The compressed path builds the whole body before connecting, so this
  11655. // fails client-side and never reaches a server.
  11656. Client cli(HOST, PORT);
  11657. cli.set_compress(true);
  11658. auto res = cli.Post(
  11659. "/", 1024,
  11660. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11661. sink.write("hello", 5);
  11662. sink.done(); // short of the 1024 bytes the request announced
  11663. return true;
  11664. },
  11665. "text/plain");
  11666. ASSERT_FALSE(res);
  11667. EXPECT_EQ(Error::Write, res.error());
  11668. }
  11669. #endif
  11670. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11671. Server svr;
  11672. svr.set_error_handler([](Request const &, Response &res) -> void {
  11673. res.set_chunked_content_provider(
  11674. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11675. sink.os << "hello";
  11676. sink.os << "world";
  11677. sink.done();
  11678. return true;
  11679. });
  11680. });
  11681. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11682. auto se = detail::scope_exit([&] {
  11683. svr.stop();
  11684. listen_thread.join();
  11685. ASSERT_FALSE(svr.is_running());
  11686. });
  11687. svr.wait_until_ready();
  11688. Client cli("localhost", PORT);
  11689. auto res = cli.Get("/");
  11690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11691. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11692. EXPECT_EQ("helloworld", res->body);
  11693. }
  11694. // A body set after a content provider must replace it, not be sent through it.
  11695. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11696. Server svr;
  11697. svr.set_mount_point("/", "./www");
  11698. svr.set_file_request_handler([](const Request &req, Response &res) {
  11699. if (req.path == "/dir/test.html") {
  11700. res.status = StatusCode::Forbidden_403;
  11701. res.set_content(std::string(5000, 'D'), "text/plain");
  11702. } else if (req.path == "/file") {
  11703. res.status = StatusCode::Forbidden_403;
  11704. res.body = "Denied";
  11705. }
  11706. });
  11707. auto port = svr.bind_to_any_port(HOST);
  11708. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. t.join();
  11712. ASSERT_FALSE(svr.is_running());
  11713. });
  11714. svr.wait_until_ready();
  11715. Client cli(HOST, port);
  11716. {
  11717. auto res = cli.Get("/dir/test.html");
  11718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11719. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11720. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11721. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11722. }
  11723. {
  11724. auto res = cli.Get("/file");
  11725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11726. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11727. EXPECT_EQ("Denied", res->body);
  11728. }
  11729. {
  11730. auto res = cli.Get("/dir/index.html");
  11731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11732. EXPECT_EQ(StatusCode::OK_200, res->status);
  11733. EXPECT_EQ(0U, res->body.find("<html>"));
  11734. }
  11735. }
  11736. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11737. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11738. Server svr;
  11739. std::vector<bool> released;
  11740. std::mutex released_mutex;
  11741. auto releaser = [&](bool success) {
  11742. std::lock_guard<std::mutex> guard(released_mutex);
  11743. released.push_back(success);
  11744. };
  11745. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11746. return sink.write(&"hello"[offset], length);
  11747. };
  11748. svr.Get("/sized", [&](const Request &, Response &res) {
  11749. res.status = StatusCode::NotFound_404;
  11750. res.set_content_provider(5, "text/plain", provider, releaser);
  11751. });
  11752. svr.Get("/chunked", [&](const Request &, Response &res) {
  11753. res.status = StatusCode::ServiceUnavailable_503;
  11754. res.set_chunked_content_provider(
  11755. "text/plain",
  11756. [](size_t, DataSink &sink) {
  11757. sink.os << "chunk";
  11758. sink.done();
  11759. return true;
  11760. },
  11761. releaser);
  11762. });
  11763. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11764. res.set_content_provider(5, "text/plain", provider, releaser);
  11765. throw std::runtime_error("after the provider");
  11766. });
  11767. svr.set_error_handler([](const Request &req, Response &res) {
  11768. // Leave the exception handler's content to it.
  11769. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11770. res.set_content(std::string(1000, 'E'), "text/html");
  11771. return Server::HandlerResponse::Handled;
  11772. });
  11773. svr.set_exception_handler(
  11774. [](const Request &, Response &res, std::exception_ptr) {
  11775. res.status = StatusCode::InternalServerError_500;
  11776. res.set_content(std::string(1000, 'X'), "text/html");
  11777. });
  11778. auto port = svr.bind_to_any_port(HOST);
  11779. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11780. auto se = detail::scope_exit([&] {
  11781. svr.stop();
  11782. t.join();
  11783. ASSERT_FALSE(svr.is_running());
  11784. });
  11785. svr.wait_until_ready();
  11786. Client cli(HOST, port);
  11787. {
  11788. auto res = cli.Get("/sized");
  11789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11790. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11791. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11792. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11793. }
  11794. {
  11795. auto res = cli.Get("/chunked");
  11796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11797. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11798. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11799. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11800. }
  11801. {
  11802. auto res = cli.Get("/throw");
  11803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11804. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11805. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11806. }
  11807. std::lock_guard<std::mutex> guard(released_mutex);
  11808. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11809. }
  11810. #endif
  11811. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11812. Server svr;
  11813. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11814. return sink.write(&"abc"[offset], length);
  11815. };
  11816. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11817. res.set_file_content("./www/dir/test.html");
  11818. res.set_content("body", "text/plain");
  11819. });
  11820. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11821. res.set_content(std::string(100, 'B'), "text/plain");
  11822. res.set_file_content("./www/dir/test.html");
  11823. });
  11824. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11825. res.set_content(std::string(100, 'B'), "text/plain");
  11826. res.set_content_provider(3, "text/x-provider", abc);
  11827. });
  11828. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11829. res.set_content_provider(3, "text/x-provider", abc);
  11830. res.set_content(std::string(100, 'B'), "text/plain");
  11831. });
  11832. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11833. res.set_content_provider(3, "text/x-provider", abc);
  11834. res.set_file_content("./www/dir/test.html", "text/x-file");
  11835. });
  11836. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11837. res.set_file_content("./www/dir/test.html");
  11838. res.set_header("Content-Type", "text/x-handler");
  11839. });
  11840. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11841. res.set_content_provider(3, "text/plain", abc);
  11842. res.body = "direct";
  11843. });
  11844. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11845. res.set_file_content("./www/dir/test.html");
  11846. res.body = "direct";
  11847. });
  11848. auto port = svr.bind_to_any_port(HOST);
  11849. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11850. auto se = detail::scope_exit([&] {
  11851. svr.stop();
  11852. t.join();
  11853. ASSERT_FALSE(svr.is_running());
  11854. });
  11855. svr.wait_until_ready();
  11856. Client cli(HOST, port);
  11857. auto expect_body = [&](const char *path, const std::string &body,
  11858. const std::string &type) {
  11859. // Uncompressed, so Content-Length can be compared with the body.
  11860. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11861. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11862. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11863. EXPECT_EQ(body, res->body) << path;
  11864. EXPECT_EQ(std::to_string(body.size()),
  11865. res->get_header_value("Content-Length"))
  11866. << path;
  11867. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11868. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11869. };
  11870. expect_body("/file-then-body", "body", "text/plain");
  11871. expect_body("/body-then-file", "test.html", "text/html");
  11872. expect_body("/body-then-provider", "abc", "text/x-provider");
  11873. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11874. expect_body("/provider-then-file", "test.html", "text/x-file");
  11875. expect_body("/file-then-header", "test.html", "text/x-handler");
  11876. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11877. expect_body("/file-then-direct-body", "direct", "text/plain");
  11878. // Ranges are checked against the body, not the dropped provider.
  11879. {
  11880. auto res = cli.Get("/provider-then-direct-body",
  11881. Headers{{make_range_header({{1, 2}})}});
  11882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11883. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11884. EXPECT_EQ("ir", res->body);
  11885. }
  11886. {
  11887. auto res = cli.Get("/file-then-direct-body",
  11888. Headers{{make_range_header({{7, 8}})}});
  11889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11890. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11891. }
  11892. }
  11893. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11894. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11895. const char *path = "./truncated_while_served.txt";
  11896. const size_t size = 32 * 1024 * 1024;
  11897. {
  11898. std::ofstream f(path, std::ios::binary);
  11899. f << std::string(size, 'x');
  11900. }
  11901. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11902. // Over TLS, where the bytes are encrypted in this process rather than
  11903. // copied by send().
  11904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11905. svr.Get("/file", [&](const Request &, Response &res) {
  11906. res.set_file_content(path, "text/plain");
  11907. });
  11908. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11909. auto se = detail::scope_exit([&] {
  11910. svr.stop();
  11911. thread.join();
  11912. ASSERT_FALSE(svr.is_running());
  11913. });
  11914. svr.wait_until_ready();
  11915. // The file shrinks once the first bytes are in, as a rewrite in place
  11916. // would, and reading the mapping past its new end used to raise SIGBUS.
  11917. SSLClient cli(HOST, PORT);
  11918. cli.enable_server_certificate_verification(false);
  11919. size_t received = 0;
  11920. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11921. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11922. received += len;
  11923. return true;
  11924. });
  11925. EXPECT_FALSE(res);
  11926. EXPECT_LT(received, size);
  11927. }
  11928. #endif
  11929. // Forward declaration (see the base64_encode note).
  11930. namespace httplib {
  11931. namespace detail {
  11932. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11933. const std::string &content_type,
  11934. EncodingType encoding);
  11935. } // namespace detail
  11936. } // namespace httplib
  11937. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11938. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11939. ASSERT_TRUE(mm->is_open());
  11940. Response res;
  11941. detail::set_file_content_provider(res, mm, "text/html",
  11942. detail::EncodingType::None);
  11943. std::string out;
  11944. DataSink sink;
  11945. sink.write = [&](const char *d, size_t l) {
  11946. out.append(d, l);
  11947. return true;
  11948. };
  11949. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11950. EXPECT_EQ("test.html", out);
  11951. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11952. EXPECT_EQ("test.html", out);
  11953. }
  11954. TEST(LongPollingTest, ClientCloseDetection) {
  11955. Server svr;
  11956. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11957. res.set_chunked_content_provider(
  11958. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11959. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11960. sink.os << "hello";
  11961. auto count = 10;
  11962. while (count > 0 && sink.is_writable()) {
  11963. this_thread::sleep_for(chrono::milliseconds(10));
  11964. count--;
  11965. }
  11966. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11967. return true;
  11968. });
  11969. });
  11970. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11971. auto se = detail::scope_exit([&] {
  11972. svr.stop();
  11973. listen_thread.join();
  11974. ASSERT_FALSE(svr.is_running());
  11975. });
  11976. svr.wait_until_ready();
  11977. Client cli("localhost", PORT);
  11978. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11979. EXPECT_EQ("hello", string(data, data_length));
  11980. return false; // close the socket immediately.
  11981. });
  11982. ASSERT_FALSE(res);
  11983. }
  11984. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11985. Server svr;
  11986. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11987. res.set_chunked_content_provider(
  11988. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11989. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11990. sink.os << "hello";
  11991. EXPECT_TRUE(sink.os.good());
  11992. // Wait for the client to close the connection
  11993. auto count = 10;
  11994. while (count > 0 && sink.is_writable()) {
  11995. this_thread::sleep_for(chrono::milliseconds(10));
  11996. count--;
  11997. }
  11998. // After client disconnect, write repeatedly until the socket
  11999. // write actually fails (small writes may be absorbed by the
  12000. // kernel buffer)
  12001. std::string chunk(1024, 'x');
  12002. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12003. sink.os << chunk;
  12004. }
  12005. EXPECT_TRUE(sink.os.fail());
  12006. return true;
  12007. });
  12008. });
  12009. auto port = svr.bind_to_any_port("localhost");
  12010. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12011. auto se = detail::scope_exit([&] {
  12012. svr.stop();
  12013. listen_thread.join();
  12014. ASSERT_FALSE(svr.is_running());
  12015. });
  12016. svr.wait_until_ready();
  12017. Client cli("localhost", port);
  12018. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12019. EXPECT_EQ("hello", string(data, data_length));
  12020. return false; // close the socket immediately.
  12021. });
  12022. ASSERT_FALSE(res);
  12023. }
  12024. TEST(GetWithParametersTest, GetWithParameters) {
  12025. Server svr;
  12026. svr.Get("/", [&](const Request &req, Response &) {
  12027. EXPECT_EQ("world", req.get_param_value("hello"));
  12028. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12029. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12030. });
  12031. svr.Get("/params", [&](const Request &req, Response &) {
  12032. EXPECT_EQ("world", req.get_param_value("hello"));
  12033. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12034. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12035. });
  12036. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12037. EXPECT_EQ("resource-id", req.matches[1]);
  12038. EXPECT_EQ("foo", req.get_param_value("param1"));
  12039. EXPECT_EQ("bar", req.get_param_value("param2"));
  12040. });
  12041. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12042. EXPECT_EQ("user-id", req.path_params.at("id"));
  12043. EXPECT_EQ("foo", req.get_param_value("param1"));
  12044. EXPECT_EQ("bar", req.get_param_value("param2"));
  12045. });
  12046. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12047. auto se = detail::scope_exit([&] {
  12048. svr.stop();
  12049. listen_thread.join();
  12050. ASSERT_FALSE(svr.is_running());
  12051. });
  12052. svr.wait_until_ready();
  12053. {
  12054. Client cli(HOST, PORT);
  12055. Params params;
  12056. params.emplace("hello", "world");
  12057. params.emplace("hello2", "world2");
  12058. params.emplace("hello3", "world3");
  12059. auto res = cli.Get("/", params, Headers{});
  12060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12061. EXPECT_EQ(StatusCode::OK_200, res->status);
  12062. }
  12063. {
  12064. Client cli(HOST, PORT);
  12065. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12067. EXPECT_EQ(StatusCode::OK_200, res->status);
  12068. }
  12069. {
  12070. Client cli(HOST, PORT);
  12071. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12073. EXPECT_EQ(StatusCode::OK_200, res->status);
  12074. }
  12075. {
  12076. Client cli(HOST, PORT);
  12077. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12079. EXPECT_EQ(StatusCode::OK_200, res->status);
  12080. }
  12081. }
  12082. TEST(GetWithParametersTest, GetWithParameters2) {
  12083. Server svr;
  12084. svr.Get("/", [&](const Request &req, Response &res) {
  12085. auto text = req.get_param_value("hello");
  12086. res.set_content(text, "text/plain");
  12087. });
  12088. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12089. auto se = detail::scope_exit([&] {
  12090. svr.stop();
  12091. listen_thread.join();
  12092. ASSERT_FALSE(svr.is_running());
  12093. });
  12094. svr.wait_until_ready();
  12095. Client cli("localhost", PORT);
  12096. Params params;
  12097. params.emplace("hello", "world");
  12098. std::string body;
  12099. auto res = cli.Get("/", params, Headers{},
  12100. [&](const char *data, size_t data_length) {
  12101. body.append(data, data_length);
  12102. return true;
  12103. });
  12104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12105. EXPECT_EQ(StatusCode::OK_200, res->status);
  12106. EXPECT_EQ("world", body);
  12107. }
  12108. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12109. Server svr;
  12110. svr.Get("/search", [&](const Request &req, Response &res) {
  12111. auto q = req.get_param_value("q");
  12112. res.set_content(q, "text/plain");
  12113. });
  12114. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12115. auto se = detail::scope_exit([&] {
  12116. svr.stop();
  12117. listen_thread.join();
  12118. ASSERT_FALSE(svr.is_running());
  12119. });
  12120. svr.wait_until_ready();
  12121. Client cli("localhost", PORT);
  12122. // Verify that Get(path, params) works without requiring Headers argument
  12123. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12125. EXPECT_EQ(StatusCode::OK_200, res->status);
  12126. EXPECT_EQ("cpp-httplib", res->body);
  12127. }
  12128. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12129. auto host = "httpbingo.org";
  12130. auto path = std::string{"/range/32"};
  12131. #ifdef CPPHTTPLIB_SSL_ENABLED
  12132. SSLClient cli(host);
  12133. #else
  12134. Client cli(host);
  12135. #endif
  12136. cli.set_default_headers({make_range_header({{1, 10}})});
  12137. cli.set_connection_timeout(5);
  12138. {
  12139. auto res = cli.Get(path);
  12140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12141. EXPECT_EQ("bcdefghijk", res->body);
  12142. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12143. }
  12144. {
  12145. auto res = cli.Get(path);
  12146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12147. EXPECT_EQ("bcdefghijk", res->body);
  12148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12149. }
  12150. }
  12151. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12152. Server svr;
  12153. svr.set_default_headers({{"Hello", "World"}});
  12154. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12155. res.set_content("ok", "text/plain");
  12156. });
  12157. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12158. auto se = detail::scope_exit([&] {
  12159. svr.stop();
  12160. listen_thread.join();
  12161. ASSERT_FALSE(svr.is_running());
  12162. });
  12163. svr.wait_until_ready();
  12164. Client cli("localhost", PORT);
  12165. auto res = cli.Get("/");
  12166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12167. EXPECT_EQ(StatusCode::OK_200, res->status);
  12168. EXPECT_EQ("ok", res->body);
  12169. EXPECT_EQ("World", res->get_header_value("Hello"));
  12170. }
  12171. #ifdef CPPHTTPLIB_SSL_ENABLED
  12172. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12173. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12174. ASSERT_TRUE(svr.is_valid());
  12175. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12176. std::this_thread::sleep_for(std::chrono::seconds(2));
  12177. res.set_content("a", "text/plain");
  12178. });
  12179. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12180. res.set_content("b", "text/plain");
  12181. });
  12182. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12183. auto se = detail::scope_exit([&] {
  12184. svr.stop();
  12185. listen_thread.join();
  12186. ASSERT_FALSE(svr.is_running());
  12187. });
  12188. svr.wait_until_ready();
  12189. SSLClient cli("localhost", PORT);
  12190. cli.enable_server_certificate_verification(false);
  12191. cli.set_keep_alive(true);
  12192. cli.set_read_timeout(std::chrono::seconds(1));
  12193. auto resa = cli.Get("/a");
  12194. ASSERT_TRUE(!resa);
  12195. EXPECT_EQ(Error::Read, resa.error());
  12196. auto resb = cli.Get("/b");
  12197. ASSERT_TRUE(resb);
  12198. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12199. EXPECT_EQ("b", resb->body);
  12200. }
  12201. // Closing an idle keep-alive connection sends close_notify and returns. The
  12202. // server must not wait for the client's close_notify: an idle client never
  12203. // sends one, so the worker would be held until the read timeout expires, and
  12204. // stop() would wait for it.
  12205. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12206. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12207. ASSERT_TRUE(svr.is_valid());
  12208. svr.set_keep_alive_timeout(1);
  12209. svr.set_read_timeout(10, 0);
  12210. svr.Get("/", [](const Request &, Response &res) {
  12211. res.set_content("ok", "text/plain");
  12212. });
  12213. auto port = svr.bind_to_any_port(HOST);
  12214. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12215. auto se = detail::scope_exit([&] {
  12216. if (listen_thread.joinable()) {
  12217. svr.stop();
  12218. listen_thread.join();
  12219. }
  12220. });
  12221. svr.wait_until_ready();
  12222. SSLClient cli(HOST, port);
  12223. cli.enable_server_certificate_verification(false);
  12224. cli.set_keep_alive(true);
  12225. auto res = cli.Get("/");
  12226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12227. EXPECT_EQ(StatusCode::OK_200, res->status);
  12228. // Stay idle past the keep-alive timeout so the server closes the connection.
  12229. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12230. auto start = std::chrono::steady_clock::now();
  12231. svr.stop();
  12232. listen_thread.join();
  12233. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12234. std::chrono::steady_clock::now() - start)
  12235. .count();
  12236. EXPECT_LT(elapsed, 3000);
  12237. }
  12238. #endif
  12239. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12240. protected:
  12241. ServerTestWithAI_PASSIVE()
  12242. : cli_(HOST, PORT)
  12243. #ifdef CPPHTTPLIB_SSL_ENABLED
  12244. ,
  12245. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12246. #endif
  12247. {
  12248. #ifdef CPPHTTPLIB_SSL_ENABLED
  12249. cli_.enable_server_certificate_verification(false);
  12250. #endif
  12251. }
  12252. virtual void SetUp() {
  12253. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12254. res.set_content("Hello World!", "text/plain");
  12255. });
  12256. t_ = thread(
  12257. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12258. svr_.wait_until_ready();
  12259. }
  12260. virtual void TearDown() {
  12261. svr_.stop();
  12262. t_.join();
  12263. }
  12264. #ifdef CPPHTTPLIB_SSL_ENABLED
  12265. SSLClient cli_;
  12266. SSLServer svr_;
  12267. #else
  12268. Client cli_;
  12269. Server svr_;
  12270. #endif
  12271. thread t_;
  12272. };
  12273. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12274. auto res = cli_.Get("/hi");
  12275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12276. EXPECT_EQ(StatusCode::OK_200, res->status);
  12277. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12278. EXPECT_EQ("Hello World!", res->body);
  12279. }
  12280. class ServerUpDownTest : public ::testing::Test {
  12281. protected:
  12282. ServerUpDownTest() : cli_(HOST, PORT) {}
  12283. virtual void SetUp() {
  12284. t_ = thread([&]() {
  12285. svr_.bind_to_any_port(HOST);
  12286. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12287. ASSERT_TRUE(svr_.listen_after_bind());
  12288. });
  12289. svr_.wait_until_ready();
  12290. }
  12291. virtual void TearDown() {
  12292. svr_.stop();
  12293. t_.join();
  12294. }
  12295. Client cli_;
  12296. Server svr_;
  12297. thread t_;
  12298. };
  12299. TEST_F(ServerUpDownTest, QuickStartStop) {
  12300. // Should not crash, especially when run with
  12301. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12302. }
  12303. class PayloadMaxLengthTest : public ::testing::Test {
  12304. protected:
  12305. PayloadMaxLengthTest()
  12306. : cli_(HOST, PORT)
  12307. #ifdef CPPHTTPLIB_SSL_ENABLED
  12308. ,
  12309. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12310. #endif
  12311. {
  12312. #ifdef CPPHTTPLIB_SSL_ENABLED
  12313. cli_.enable_server_certificate_verification(false);
  12314. #endif
  12315. }
  12316. virtual void SetUp() {
  12317. svr_.set_payload_max_length(8);
  12318. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12319. res.set_content("test", "text/plain");
  12320. });
  12321. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12322. svr_.wait_until_ready();
  12323. }
  12324. virtual void TearDown() {
  12325. svr_.stop();
  12326. t_.join();
  12327. }
  12328. #ifdef CPPHTTPLIB_SSL_ENABLED
  12329. SSLClient cli_;
  12330. SSLServer svr_;
  12331. #else
  12332. Client cli_;
  12333. Server svr_;
  12334. #endif
  12335. thread t_;
  12336. };
  12337. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12338. auto res = cli_.Post("/test", "123456789", "text/plain");
  12339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12340. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12341. res = cli_.Post("/test", "12345678", "text/plain");
  12342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12343. EXPECT_EQ(StatusCode::OK_200, res->status);
  12344. }
  12345. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12346. // Test chunked encoding with payload exceeding the 8-byte limit
  12347. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12348. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12350. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12351. }
  12352. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12353. // Test chunked encoding with payload within the 8-byte limit
  12354. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12355. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12357. EXPECT_EQ(StatusCode::OK_200, res->status);
  12358. }
  12359. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12360. // Test using send_request to send chunked data exceeding payload limit
  12361. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12362. "Host: " +
  12363. std::string(HOST) + ":" + std::to_string(PORT) +
  12364. "\r\n"
  12365. "Transfer-Encoding: chunked\r\n"
  12366. "Connection: close\r\n"
  12367. "\r\n"
  12368. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12369. "0123456789\r\n"
  12370. "0\r\n" // End chunk
  12371. "\r\n";
  12372. std::string response;
  12373. bool result = send_request(1, chunked_request, &response);
  12374. if (!result) {
  12375. // If send_request fails, it might be because the server closed the
  12376. // connection due to payload limit enforcement, which is acceptable
  12377. SUCCEED()
  12378. << "Server rejected oversized chunked request (connection closed)";
  12379. } else {
  12380. // If we got a response, check if it's an error response or connection was
  12381. // closed early Short response length indicates connection was closed due to
  12382. // payload limit
  12383. if (response.length() <= 10) {
  12384. SUCCEED() << "Server closed connection for oversized chunked request";
  12385. } else {
  12386. // Check for error status codes
  12387. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12388. response.find("Payload Too Large") != std::string::npos ||
  12389. response.find("400") != std::string::npos);
  12390. }
  12391. }
  12392. }
  12393. class LargePayloadMaxLengthTest : public ::testing::Test {
  12394. protected:
  12395. LargePayloadMaxLengthTest()
  12396. : cli_(HOST, PORT)
  12397. #ifdef CPPHTTPLIB_SSL_ENABLED
  12398. ,
  12399. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12400. #endif
  12401. {
  12402. #ifdef CPPHTTPLIB_SSL_ENABLED
  12403. cli_.enable_server_certificate_verification(false);
  12404. #endif
  12405. }
  12406. virtual void SetUp() {
  12407. // Set 10MB payload limit
  12408. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12409. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12410. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12411. res.set_content("Large payload test", "text/plain");
  12412. });
  12413. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12414. svr_.wait_until_ready();
  12415. }
  12416. virtual void TearDown() {
  12417. svr_.stop();
  12418. t_.join();
  12419. }
  12420. #ifdef CPPHTTPLIB_SSL_ENABLED
  12421. SSLClient cli_;
  12422. SSLServer svr_;
  12423. #else
  12424. Client cli_;
  12425. Server svr_;
  12426. #endif
  12427. thread t_;
  12428. };
  12429. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12430. // Test chunked encoding with payload within 10MB limit
  12431. std::string medium_payload(5 * 1024 * 1024,
  12432. 'A'); // 5MB payload, within 10MB limit
  12433. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12435. EXPECT_EQ(StatusCode::OK_200, res->status);
  12436. }
  12437. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12438. // Test chunked encoding with payload exceeding 10MB limit
  12439. std::string large_payload(12 * 1024 * 1024,
  12440. 'B'); // 12MB payload, exceeds 10MB limit
  12441. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12442. // Server may either return 413 or close the connection
  12443. if (res) {
  12444. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12445. } else {
  12446. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12447. }
  12448. }
  12449. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12450. Server svr;
  12451. svr.Get("/", [](const Request &, Response &res) {
  12452. // Claims the most the client accepts, far more than it sends, then drops
  12453. // the connection.
  12454. res.set_content_provider(std::string().max_size(), "text/plain",
  12455. [](size_t, size_t, DataSink &sink) {
  12456. sink.write("abc", 3);
  12457. return false;
  12458. });
  12459. });
  12460. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12461. auto se = detail::scope_exit([&] {
  12462. svr.stop();
  12463. thread.join();
  12464. ASSERT_FALSE(svr.is_running());
  12465. });
  12466. svr.wait_until_ready();
  12467. Client cli(HOST, PORT);
  12468. cli.set_payload_max_length(0);
  12469. EXPECT_FALSE(cli.Get("/"));
  12470. }
  12471. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12472. // Stream API does, not as a plain read failure
  12473. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12474. Server svr;
  12475. svr.Get("/big", [](const Request &, Response &res) {
  12476. res.set_content(std::string(100000, 'b'), "text/plain");
  12477. });
  12478. auto port = svr.bind_to_any_port(HOST);
  12479. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12480. auto se = detail::scope_exit([&] {
  12481. svr.stop();
  12482. thread.join();
  12483. });
  12484. svr.wait_until_ready();
  12485. Client cli(HOST, port);
  12486. cli.set_payload_max_length(1000);
  12487. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12488. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12489. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12490. [](const char *, size_t) { return true; });
  12491. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12492. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12493. // Small on the wire, over the limit once decompressed
  12494. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12495. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12496. #endif
  12497. }
  12498. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12499. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12500. // path.
  12501. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12502. Server svr;
  12503. const size_t LIMIT = 64 * 1024; // 64KB
  12504. svr.set_payload_max_length(LIMIT);
  12505. size_t total = 0;
  12506. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12507. const ContentReader &content_reader) {
  12508. content_reader([&](const char * /*data*/, size_t len) {
  12509. total += len;
  12510. return true;
  12511. });
  12512. res.status = 200;
  12513. res.set_content("stream_ok", "text/plain");
  12514. });
  12515. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12516. auto se = detail::scope_exit([&] {
  12517. svr.stop();
  12518. thread.join();
  12519. ASSERT_FALSE(svr.is_running());
  12520. });
  12521. svr.wait_until_ready();
  12522. // Prepare 256KB raw data and gzip-compress it
  12523. std::string raw(256 * 1024, 'A');
  12524. std::string gz;
  12525. {
  12526. z_stream zs{};
  12527. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12528. Z_DEFAULT_STRATEGY);
  12529. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12530. zs.avail_in = static_cast<uInt>(raw.size());
  12531. char outbuf[4096];
  12532. int ret;
  12533. do {
  12534. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12535. zs.avail_out = sizeof(outbuf);
  12536. ret = deflate(&zs, Z_FINISH);
  12537. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12538. } while (ret != Z_STREAM_END);
  12539. deflateEnd(&zs);
  12540. }
  12541. Client cli(HOST, PORT);
  12542. cli.set_connection_timeout(std::chrono::seconds(5));
  12543. Headers headers = {{"Content-Encoding", "gzip"}};
  12544. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12545. "application/octet-stream");
  12546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12547. // Server must reject oversized decompressed payloads with 413.
  12548. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12549. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12550. EXPECT_LE(total, LIMIT);
  12551. }
  12552. #endif
  12553. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12554. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12555. // the payload must be passed through untouched instead of being rejected.
  12556. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12557. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12558. Server svr;
  12559. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12560. res.set_content(body, "image/jpeg");
  12561. res.set_header("Content-Encoding", "UTF-8");
  12562. });
  12563. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12564. res.set_content(body, "image/jpeg");
  12565. res.set_header("Content-Encoding", "identity");
  12566. });
  12567. svr.Post("/echo", [](const Request &req, Response &res) {
  12568. res.set_content(req.body, "image/jpeg");
  12569. });
  12570. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12571. auto se = detail::scope_exit([&] {
  12572. svr.stop();
  12573. t.join();
  12574. ASSERT_FALSE(svr.is_running());
  12575. });
  12576. svr.wait_until_ready();
  12577. Client cli(HOST, PORT);
  12578. {
  12579. auto res = cli.Get("/image");
  12580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12581. EXPECT_EQ(StatusCode::OK_200, res->status);
  12582. EXPECT_EQ(body, res->body);
  12583. }
  12584. {
  12585. auto res = cli.Get("/identity");
  12586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12587. EXPECT_EQ(StatusCode::OK_200, res->status);
  12588. EXPECT_EQ(body, res->body);
  12589. }
  12590. {
  12591. // The same applies to a request body reaching the server.
  12592. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12593. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12595. EXPECT_EQ(StatusCode::OK_200, res->status);
  12596. EXPECT_EQ(body, res->body);
  12597. }
  12598. }
  12599. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12600. // gzip-encoded response even when the build has no zlib support.
  12601. static const char GZIPPED_HELLO_WORLD[] = {
  12602. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12603. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12604. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12605. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12606. // A content coding is a whole token, not something the field value merely
  12607. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12608. // as "fibre" look like Brotli, and turned a multi-coding value like
  12609. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12610. // it was never meant to see.
  12611. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12612. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12613. Server svr;
  12614. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12615. res.set_content(body, "image/jpeg");
  12616. res.set_header("Content-Encoding", "fibre");
  12617. });
  12618. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12619. res.set_content(body, "image/jpeg");
  12620. res.set_header("Content-Encoding", "gzip, br");
  12621. });
  12622. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12623. res.set_content(body, "image/jpeg");
  12624. res.set_header("Content-Encoding", "x-zstd-ish");
  12625. });
  12626. auto port = svr.bind_to_any_port(HOST);
  12627. thread t = thread([&]() { svr.listen_after_bind(); });
  12628. auto se = detail::scope_exit([&] {
  12629. svr.stop();
  12630. t.join();
  12631. ASSERT_FALSE(svr.is_running());
  12632. });
  12633. svr.wait_until_ready();
  12634. Client cli(HOST, port);
  12635. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12636. auto res = cli.Get(path);
  12637. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12638. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12639. // Not a coding we recognize, so the payload comes back untouched
  12640. EXPECT_EQ(body, res->body) << path;
  12641. }
  12642. }
  12643. // A content coding cpp-httplib recognizes but was not built with must be
  12644. // reported as such. Handing the still-compressed payload back to the caller
  12645. // would silently corrupt it.
  12646. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12647. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12648. Server svr;
  12649. // "image/jpeg" keeps the server from applying a content coding of its own,
  12650. // so the hand-crafted Content-Encoding below survives.
  12651. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12652. res.set_content(gzipped, "image/jpeg");
  12653. res.set_header("Content-Encoding", "gzip");
  12654. });
  12655. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12656. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12657. res.set_content(gzipped, "image/jpeg");
  12658. res.set_header("Content-Encoding", "GZIP");
  12659. });
  12660. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12661. auto se = detail::scope_exit([&] {
  12662. svr.stop();
  12663. t.join();
  12664. ASSERT_FALSE(svr.is_running());
  12665. });
  12666. svr.wait_until_ready();
  12667. Client cli(HOST, PORT);
  12668. {
  12669. auto res = cli.Get("/gzipped");
  12670. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12672. EXPECT_EQ("Hello World!", res->body);
  12673. #else
  12674. ASSERT_FALSE(res);
  12675. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12676. #endif
  12677. }
  12678. {
  12679. // open_stream() must behave the same way.
  12680. auto handle = cli.open_stream("GET", "/gzipped");
  12681. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12682. ASSERT_TRUE(handle.is_valid());
  12683. std::string received;
  12684. char buf[256];
  12685. ssize_t n;
  12686. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12687. received.append(buf, static_cast<size_t>(n));
  12688. }
  12689. EXPECT_EQ("Hello World!", received);
  12690. #else
  12691. EXPECT_FALSE(handle.is_valid());
  12692. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12693. #endif
  12694. }
  12695. {
  12696. // A differently-cased coding must not be mistaken for an unknown one, or
  12697. // the body would be handed back still compressed.
  12698. auto res = cli.Get("/gzipped-uppercase");
  12699. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12701. EXPECT_EQ("Hello World!", res->body);
  12702. #else
  12703. ASSERT_FALSE(res);
  12704. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12705. #endif
  12706. }
  12707. }
  12708. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12709. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12710. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12711. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12712. // body a second time and appending a second Content-Encoding field line, so
  12713. // clients that decode one coding per listed value handed back raw gzip bytes.
  12714. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12715. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12716. Server svr;
  12717. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12718. // keeps the server from applying a coding of its own.
  12719. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12720. res.set_content(gzipped, "text/plain");
  12721. res.set_header("Content-Encoding", "gzip");
  12722. });
  12723. auto port = svr.bind_to_any_port(HOST);
  12724. thread t = thread([&]() { svr.listen_after_bind(); });
  12725. auto se = detail::scope_exit([&] {
  12726. svr.stop();
  12727. t.join();
  12728. ASSERT_FALSE(svr.is_running());
  12729. });
  12730. svr.wait_until_ready();
  12731. Client cli(HOST, port);
  12732. Headers headers = {{"Accept-Encoding", "gzip"}};
  12733. auto res = cli.Get("/pre-gzipped", headers);
  12734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12735. EXPECT_EQ(StatusCode::OK_200, res->status);
  12736. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12737. EXPECT_EQ("Hello World!", res->body);
  12738. }
  12739. // set_compress(false) sends every handler response as it is, buffered or
  12740. // streamed
  12741. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12742. const std::string text(1000, 'a');
  12743. Server svr;
  12744. svr.set_compress(false);
  12745. svr.Get("/buffered", [&](const Request &, Response &res) {
  12746. res.set_content(text, "text/plain");
  12747. });
  12748. svr.Get("/streamed", [&](const Request &, Response &res) {
  12749. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12750. sink.write(text.data(), text.size());
  12751. sink.done();
  12752. return true;
  12753. });
  12754. });
  12755. auto port = svr.bind_to_any_port(HOST);
  12756. ASSERT_LT(0, port);
  12757. thread t = thread([&] { svr.listen_after_bind(); });
  12758. auto se = detail::scope_exit([&] {
  12759. svr.stop();
  12760. t.join();
  12761. ASSERT_FALSE(svr.is_running());
  12762. });
  12763. svr.wait_until_ready();
  12764. Client cli(HOST, port);
  12765. cli.set_decompress(false);
  12766. for (auto path : {"/buffered", "/streamed"}) {
  12767. SCOPED_TRACE(path);
  12768. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12770. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12771. EXPECT_EQ(text, res->body);
  12772. }
  12773. }
  12774. // A chunked provider settles its coding where the headers are written and
  12775. // reuses it at write time. Both ends of that have to hold: a handler's own
  12776. // Content-Encoding suppresses the coding, and a response without one is still
  12777. // compressed as it always was.
  12778. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12779. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12780. const std::string plain = "Hello World! Hello World! Hello World!";
  12781. Server svr;
  12782. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12783. res.set_header("Content-Encoding", "gzip");
  12784. res.set_chunked_content_provider(
  12785. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12786. sink.write(gzipped.data(), gzipped.size());
  12787. sink.done();
  12788. return true;
  12789. });
  12790. });
  12791. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12792. res.set_chunked_content_provider(
  12793. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12794. sink.write(plain.data(), plain.size());
  12795. sink.done();
  12796. return true;
  12797. });
  12798. });
  12799. auto port = svr.bind_to_any_port(HOST);
  12800. thread t = thread([&]() { svr.listen_after_bind(); });
  12801. auto se = detail::scope_exit([&] {
  12802. svr.stop();
  12803. t.join();
  12804. ASSERT_FALSE(svr.is_running());
  12805. });
  12806. svr.wait_until_ready();
  12807. Client cli(HOST, port);
  12808. Headers headers = {{"Accept-Encoding", "gzip"}};
  12809. {
  12810. auto res = cli.Get("/pre-gzipped", headers);
  12811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12812. EXPECT_EQ(StatusCode::OK_200, res->status);
  12813. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12814. EXPECT_EQ("Hello World!", res->body);
  12815. }
  12816. {
  12817. auto res = cli.Get("/negotiated", headers);
  12818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12819. EXPECT_EQ(StatusCode::OK_200, res->status);
  12820. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12821. EXPECT_EQ(plain, res->body);
  12822. }
  12823. }
  12824. #endif
  12825. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12826. // the same message as the comma-joined one, so both have to be read the same
  12827. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12828. // single gzip coding, and a body the sender says was encoded twice was handed
  12829. // back after one pass, still compressed but presented as decoded.
  12830. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12831. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12832. Server svr;
  12833. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12834. res.set_content(body, "image/jpeg");
  12835. res.headers.emplace("Content-Encoding", "gzip");
  12836. res.headers.emplace("Content-Encoding", "gzip");
  12837. });
  12838. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12839. res.set_content(body, "image/jpeg");
  12840. res.set_header("Content-Encoding", "gzip, gzip");
  12841. });
  12842. auto port = svr.bind_to_any_port(HOST);
  12843. thread t = thread([&]() { svr.listen_after_bind(); });
  12844. auto se = detail::scope_exit([&] {
  12845. svr.stop();
  12846. t.join();
  12847. ASSERT_FALSE(svr.is_running());
  12848. });
  12849. svr.wait_until_ready();
  12850. Client cli(HOST, port);
  12851. // Two codings is not something cpp-httplib decodes, so both representations
  12852. // take the pass-through path rather than one of them being gunzipped once.
  12853. for (const char *path : {"/split", "/joined"}) {
  12854. auto res = cli.Get(path);
  12855. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12856. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12857. EXPECT_EQ(body, res->body) << path;
  12858. }
  12859. }
  12860. // Regression test for DoS vulnerability: a malicious server sending a response
  12861. // without Content-Length header must not cause unbounded memory consumption on
  12862. // the client side. The client should stop reading after a reasonable limit,
  12863. // similar to the server-side set_payload_max_length protection.
  12864. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12865. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12866. #ifndef _WIN32
  12867. signal(SIGPIPE, SIG_IGN);
  12868. #endif
  12869. auto server_thread = std::thread([] {
  12870. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12871. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12872. default_socket_options(srv);
  12873. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12874. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12875. sockaddr_in addr{};
  12876. addr.sin_family = AF_INET;
  12877. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12878. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12879. int opt = 1;
  12880. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12881. #ifdef _WIN32
  12882. reinterpret_cast<const char *>(&opt),
  12883. #else
  12884. &opt,
  12885. #endif
  12886. sizeof(opt));
  12887. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12888. ::listen(srv, 1);
  12889. sockaddr_in cli_addr{};
  12890. socklen_t cli_len = sizeof(cli_addr);
  12891. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12892. if (cli != INVALID_SOCKET) {
  12893. char buf[4096];
  12894. ::recv(cli, buf, sizeof(buf), 0);
  12895. // Malicious response: no Content-Length, no chunked encoding
  12896. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12897. "Connection: close\r\n"
  12898. "\r\n";
  12899. ::send(cli,
  12900. #ifdef _WIN32
  12901. static_cast<const char *>(response_header.c_str()),
  12902. static_cast<int>(response_header.size()),
  12903. #else
  12904. response_header.c_str(), response_header.size(),
  12905. #endif
  12906. 0);
  12907. // Send 10MB of data
  12908. std::string chunk(64 * 1024, 'A');
  12909. size_t total_sent = 0;
  12910. while (total_sent < MALICIOUS_DATA_SIZE) {
  12911. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12912. auto sent = ::send(cli,
  12913. #ifdef _WIN32
  12914. static_cast<const char *>(chunk.c_str()),
  12915. static_cast<int>(to_send),
  12916. #else
  12917. chunk.c_str(), to_send,
  12918. #endif
  12919. 0);
  12920. if (sent <= 0) break;
  12921. total_sent += static_cast<size_t>(sent);
  12922. }
  12923. detail::close_socket(cli);
  12924. }
  12925. detail::close_socket(srv);
  12926. });
  12927. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12928. size_t total_read = 0;
  12929. {
  12930. Client cli("127.0.0.1", PORT + 2);
  12931. cli.set_read_timeout(5, 0);
  12932. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12933. auto stream = cli.open_stream("GET", "/malicious");
  12934. ASSERT_TRUE(stream.is_valid());
  12935. char buffer[64 * 1024];
  12936. ssize_t n;
  12937. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12938. total_read += static_cast<size_t>(n);
  12939. }
  12940. } // StreamHandle and Client destroyed here, closing the socket
  12941. server_thread.join();
  12942. // With set_payload_max_length, the client must stop reading before consuming
  12943. // all 10MB. The read loop should be cut off at or near the configured limit.
  12944. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12945. << "Client read " << total_read << " bytes, exceeding the configured "
  12946. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12947. }
  12948. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12949. // the entire response body without truncation.
  12950. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12951. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12952. #ifndef _WIN32
  12953. signal(SIGPIPE, SIG_IGN);
  12954. #endif
  12955. auto server_thread = std::thread([] {
  12956. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12957. default_socket_options(srv);
  12958. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12959. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12960. sockaddr_in addr{};
  12961. addr.sin_family = AF_INET;
  12962. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12963. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12964. int opt = 1;
  12965. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12966. #ifdef _WIN32
  12967. reinterpret_cast<const char *>(&opt),
  12968. #else
  12969. &opt,
  12970. #endif
  12971. sizeof(opt));
  12972. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12973. ::listen(srv, 1);
  12974. sockaddr_in cli_addr{};
  12975. socklen_t cli_len = sizeof(cli_addr);
  12976. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12977. if (cli != INVALID_SOCKET) {
  12978. char buf[4096];
  12979. ::recv(cli, buf, sizeof(buf), 0);
  12980. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12981. "Connection: close\r\n"
  12982. "\r\n";
  12983. ::send(cli,
  12984. #ifdef _WIN32
  12985. static_cast<const char *>(response_header.c_str()),
  12986. static_cast<int>(response_header.size()),
  12987. #else
  12988. response_header.c_str(), response_header.size(),
  12989. #endif
  12990. 0);
  12991. std::string chunk(64 * 1024, 'A');
  12992. size_t total_sent = 0;
  12993. while (total_sent < DATA_SIZE) {
  12994. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12995. auto sent = ::send(cli,
  12996. #ifdef _WIN32
  12997. static_cast<const char *>(chunk.c_str()),
  12998. static_cast<int>(to_send),
  12999. #else
  13000. chunk.c_str(), to_send,
  13001. #endif
  13002. 0);
  13003. if (sent <= 0) break;
  13004. total_sent += static_cast<size_t>(sent);
  13005. }
  13006. #ifdef _WIN32
  13007. ::shutdown(cli, SD_SEND);
  13008. #else
  13009. ::shutdown(cli, SHUT_WR);
  13010. #endif
  13011. // Drain until the client closes its end, ensuring all data is delivered
  13012. char drain[1024];
  13013. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13014. detail::close_socket(cli);
  13015. }
  13016. detail::close_socket(srv);
  13017. });
  13018. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13019. size_t total_read = 0;
  13020. {
  13021. Client cli("127.0.0.1", PORT + 2);
  13022. cli.set_read_timeout(5, 0);
  13023. cli.set_payload_max_length(0); // 0 means no limit
  13024. auto stream = cli.open_stream("GET", "/data");
  13025. ASSERT_TRUE(stream.is_valid());
  13026. char buffer[64 * 1024];
  13027. ssize_t n;
  13028. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13029. total_read += static_cast<size_t>(n);
  13030. }
  13031. }
  13032. server_thread.join();
  13033. EXPECT_EQ(total_read, DATA_SIZE)
  13034. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13035. << " bytes without truncation, but only read " << total_read << " bytes.";
  13036. }
  13037. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13038. // enormous Content-Length must not cause the client to pre-allocate a huge
  13039. // response body buffer. The reservation is capped at payload_max_length_, and
  13040. // the read itself fails when the body exceeds the limit.
  13041. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13042. #ifndef _WIN32
  13043. signal(SIGPIPE, SIG_IGN);
  13044. #endif
  13045. auto server_thread = std::thread([] {
  13046. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13047. default_socket_options(srv);
  13048. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13049. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13050. sockaddr_in addr{};
  13051. addr.sin_family = AF_INET;
  13052. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13053. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13054. int opt = 1;
  13055. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13056. #ifdef _WIN32
  13057. reinterpret_cast<const char *>(&opt),
  13058. #else
  13059. &opt,
  13060. #endif
  13061. sizeof(opt));
  13062. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13063. ::listen(srv, 1);
  13064. sockaddr_in cli_addr{};
  13065. socklen_t cli_len = sizeof(cli_addr);
  13066. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13067. if (cli != INVALID_SOCKET) {
  13068. char buf[4096];
  13069. ::recv(cli, buf, sizeof(buf), 0);
  13070. // Malicious response: claim a 20GB body but send only a tiny payload.
  13071. std::string response = "HTTP/1.1 200 OK\r\n"
  13072. "Content-Length: 20000000000\r\n"
  13073. "\r\n"
  13074. "abc";
  13075. ::send(cli,
  13076. #ifdef _WIN32
  13077. static_cast<const char *>(response.c_str()),
  13078. static_cast<int>(response.size()),
  13079. #else
  13080. response.c_str(), response.size(),
  13081. #endif
  13082. 0);
  13083. detail::close_socket(cli);
  13084. }
  13085. detail::close_socket(srv);
  13086. });
  13087. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13088. {
  13089. Client cli("127.0.0.1", PORT + 2);
  13090. cli.set_read_timeout(5, 0);
  13091. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13092. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13093. // (server claims more bytes than payload_max_length permits), but it must
  13094. // not exhaust memory before getting there.
  13095. auto res = cli.Get("/malicious");
  13096. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13097. }
  13098. server_thread.join();
  13099. }
  13100. // Verify that content_receiver bypasses the default payload_max_length,
  13101. // allowing streaming downloads larger than 100MB without requiring an explicit
  13102. // set_payload_max_length call.
  13103. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13104. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13105. #ifndef _WIN32
  13106. signal(SIGPIPE, SIG_IGN);
  13107. #endif
  13108. auto server_thread = std::thread([] {
  13109. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13110. default_socket_options(srv);
  13111. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13112. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13113. sockaddr_in addr{};
  13114. addr.sin_family = AF_INET;
  13115. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13116. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13117. int opt = 1;
  13118. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13119. #ifdef _WIN32
  13120. reinterpret_cast<const char *>(&opt),
  13121. #else
  13122. &opt,
  13123. #endif
  13124. sizeof(opt));
  13125. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13126. ::listen(srv, 1);
  13127. sockaddr_in cli_addr{};
  13128. socklen_t cli_len = sizeof(cli_addr);
  13129. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13130. if (cli != INVALID_SOCKET) {
  13131. char buf[4096];
  13132. ::recv(cli, buf, sizeof(buf), 0);
  13133. // Response with Content-Length larger than default 100MB limit
  13134. auto content_length = std::to_string(DATA_SIZE);
  13135. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13136. "Content-Length: " +
  13137. content_length +
  13138. "\r\n"
  13139. "Connection: close\r\n"
  13140. "\r\n";
  13141. ::send(cli,
  13142. #ifdef _WIN32
  13143. static_cast<const char *>(response_header.c_str()),
  13144. static_cast<int>(response_header.size()),
  13145. #else
  13146. response_header.c_str(), response_header.size(),
  13147. #endif
  13148. 0);
  13149. std::string chunk(64 * 1024, 'A');
  13150. size_t total_sent = 0;
  13151. while (total_sent < DATA_SIZE) {
  13152. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13153. auto sent = ::send(cli,
  13154. #ifdef _WIN32
  13155. static_cast<const char *>(chunk.c_str()),
  13156. static_cast<int>(to_send),
  13157. #else
  13158. chunk.c_str(), to_send,
  13159. #endif
  13160. 0);
  13161. if (sent <= 0) break;
  13162. total_sent += static_cast<size_t>(sent);
  13163. }
  13164. detail::close_socket(cli);
  13165. }
  13166. detail::close_socket(srv);
  13167. });
  13168. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13169. size_t total_received = 0;
  13170. {
  13171. Client cli("127.0.0.1", PORT + 2);
  13172. cli.set_read_timeout(10, 0);
  13173. // Do NOT call set_payload_max_length — use the default 100MB limit
  13174. auto res =
  13175. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13176. total_received += data_length;
  13177. return true;
  13178. });
  13179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13180. EXPECT_EQ(StatusCode::OK_200, res->status);
  13181. }
  13182. server_thread.join();
  13183. EXPECT_EQ(total_received, DATA_SIZE)
  13184. << "With content_receiver, the client should read all " << DATA_SIZE
  13185. << " bytes despite the default 100MB payload_max_length, but only read "
  13186. << total_received << " bytes.";
  13187. }
  13188. // Verify that an explicit set_payload_max_length smaller than the response is
  13189. // enforced even when a content_receiver is used.
  13190. TEST(ClientVulnerabilityTest,
  13191. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13192. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13193. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13194. #ifndef _WIN32
  13195. signal(SIGPIPE, SIG_IGN);
  13196. #endif
  13197. auto server_thread = std::thread([] {
  13198. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13199. default_socket_options(srv);
  13200. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13201. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13202. sockaddr_in addr{};
  13203. addr.sin_family = AF_INET;
  13204. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13205. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13206. int opt = 1;
  13207. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13208. #ifdef _WIN32
  13209. reinterpret_cast<const char *>(&opt),
  13210. #else
  13211. &opt,
  13212. #endif
  13213. sizeof(opt));
  13214. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13215. ::listen(srv, 1);
  13216. sockaddr_in cli_addr{};
  13217. socklen_t cli_len = sizeof(cli_addr);
  13218. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13219. if (cli != INVALID_SOCKET) {
  13220. char buf[4096];
  13221. ::recv(cli, buf, sizeof(buf), 0);
  13222. auto content_length = std::to_string(DATA_SIZE);
  13223. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13224. "Content-Length: " +
  13225. content_length +
  13226. "\r\n"
  13227. "Connection: close\r\n"
  13228. "\r\n";
  13229. ::send(cli,
  13230. #ifdef _WIN32
  13231. static_cast<const char *>(response_header.c_str()),
  13232. static_cast<int>(response_header.size()),
  13233. #else
  13234. response_header.c_str(), response_header.size(),
  13235. #endif
  13236. 0);
  13237. std::string chunk(64 * 1024, 'A');
  13238. size_t total_sent = 0;
  13239. while (total_sent < DATA_SIZE) {
  13240. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13241. auto sent = ::send(cli,
  13242. #ifdef _WIN32
  13243. static_cast<const char *>(chunk.c_str()),
  13244. static_cast<int>(to_send),
  13245. #else
  13246. chunk.c_str(), to_send,
  13247. #endif
  13248. 0);
  13249. if (sent <= 0) break;
  13250. total_sent += static_cast<size_t>(sent);
  13251. }
  13252. detail::close_socket(cli);
  13253. }
  13254. detail::close_socket(srv);
  13255. });
  13256. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13257. size_t total_received = 0;
  13258. {
  13259. Client cli("127.0.0.1", PORT + 2);
  13260. cli.set_read_timeout(10, 0);
  13261. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13262. auto res =
  13263. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13264. total_received += data_length;
  13265. return true;
  13266. });
  13267. // Should fail because 200MB exceeds the explicit 150MB limit
  13268. EXPECT_FALSE(res);
  13269. }
  13270. server_thread.join();
  13271. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13272. << "Client with content_receiver should respect the explicit "
  13273. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13274. << total_received << " bytes.";
  13275. }
  13276. // Verify that an explicit set_payload_max_length larger than the response
  13277. // allows the content_receiver to read all data successfully.
  13278. TEST(ClientVulnerabilityTest,
  13279. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13280. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13281. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13282. #ifndef _WIN32
  13283. signal(SIGPIPE, SIG_IGN);
  13284. #endif
  13285. auto server_thread = std::thread([] {
  13286. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13287. default_socket_options(srv);
  13288. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13289. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13290. sockaddr_in addr{};
  13291. addr.sin_family = AF_INET;
  13292. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13293. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13294. int opt = 1;
  13295. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13296. #ifdef _WIN32
  13297. reinterpret_cast<const char *>(&opt),
  13298. #else
  13299. &opt,
  13300. #endif
  13301. sizeof(opt));
  13302. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13303. ::listen(srv, 1);
  13304. sockaddr_in cli_addr{};
  13305. socklen_t cli_len = sizeof(cli_addr);
  13306. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13307. if (cli != INVALID_SOCKET) {
  13308. char buf[4096];
  13309. ::recv(cli, buf, sizeof(buf), 0);
  13310. auto content_length = std::to_string(DATA_SIZE);
  13311. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13312. "Content-Length: " +
  13313. content_length +
  13314. "\r\n"
  13315. "Connection: close\r\n"
  13316. "\r\n";
  13317. ::send(cli,
  13318. #ifdef _WIN32
  13319. static_cast<const char *>(response_header.c_str()),
  13320. static_cast<int>(response_header.size()),
  13321. #else
  13322. response_header.c_str(), response_header.size(),
  13323. #endif
  13324. 0);
  13325. std::string chunk(64 * 1024, 'A');
  13326. size_t total_sent = 0;
  13327. while (total_sent < DATA_SIZE) {
  13328. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13329. auto sent = ::send(cli,
  13330. #ifdef _WIN32
  13331. static_cast<const char *>(chunk.c_str()),
  13332. static_cast<int>(to_send),
  13333. #else
  13334. chunk.c_str(), to_send,
  13335. #endif
  13336. 0);
  13337. if (sent <= 0) break;
  13338. total_sent += static_cast<size_t>(sent);
  13339. }
  13340. #ifdef _WIN32
  13341. ::shutdown(cli, SD_SEND);
  13342. #else
  13343. ::shutdown(cli, SHUT_WR);
  13344. #endif
  13345. char drain[1024];
  13346. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13347. detail::close_socket(cli);
  13348. }
  13349. detail::close_socket(srv);
  13350. });
  13351. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13352. size_t total_received = 0;
  13353. {
  13354. Client cli("127.0.0.1", PORT + 2);
  13355. cli.set_read_timeout(10, 0);
  13356. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13357. auto res =
  13358. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13359. total_received += data_length;
  13360. return true;
  13361. });
  13362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13363. EXPECT_EQ(StatusCode::OK_200, res->status);
  13364. }
  13365. server_thread.join();
  13366. EXPECT_EQ(total_received, DATA_SIZE)
  13367. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13368. << " bytes (larger than " << DATA_SIZE
  13369. << " bytes response), content_receiver should read all data, but only "
  13370. "read "
  13371. << total_received << " bytes.";
  13372. }
  13373. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13374. // Regression test for "zip bomb" attack on the client side: a malicious server
  13375. // sends a small gzip-compressed response that decompresses to a huge payload.
  13376. // The client must enforce payload_max_length on the decompressed size.
  13377. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13378. constexpr size_t DECOMPRESSED_SIZE =
  13379. 10 * 1024 * 1024; // 10MB after decompression
  13380. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13381. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13382. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13383. std::string compressed;
  13384. {
  13385. httplib::detail::gzip_compressor compressor;
  13386. bool ok =
  13387. compressor.compress(uncompressed.data(), uncompressed.size(),
  13388. /*last=*/true, [&](const char *buf, size_t len) {
  13389. compressed.append(buf, len);
  13390. return true;
  13391. });
  13392. ASSERT_TRUE(ok);
  13393. }
  13394. // Sanity: compressed data should be much smaller than the decompressed size
  13395. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13396. #ifndef _WIN32
  13397. signal(SIGPIPE, SIG_IGN);
  13398. #endif
  13399. // Set up the listening socket in the main thread so the server is guaranteed
  13400. // to be ready before the client connects (eliminates race condition).
  13401. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13402. default_socket_options(srv);
  13403. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13404. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13405. sockaddr_in addr{};
  13406. addr.sin_family = AF_INET;
  13407. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13408. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13409. int opt = 1;
  13410. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13411. #ifdef _WIN32
  13412. reinterpret_cast<const char *>(&opt),
  13413. #else
  13414. &opt,
  13415. #endif
  13416. sizeof(opt));
  13417. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13418. ASSERT_EQ(0, ::listen(srv, 1));
  13419. auto server_thread = std::thread([&compressed, srv] {
  13420. sockaddr_in cli_addr{};
  13421. socklen_t cli_len = sizeof(cli_addr);
  13422. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13423. if (cli != INVALID_SOCKET) {
  13424. // Read the full HTTP request (until \r\n\r\n)
  13425. char buf[4096];
  13426. size_t total = 0;
  13427. while (total < sizeof(buf)) {
  13428. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13429. if (n <= 0) break;
  13430. total += static_cast<size_t>(n);
  13431. // Check for end of headers
  13432. if (total >= 4) {
  13433. std::string req(buf, total);
  13434. if (req.find("\r\n\r\n") != std::string::npos) break;
  13435. }
  13436. }
  13437. // Malicious response: gzip-compressed body, no Content-Length
  13438. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13439. "Content-Encoding: gzip\r\n"
  13440. "Connection: close\r\n"
  13441. "\r\n";
  13442. ::send(cli,
  13443. #ifdef _WIN32
  13444. static_cast<const char *>(response_header.c_str()),
  13445. static_cast<int>(response_header.size()),
  13446. #else
  13447. response_header.c_str(), response_header.size(),
  13448. #endif
  13449. 0);
  13450. // Send the compressed payload (small on the wire, huge when decompressed)
  13451. size_t total_sent = 0;
  13452. while (total_sent < compressed.size()) {
  13453. auto to_send = std::min(compressed.size() - total_sent,
  13454. static_cast<size_t>(64 * 1024));
  13455. auto sent =
  13456. ::send(cli,
  13457. #ifdef _WIN32
  13458. static_cast<const char *>(compressed.c_str() + total_sent),
  13459. static_cast<int>(to_send),
  13460. #else
  13461. compressed.c_str() + total_sent, to_send,
  13462. #endif
  13463. 0);
  13464. if (sent <= 0) break;
  13465. total_sent += static_cast<size_t>(sent);
  13466. }
  13467. detail::close_socket(cli);
  13468. }
  13469. });
  13470. auto se = detail::scope_exit([&] {
  13471. detail::close_socket(srv);
  13472. server_thread.join();
  13473. });
  13474. size_t total_decompressed = 0;
  13475. {
  13476. Client cli("127.0.0.1", PORT + 3);
  13477. cli.set_read_timeout(5, 0);
  13478. cli.set_decompress(true);
  13479. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13480. auto stream = cli.open_stream("GET", "/zipbomb");
  13481. ASSERT_TRUE(stream.is_valid());
  13482. char buffer[64 * 1024];
  13483. ssize_t n;
  13484. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13485. total_decompressed += static_cast<size_t>(n);
  13486. }
  13487. }
  13488. // The decompressed size must be capped by payload_max_length. Without
  13489. // protection, the client would decompress the full 10MB from a tiny
  13490. // compressed payload, enabling a zip bomb DoS attack.
  13491. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13492. << "Client decompressed " << total_decompressed
  13493. << " bytes from a gzip response. The decompressed size should be "
  13494. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13495. }
  13496. #endif
  13497. TEST(HostAndPortPropertiesTest, NoSSL) {
  13498. httplib::Client cli("www.google.com", 1234);
  13499. ASSERT_EQ("www.google.com", cli.host());
  13500. ASSERT_EQ(1234, cli.port());
  13501. }
  13502. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13503. httplib::Client cli("www.google.com:1234");
  13504. ASSERT_EQ("www.google.com", cli.host());
  13505. ASSERT_EQ(1234, cli.port());
  13506. }
  13507. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13508. // Port number that overflows int — should not crash, client becomes invalid
  13509. httplib::Client cli("http://www.google.com:99999999999999999999");
  13510. ASSERT_FALSE(cli.is_valid());
  13511. }
  13512. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13513. // Port 99999 exceeds valid range (1-65535) — should not crash
  13514. httplib::Client cli("http://www.google.com:99999");
  13515. ASSERT_FALSE(cli.is_valid());
  13516. auto res = cli.Get("/");
  13517. EXPECT_FALSE(res);
  13518. EXPECT_EQ(Error::Connection, res.error());
  13519. }
  13520. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13521. httplib::Client cli("http://user:pass@localhost:1234");
  13522. ASSERT_FALSE(cli.is_valid());
  13523. EXPECT_FALSE(cli.Get("/"));
  13524. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13525. }
  13526. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13527. httplib::Client cli("http://www.google.com:80abc");
  13528. ASSERT_FALSE(cli.is_valid());
  13529. }
  13530. #ifdef CPPHTTPLIB_SSL_ENABLED
  13531. TEST(HostAndPortPropertiesTest, SSL) {
  13532. httplib::SSLClient cli("www.google.com");
  13533. ASSERT_EQ("www.google.com", cli.host());
  13534. ASSERT_EQ(443, cli.port());
  13535. }
  13536. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13537. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13538. std::string cert;
  13539. read_file(CA_CERT_FILE, cert);
  13540. httplib::SSLClient httplib_client("www.google.com");
  13541. // Load CA store first time
  13542. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13543. // Load CA store second time (update)
  13544. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13545. // Verify client is still valid and can make connections
  13546. httplib_client.enable_server_certificate_verification(true);
  13547. auto res = httplib_client.Get("/");
  13548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13549. // Google may return 200 or 301 depending on various factors
  13550. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13551. res->status == StatusCode::MovedPermanently_301);
  13552. }
  13553. TEST(SSLClientTest, ServerNameIndication_Online) {
  13554. auto host = "httpbingo.org";
  13555. auto path = std::string{"/get"};
  13556. SSLClient cli(host, 443);
  13557. auto res = cli.Get(path);
  13558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13559. ASSERT_EQ(StatusCode::OK_200, res->status);
  13560. }
  13561. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13562. // Use a site that will cause SSL verification failure due to self-signed cert
  13563. SSLClient cli("self-signed.badssl.com", 443);
  13564. cli.enable_server_certificate_verification(true);
  13565. auto res = cli.Get("/");
  13566. ASSERT_TRUE(!res);
  13567. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13568. // Verify backend error is captured for SSLServerVerification
  13569. // This occurs when certificate verification fails
  13570. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13571. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13572. EXPECT_NE(0UL, res.ssl_backend_error());
  13573. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13574. res.ssl_error());
  13575. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13576. #if !defined(_WIN32) || \
  13577. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13578. // On non-Windows or when Windows Schannel is disabled, the error comes
  13579. // from OpenSSL's verification
  13580. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13581. res.ssl_backend_error());
  13582. #endif
  13583. #endif
  13584. }
  13585. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13586. // Use a site where hostname doesn't match the certificate
  13587. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13588. SSLClient cli("wrong.host.badssl.com", 443);
  13589. cli.enable_server_certificate_verification(true);
  13590. cli.enable_server_hostname_verification(true);
  13591. auto res = cli.Get("/");
  13592. ASSERT_TRUE(!res);
  13593. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13594. // Verify backend error is captured for hostname verification failure
  13595. EXPECT_NE(0UL, res.ssl_backend_error());
  13596. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13597. res.ssl_error());
  13598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13599. #if !defined(_WIN32) || \
  13600. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13601. // On non-Windows or when Windows Schannel is disabled, the error comes
  13602. // from OpenSSL's hostname verification
  13603. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13604. res.ssl_backend_error());
  13605. #endif
  13606. #endif
  13607. }
  13608. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13609. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13610. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13611. SSLClient cli("www.google.com", 443);
  13612. cli.enable_server_certificate_verification(true);
  13613. auto res = cli.Get("/");
  13614. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13615. }
  13616. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13617. SSLClient cli("www.google.com", 443);
  13618. cli.enable_server_certificate_verification(true);
  13619. cli.enable_windows_certificate_verification(false);
  13620. auto res = cli.Get("/");
  13621. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13622. }
  13623. // The server sends an intermediate cross-signed by a root Windows trusts,
  13624. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13625. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13626. SSLClient cli("accounts.spotify.com", 443);
  13627. auto res = cli.Get("/");
  13628. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13629. << " ssl_backend_error=" << res.ssl_backend_error();
  13630. }
  13631. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13632. // policy status, which no backend reports for a self-signed certificate.
  13633. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13634. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13635. ASSERT_TRUE(svr.is_valid());
  13636. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13637. auto se = detail::scope_exit([&] {
  13638. svr.stop();
  13639. t.join();
  13640. ASSERT_FALSE(svr.is_running());
  13641. });
  13642. svr.wait_until_ready();
  13643. SSLClient cli("127.0.0.1", PORT);
  13644. cli.set_connection_timeout(30);
  13645. auto res = cli.Get("/");
  13646. ASSERT_FALSE(res);
  13647. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13648. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13649. }
  13650. #endif
  13651. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13652. Client cli("https://google.com");
  13653. auto res = cli.Get("/");
  13654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13655. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13656. }
  13657. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13658. SSLClient cli("google.com");
  13659. cli.set_ca_cert_path(CA_CERT_FILE);
  13660. auto res = cli.Get("/");
  13661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13662. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13663. }
  13664. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13665. SSLClient cli("google.com");
  13666. cli.enable_server_certificate_verification(true);
  13667. cli.set_ca_cert_path("hello");
  13668. auto res = cli.Get("/");
  13669. ASSERT_TRUE(!res);
  13670. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13671. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13672. // should be set
  13673. EXPECT_EQ(0, res.ssl_error());
  13674. // Verify backend error is captured for SSLLoadingCerts
  13675. // This error occurs when loading CA certificates fails
  13676. EXPECT_NE(0UL, res.ssl_backend_error());
  13677. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13678. // OpenSSL specific error codes:
  13679. // > openssl errstr 0x80000002
  13680. // error:80000002:system library::No such file or directory
  13681. // > openssl errstr 0xA000126
  13682. // error:0A000126:SSL routines::unexpected eof while reading
  13683. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13684. res.ssl_backend_error() == 0xA000126);
  13685. #endif
  13686. }
  13687. TEST(SSLClientTest, ServerCertificateVerification4) {
  13688. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13689. ASSERT_TRUE(svr.is_valid());
  13690. svr.Get("/test", [&](const Request &, Response &res) {
  13691. res.set_content("test", "text/plain");
  13692. svr.stop();
  13693. ASSERT_TRUE(true);
  13694. });
  13695. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13696. auto se = detail::scope_exit([&] {
  13697. t.join();
  13698. ASSERT_FALSE(svr.is_running());
  13699. });
  13700. svr.wait_until_ready();
  13701. SSLClient cli("127.0.0.1", PORT);
  13702. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13703. cli.enable_server_certificate_verification(true);
  13704. cli.set_connection_timeout(30);
  13705. auto res = cli.Get("/test");
  13706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13707. ASSERT_EQ(StatusCode::OK_200, res->status);
  13708. }
  13709. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13710. std::string cert;
  13711. read_file(CA_CERT_FILE, cert);
  13712. SSLClient cli("google.com");
  13713. cli.load_ca_cert_store(cert.data(), cert.size());
  13714. const auto res = cli.Get("/");
  13715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13716. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13717. }
  13718. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13719. // clang-format off
  13720. static constexpr char cert[] =
  13721. "GlobalSign Root CA\n"
  13722. "==================\n"
  13723. "-----BEGIN CERTIFICATE-----\n"
  13724. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13725. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13726. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13727. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13728. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13729. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13730. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13731. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13732. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13733. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13734. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13735. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13736. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13737. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13738. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13739. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13740. "-----END CERTIFICATE-----\n";
  13741. // clang-format on
  13742. SSLClient cli("google.com");
  13743. cli.load_ca_cert_store(cert, sizeof(cert));
  13744. const auto res = cli.Get("/");
  13745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13746. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13747. }
  13748. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13749. SSLClient cli("www.youtube.com");
  13750. cli.set_ca_cert_path(CA_CERT_FILE);
  13751. cli.enable_server_certificate_verification(true);
  13752. cli.set_follow_location(true);
  13753. auto res = cli.Get("/");
  13754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13755. ASSERT_EQ(StatusCode::OK_200, res->status);
  13756. }
  13757. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13758. SSLClient cli("wWw.YouTube.Com");
  13759. cli.set_ca_cert_path(CA_CERT_FILE);
  13760. cli.enable_server_certificate_verification(true);
  13761. cli.enable_server_hostname_verification(true);
  13762. cli.set_follow_location(true);
  13763. auto res = cli.Get("/");
  13764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13765. ASSERT_EQ(StatusCode::OK_200, res->status);
  13766. }
  13767. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13768. SSLClient cli("gOoGlE.COm");
  13769. cli.enable_server_certificate_verification(true);
  13770. cli.enable_server_hostname_verification(true);
  13771. cli.set_follow_location(true);
  13772. auto res = cli.Get("/");
  13773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13774. ASSERT_EQ(StatusCode::OK_200, res->status);
  13775. }
  13776. TEST(SSLClientTest, Issue2004_Online) {
  13777. Client client("https://google.com");
  13778. client.set_follow_location(true);
  13779. auto res = client.Get("/");
  13780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13781. ASSERT_EQ(StatusCode::OK_200, res->status);
  13782. auto body = res->body;
  13783. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13784. }
  13785. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13786. // Create SSLClient with invalid cert/key to make is_valid() return false
  13787. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13788. "nonexistent_key.pem");
  13789. // is_valid() should be false due to cert loading failure
  13790. ASSERT_FALSE(cli.is_valid());
  13791. auto res = cli.Get("/");
  13792. ASSERT_FALSE(res);
  13793. EXPECT_EQ(Error::SSLConnection, res.error());
  13794. }
  13795. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13796. // Test for Issue #2251: SSL error not properly reported when client cert
  13797. // and key paths are swapped or mismatched
  13798. // This simulates the scenario where user accidentally swaps the cert and key
  13799. // files
  13800. // Using client cert file as private key and vice versa (completely wrong)
  13801. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13802. // Should fail validation due to cert/key mismatch
  13803. ASSERT_FALSE(cli.is_valid());
  13804. // Attempt to make a request should fail with proper error
  13805. auto res = cli.Get("/");
  13806. ASSERT_FALSE(res);
  13807. EXPECT_EQ(Error::SSLConnection, res.error());
  13808. // SSL error should be recorded in the Result object (this is the key fix for
  13809. // Issue #2251)
  13810. auto backend_error = res.ssl_backend_error();
  13811. EXPECT_NE(0u, backend_error);
  13812. }
  13813. // Tests cert/key mismatch detection at the TLS context level
  13814. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13815. // Test that using mismatched cert/key causes connection failure.
  13816. // We verify this at the SSLClient level rather than through internal
  13817. // TLS API functions.
  13818. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13819. cli.enable_server_certificate_verification(false);
  13820. cli.set_connection_timeout(2);
  13821. // The mismatch should cause a connection or handshake error
  13822. auto res = cli.Get("/test");
  13823. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13824. // Either way, the request should fail
  13825. EXPECT_FALSE(res);
  13826. }
  13827. #endif
  13828. #if 0
  13829. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13830. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13831. ASSERT_TRUE(cli != nullptr);
  13832. cli->set_address_family(AF_INET6);
  13833. cli->set_interface("en0");
  13834. auto res = cli->Get("/get");
  13835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13836. ASSERT_EQ(StatusCode::OK_200, res->status);
  13837. }
  13838. #endif
  13839. // Client certificate tests - work with all TLS backends
  13840. #ifdef CPPHTTPLIB_SSL_ENABLED
  13841. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13842. void ClientCertPresent(
  13843. const std::string &client_cert_file,
  13844. const std::string &client_private_key_file,
  13845. const std::string &client_encrypted_private_key_pass = std::string(),
  13846. const ClientCertServerSetup &setup = nullptr) {
  13847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13848. ASSERT_TRUE(svr.is_valid());
  13849. if (setup) { setup(svr); }
  13850. svr.Get("/test", [&](const Request &req, Response &res) {
  13851. res.set_content("test", "text/plain");
  13852. auto cert = req.peer_cert();
  13853. ASSERT_TRUE(static_cast<bool>(cert));
  13854. std::string common_name = cert.subject_cn();
  13855. EXPECT_EQ("Common Name", common_name);
  13856. });
  13857. auto port = svr.bind_to_any_port(HOST);
  13858. ASSERT_LT(0, port);
  13859. thread t = thread([&]() { svr.listen_after_bind(); });
  13860. auto se = detail::scope_exit([&] {
  13861. svr.stop();
  13862. t.join();
  13863. ASSERT_FALSE(svr.is_running());
  13864. });
  13865. svr.wait_until_ready();
  13866. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13867. client_encrypted_private_key_pass);
  13868. cli.enable_server_certificate_verification(false);
  13869. cli.set_connection_timeout(30);
  13870. auto res = cli.Get("/test");
  13871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13872. ASSERT_EQ(StatusCode::OK_200, res->status);
  13873. }
  13874. TEST(SSLClientServerTest, ClientCertPresent) {
  13875. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13876. }
  13877. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13878. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13879. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13880. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13881. }
  13882. // Expects svr, which must require client certificates, to reject a client
  13883. // that has none
  13884. void RejectsClientWithoutCert(SSLServer &svr) {
  13885. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13886. auto port = svr.bind_to_any_port(HOST);
  13887. ASSERT_LT(0, port);
  13888. thread t = thread([&]() { svr.listen_after_bind(); });
  13889. auto se = detail::scope_exit([&] {
  13890. svr.stop();
  13891. t.join();
  13892. ASSERT_FALSE(svr.is_running());
  13893. });
  13894. svr.wait_until_ready();
  13895. SSLClient cli(HOST, port);
  13896. cli.set_connection_timeout(30);
  13897. // Skip the server certificate check, so that the request fails because the
  13898. // client certificate is missing rather than because cert.pem is not trusted
  13899. cli.enable_server_certificate_verification(false);
  13900. auto res = cli.Get("/test");
  13901. ASSERT_FALSE(res);
  13902. // The server rejects the client during the handshake, or on TLS 1.3 right
  13903. // after it, which the client notices on its first write or read
  13904. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13905. res.error() == Error::Write || res.error() == Error::Read)
  13906. << to_string(res.error());
  13907. if (res.error() == Error::SSLConnection) {
  13908. EXPECT_NE(0UL, res.ssl_backend_error());
  13909. }
  13910. // A rejection noticed on the write keeps the TLS error the write hit
  13911. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13912. }
  13913. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13915. ASSERT_TRUE(svr.is_valid());
  13916. if (setup) { setup(svr); }
  13917. RejectsClientWithoutCert(svr);
  13918. }
  13919. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13920. // A server that requires client certificates must keep requiring them after
  13921. // setup changes it, and keep accepting a client that has one
  13922. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13923. ClientCertMissing(setup);
  13924. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13925. setup);
  13926. }
  13927. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13928. ClientCertStillRequired([](SSLServer &svr) {
  13929. ASSERT_TRUE(tls::set_verify_callback(
  13930. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13931. });
  13932. }
  13933. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13934. ClientCertStillRequired([](SSLServer &svr) {
  13935. ASSERT_TRUE(tls::set_verify_callback(
  13936. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13937. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13938. });
  13939. }
  13940. // The client verifies the server certificate during the handshake, so a
  13941. // server that fails the check never gets the client certificate, even when a
  13942. // verifier of the client's own accepts it
  13943. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13944. struct Case {
  13945. const char *trusted_ca;
  13946. const char *host;
  13947. Error error;
  13948. };
  13949. // cert2.pem names localhost: the first client does not trust it, and the
  13950. // second trusts it but asks for another name
  13951. for (const auto &c :
  13952. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13953. Case{SERVER_CERT2_FILE, "example.com",
  13954. Error::SSLServerHostnameVerification}}) {
  13955. for (auto with_verifier : {false, true}) {
  13956. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13957. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13958. CLIENT_CA_CERT_FILE);
  13959. ASSERT_TRUE(svr.is_valid());
  13960. std::atomic<bool> got_client_cert{false};
  13961. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13962. [&](const tls::VerifyContext &) {
  13963. got_client_cert = true;
  13964. return true;
  13965. }));
  13966. auto port = svr.bind_to_any_port("127.0.0.1");
  13967. ASSERT_LT(0, port);
  13968. thread t = thread([&] { svr.listen_after_bind(); });
  13969. svr.wait_until_ready();
  13970. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13971. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  13972. cli.set_ca_cert_path(c.trusted_ca);
  13973. if (with_verifier) {
  13974. cli.set_server_certificate_verifier(
  13975. [](const tls::VerifyContext &) { return true; });
  13976. }
  13977. auto res = cli.Get("/");
  13978. EXPECT_FALSE(res);
  13979. EXPECT_EQ(c.error, res.error());
  13980. svr.stop();
  13981. t.join();
  13982. EXPECT_FALSE(got_client_cert);
  13983. }
  13984. }
  13985. }
  13986. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13987. std::string cert_pem, key_pem, ca_pem;
  13988. read_file(SERVER_CERT_FILE, cert_pem);
  13989. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13990. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13991. ASSERT_TRUE(
  13992. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13993. }
  13994. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13996. ASSERT_TRUE(svr.is_valid());
  13997. UpdateCertsPemWithClientCA(svr);
  13998. RejectsClientWithoutCert(svr);
  13999. }
  14000. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14001. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14002. }
  14003. // A TLS error from one request must not show up in a later request's Result
  14004. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14005. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14006. ASSERT_TRUE(svr.is_valid());
  14007. svr.Get("/test", [](const Request &, Response &res) {
  14008. res.set_content("test", "text/plain");
  14009. });
  14010. auto port = svr.bind_to_any_port(HOST);
  14011. ASSERT_LT(0, port);
  14012. thread t = thread([&]() { svr.listen_after_bind(); });
  14013. auto se = detail::scope_exit([&] {
  14014. svr.stop();
  14015. t.join();
  14016. ASSERT_FALSE(svr.is_running());
  14017. });
  14018. svr.wait_until_ready();
  14019. SSLClient cli(HOST, port);
  14020. cli.set_connection_timeout(30);
  14021. cli.enable_server_hostname_verification(false);
  14022. // cert.pem is not trusted, so the handshake fails
  14023. ASSERT_FALSE(cli.Get("/test"));
  14024. cli.enable_server_certificate_verification(false);
  14025. auto res = cli.Get("/test");
  14026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14027. EXPECT_EQ(0, res.ssl_error());
  14028. EXPECT_EQ(0UL, res.ssl_backend_error());
  14029. }
  14030. // PEM memory-based constructor tests (works with all TLS backends).
  14031. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14032. // terminator after it.
  14033. void PemMemoryClientCertPresent(
  14034. const std::string &client_cert_file,
  14035. const std::string &client_private_key_file,
  14036. const std::string &client_encrypted_private_key_pass = std::string(),
  14037. bool exact_size = false) {
  14038. // Read PEM files into memory
  14039. std::string server_cert_pem, server_key_pem;
  14040. std::string client_ca_pem;
  14041. std::string client_cert_pem, client_key_pem;
  14042. read_file(SERVER_CERT_FILE, server_cert_pem);
  14043. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14044. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14045. read_file(client_cert_file, client_cert_pem);
  14046. read_file(client_private_key_file, client_key_pem);
  14047. std::list<std::vector<char>> exact_copies;
  14048. auto data = [&](const std::string &pem) -> const char * {
  14049. if (!exact_size) { return pem.c_str(); }
  14050. exact_copies.emplace_back(pem.begin(), pem.end());
  14051. return exact_copies.back().data();
  14052. };
  14053. // Create server with PEM memory
  14054. SSLServer::PemMemory server_pem = {
  14055. data(server_cert_pem),
  14056. server_cert_pem.size(),
  14057. data(server_key_pem),
  14058. server_key_pem.size(),
  14059. data(client_ca_pem),
  14060. client_ca_pem.size(),
  14061. nullptr // no password for server key
  14062. };
  14063. SSLServer svr(server_pem);
  14064. ASSERT_TRUE(svr.is_valid());
  14065. svr.Get("/test", [&](const Request &req, Response &res) {
  14066. res.set_content("test", "text/plain");
  14067. auto cert = req.peer_cert();
  14068. ASSERT_TRUE(static_cast<bool>(cert));
  14069. EXPECT_EQ("Common Name", cert.subject_cn());
  14070. });
  14071. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14072. auto se = detail::scope_exit([&] {
  14073. svr.stop();
  14074. t.join();
  14075. ASSERT_FALSE(svr.is_running());
  14076. });
  14077. svr.wait_until_ready();
  14078. // Create client with PEM memory
  14079. const char *password = client_encrypted_private_key_pass.empty()
  14080. ? nullptr
  14081. : client_encrypted_private_key_pass.c_str();
  14082. SSLClient::PemMemory client_pem = {
  14083. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14084. client_key_pem.size(), password};
  14085. SSLClient cli(HOST, PORT, client_pem);
  14086. cli.enable_server_certificate_verification(false);
  14087. cli.set_connection_timeout(30);
  14088. auto res = cli.Get("/test");
  14089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14090. ASSERT_EQ(StatusCode::OK_200, res->status);
  14091. }
  14092. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14093. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14094. }
  14095. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14096. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14097. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14098. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14099. }
  14100. // A server built from PEM memory with a client CA requires client certificates,
  14101. // also when the CA is a NUL-terminated string passed with a length of 0
  14102. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14103. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14104. read_file(SERVER_CERT_FILE, server_cert_pem);
  14105. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14106. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14107. SSLServer::PemMemory server_pem = {
  14108. server_cert_pem.c_str(),
  14109. server_cert_pem.size(),
  14110. server_key_pem.c_str(),
  14111. server_key_pem.size(),
  14112. client_ca_pem.c_str(),
  14113. client_ca_pem.size(),
  14114. nullptr // no password for server key
  14115. };
  14116. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14117. SCOPED_TRACE(client_ca_pem_len);
  14118. server_pem.client_ca_pem_len = client_ca_pem_len;
  14119. SSLServer svr(server_pem);
  14120. ASSERT_TRUE(svr.is_valid());
  14121. RejectsClientWithoutCert(svr);
  14122. }
  14123. // An empty CA fails to load instead of turning the check off
  14124. server_pem.client_ca_pem = "";
  14125. server_pem.client_ca_pem_len = 0;
  14126. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14127. }
  14128. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14129. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14130. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14131. true);
  14132. }
  14133. // A length shorter than the PEM cuts it short, so it no longer loads
  14134. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14135. std::string cert, key;
  14136. read_file(SERVER_CERT_FILE, cert);
  14137. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14138. for (auto cut_cert : {true, false}) {
  14139. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14140. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14141. SSLServer::PemMemory server_pem = {
  14142. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14143. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14144. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14145. key_len, nullptr};
  14146. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14147. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14148. key.c_str(), key_len, nullptr};
  14149. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14150. }
  14151. }
  14152. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14153. class NoListenSSLServer : public SSLServer {
  14154. public:
  14155. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14156. const char *client_ca_cert_file_path,
  14157. const char *client_ca_cert_dir_path = nullptr)
  14158. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14159. client_ca_cert_dir_path),
  14160. stop_(false) {}
  14161. std::atomic_bool stop_;
  14162. private:
  14163. bool process_and_close_socket(socket_t /*sock*/) override {
  14164. // Don't create SSL context
  14165. while (!stop_.load()) {
  14166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14167. }
  14168. return true;
  14169. }
  14170. };
  14171. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14172. CLIENT_CA_CERT_FILE);
  14173. ASSERT_TRUE(svr.is_valid());
  14174. svr.Get("/test", [&](const Request &, Response &res) {
  14175. res.set_content("test", "text/plain");
  14176. });
  14177. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14178. auto se = detail::scope_exit([&] {
  14179. svr.stop_ = true;
  14180. svr.stop();
  14181. t.join();
  14182. ASSERT_FALSE(svr.is_running());
  14183. });
  14184. svr.wait_until_ready();
  14185. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14186. cli.enable_server_certificate_verification(false);
  14187. cli.set_connection_timeout(1);
  14188. auto res = cli.Get("/test");
  14189. ASSERT_TRUE(!res);
  14190. EXPECT_EQ(Error::SSLConnection, res.error());
  14191. // Timeout results in WantRead error code (maps to backend-specific value)
  14192. EXPECT_NE(0, res.ssl_error());
  14193. }
  14194. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14195. // Test SSLServer with client certificate verification using the standard
  14196. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14197. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14198. CLIENT_CA_CERT_DIR);
  14199. ASSERT_TRUE(svr.is_valid());
  14200. svr.Get("/test", [&](const Request &req, Response &res) {
  14201. res.set_content("test", "text/plain");
  14202. auto cert = req.peer_cert();
  14203. ASSERT_TRUE(static_cast<bool>(cert));
  14204. auto common_name = cert.subject_cn();
  14205. EXPECT_EQ("Common Name", common_name);
  14206. });
  14207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14208. auto se = detail::scope_exit([&] {
  14209. svr.stop();
  14210. t.join();
  14211. ASSERT_FALSE(svr.is_running());
  14212. });
  14213. svr.wait_until_ready();
  14214. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14215. cli.enable_server_certificate_verification(false);
  14216. cli.set_connection_timeout(30);
  14217. auto res = cli.Get("/test");
  14218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14219. ASSERT_EQ(StatusCode::OK_200, res->status);
  14220. }
  14221. // Test verify_hostname on every backend: a host is named by a SAN only
  14222. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14223. using namespace httplib::tls;
  14224. // We need a running server to test against
  14225. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14226. ASSERT_TRUE(svr.is_valid());
  14227. svr.Get("/test", [](const Request &, Response &res) {
  14228. res.set_content("ok", "text/plain");
  14229. });
  14230. thread t([&]() { svr.listen(HOST, PORT); });
  14231. auto se = detail::scope_exit([&] {
  14232. svr.stop();
  14233. t.join();
  14234. });
  14235. svr.wait_until_ready();
  14236. bool verify_callback_called = false;
  14237. bool verify_result_wrong = false;
  14238. SSLClient cli(HOST, PORT);
  14239. cli.enable_server_certificate_verification(true);
  14240. cli.set_ca_cert_path(CA_CERT_FILE);
  14241. cli.set_connection_timeout(5);
  14242. // Note: Test certificate has CN="Common Name", not "localhost"
  14243. bool verify_result_cn = false;
  14244. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14245. verify_callback_called = true;
  14246. if (!ctx.cert) return false;
  14247. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14248. verify_result_cn = ctx.check_hostname("Common Name");
  14249. // Test 2: wrong hostname should not match
  14250. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14251. return true; // Accept for the purpose of this test
  14252. });
  14253. auto res = cli.Get("/test");
  14254. // The request may succeed or fail depending on cert configuration
  14255. // but the callback should have been called
  14256. ASSERT_TRUE(verify_callback_called)
  14257. << "Verify callback should have been called";
  14258. EXPECT_FALSE(verify_result_cn)
  14259. << "verify_hostname must not match the certificate CN (no SAN)";
  14260. // Wrong hostname should not match
  14261. EXPECT_FALSE(verify_result_wrong)
  14262. << "verify_hostname should not match 'wronghost.example.com'";
  14263. }
  14264. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14265. // backend verifies it.
  14266. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14267. // Certificate CN is "localhost" and it carries no SAN.
  14268. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14269. ASSERT_TRUE(svr.is_valid());
  14270. svr.Get("/test", [](const Request &, Response &res) {
  14271. res.set_content("ok", "text/plain");
  14272. });
  14273. auto port = svr.bind_to_any_port(HOST);
  14274. thread t([&]() { svr.listen_after_bind(); });
  14275. auto se = detail::scope_exit([&] {
  14276. svr.stop();
  14277. t.join();
  14278. });
  14279. svr.wait_until_ready();
  14280. SSLClient cli("localhost", port);
  14281. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14282. cli.enable_server_certificate_verification(true);
  14283. cli.set_connection_timeout(5);
  14284. auto res = cli.Get("/test");
  14285. ASSERT_FALSE(res);
  14286. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14287. // The same certificate is accepted once host name verification is off, so the
  14288. // failure above is the host name and not the chain.
  14289. cli.enable_server_hostname_verification(false);
  14290. res = cli.Get("/test");
  14291. ASSERT_TRUE(res) << to_string(res.error());
  14292. EXPECT_EQ(StatusCode::OK_200, res->status);
  14293. }
  14294. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14295. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14296. // X509_check_ip behavior and must hold for every backend.
  14297. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14298. using namespace httplib::tls;
  14299. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14300. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14301. ASSERT_TRUE(svr.is_valid());
  14302. svr.Get("/test", [](const Request &, Response &res) {
  14303. res.set_content("ok", "text/plain");
  14304. });
  14305. thread t([&]() { svr.listen(HOST, PORT); });
  14306. auto se = detail::scope_exit([&] {
  14307. svr.stop();
  14308. t.join();
  14309. });
  14310. svr.wait_until_ready();
  14311. bool verify_callback_called = false;
  14312. bool ip_matched_via_cn = true;
  14313. SSLClient cli(HOST, PORT);
  14314. cli.enable_server_certificate_verification(true);
  14315. cli.set_ca_cert_path(CA_CERT_FILE);
  14316. cli.set_connection_timeout(5);
  14317. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14318. verify_callback_called = true;
  14319. if (!ctx.cert) return false;
  14320. // The IP appears only in the CN, so it must NOT be accepted.
  14321. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14322. return true; // Accept for the purpose of this test
  14323. });
  14324. cli.Get("/test");
  14325. ASSERT_TRUE(verify_callback_called)
  14326. << "Verify callback should have been called";
  14327. EXPECT_FALSE(ip_matched_via_cn)
  14328. << "An IP host must not be authenticated via the certificate CN";
  14329. }
  14330. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14331. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14332. using namespace httplib::tls;
  14333. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14334. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14335. ASSERT_TRUE(svr.is_valid());
  14336. svr.Get("/test", [](const Request &, Response &res) {
  14337. res.set_content("ok", "text/plain");
  14338. });
  14339. thread t([&]() { svr.listen(HOST, PORT); });
  14340. auto se = detail::scope_exit([&] {
  14341. svr.stop();
  14342. t.join();
  14343. });
  14344. svr.wait_until_ready();
  14345. bool verify_callback_called = false;
  14346. bool san_matched = false;
  14347. bool wrong_ipv6_matched = true;
  14348. bool cn_ipv6_matched = true;
  14349. SSLClient cli(HOST, PORT);
  14350. cli.enable_server_certificate_verification(true);
  14351. cli.set_ca_cert_path(CA_CERT_FILE);
  14352. cli.set_connection_timeout(5);
  14353. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14354. verify_callback_called = true;
  14355. if (!ctx.cert) return false;
  14356. // Matches the IPv6 iPAddress SAN.
  14357. san_matched = ctx.check_hostname("2001:db8::1");
  14358. // A different IPv6 address must not match.
  14359. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14360. // "::1" lives only in the CN, so it must not be accepted.
  14361. cn_ipv6_matched = ctx.check_hostname("::1");
  14362. return true; // Accept for the purpose of this test
  14363. });
  14364. cli.Get("/test");
  14365. ASSERT_TRUE(verify_callback_called)
  14366. << "Verify callback should have been called";
  14367. EXPECT_TRUE(san_matched)
  14368. << "verify_hostname should match an IPv6 iPAddress SAN";
  14369. EXPECT_FALSE(wrong_ipv6_matched)
  14370. << "verify_hostname should not match a non-matching IPv6 address";
  14371. EXPECT_FALSE(cn_ipv6_matched)
  14372. << "An IPv6 host must not be authenticated via the certificate CN";
  14373. }
  14374. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14375. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14376. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14377. using namespace httplib::tls;
  14378. // SANs: DNS:a.zz, IP:42.46.122.122
  14379. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14380. ASSERT_TRUE(svr.is_valid());
  14381. svr.Get("/test", [](const Request &, Response &res) {
  14382. res.set_content("ok", "text/plain");
  14383. });
  14384. auto port = svr.bind_to_any_port(HOST);
  14385. thread t([&]() { svr.listen_after_bind(); });
  14386. auto se = detail::scope_exit([&] {
  14387. svr.stop();
  14388. t.join();
  14389. });
  14390. svr.wait_until_ready();
  14391. bool verify_callback_called = false;
  14392. bool dns_san_matched = false;
  14393. bool ip_san_matched = false;
  14394. bool ip_matched_via_dns_san = true;
  14395. bool dns_matched_via_ip_san = true;
  14396. bool cn_matched_next_to_dns_san = true;
  14397. SSLClient cli(HOST, port);
  14398. cli.enable_server_certificate_verification(true);
  14399. cli.set_ca_cert_path(CA_CERT_FILE);
  14400. cli.set_connection_timeout(5);
  14401. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14402. verify_callback_called = true;
  14403. if (!ctx.cert) return false;
  14404. dns_san_matched = ctx.check_hostname("a.zz");
  14405. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14406. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14407. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14408. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14409. return true; // Accept for the purpose of this test
  14410. });
  14411. cli.Get("/test");
  14412. ASSERT_TRUE(verify_callback_called)
  14413. << "Verify callback should have been called";
  14414. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14415. EXPECT_TRUE(ip_san_matched)
  14416. << "verify_hostname should match an iPAddress SAN";
  14417. EXPECT_FALSE(ip_matched_via_dns_san)
  14418. << "An IP host must not be authenticated via a dNSName SAN";
  14419. EXPECT_FALSE(dns_matched_via_ip_san)
  14420. << "A DNS host must not be authenticated via an iPAddress SAN";
  14421. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14422. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14423. }
  14424. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14425. // "www.*.example.test" names one host and not every host under example.test.
  14426. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14427. using namespace httplib::tls;
  14428. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14429. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14430. ASSERT_TRUE(svr.is_valid());
  14431. svr.Get("/test", [](const Request &, Response &res) {
  14432. res.set_content("ok", "text/plain");
  14433. });
  14434. auto port = svr.bind_to_any_port(HOST);
  14435. thread t([&]() { svr.listen_after_bind(); });
  14436. auto se = detail::scope_exit([&] {
  14437. svr.stop();
  14438. t.join();
  14439. });
  14440. svr.wait_until_ready();
  14441. bool verify_callback_called = false;
  14442. bool leftmost_wildcard_matched = false;
  14443. bool wildcard_spanned_labels = true;
  14444. bool inner_wildcard_matched = true;
  14445. SSLClient cli(HOST, port);
  14446. cli.enable_server_certificate_verification(true);
  14447. cli.set_ca_cert_path(CA_CERT_FILE);
  14448. cli.set_connection_timeout(5);
  14449. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14450. verify_callback_called = true;
  14451. if (!ctx.cert) return false;
  14452. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14453. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14454. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14455. return true; // Accept for the purpose of this test
  14456. });
  14457. cli.Get("/test");
  14458. ASSERT_TRUE(verify_callback_called)
  14459. << "Verify callback should have been called";
  14460. EXPECT_TRUE(leftmost_wildcard_matched)
  14461. << "A leftmost wildcard should match a single label";
  14462. EXPECT_FALSE(wildcard_spanned_labels)
  14463. << "A wildcard label must not match more than one label";
  14464. EXPECT_FALSE(inner_wildcard_matched)
  14465. << "A wildcard outside the leftmost label must not be honoured";
  14466. }
  14467. // sans() must report each SAN entry under its own type.
  14468. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14469. using namespace httplib::tls;
  14470. // SANs: DNS:a.zz, IP:42.46.122.122
  14471. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14472. ASSERT_TRUE(svr.is_valid());
  14473. svr.Get("/test", [](const Request &, Response &res) {
  14474. res.set_content("ok", "text/plain");
  14475. });
  14476. auto port = svr.bind_to_any_port(HOST);
  14477. thread t([&]() { svr.listen_after_bind(); });
  14478. auto se = detail::scope_exit([&] {
  14479. svr.stop();
  14480. t.join();
  14481. });
  14482. svr.wait_until_ready();
  14483. bool verify_callback_called = false;
  14484. std::vector<SanEntry> sans;
  14485. SSLClient cli(HOST, port);
  14486. cli.enable_server_certificate_verification(true);
  14487. cli.set_ca_cert_path(CA_CERT_FILE);
  14488. cli.set_connection_timeout(5);
  14489. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14490. verify_callback_called = true;
  14491. if (!ctx.cert) return false;
  14492. sans = ctx.sans();
  14493. return true; // Accept for the purpose of this test
  14494. });
  14495. cli.Get("/test");
  14496. ASSERT_TRUE(verify_callback_called)
  14497. << "Verify callback should have been called";
  14498. auto has_san = [&](SanType type, const std::string &value) {
  14499. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14500. return san.type == type && san.value == value;
  14501. });
  14502. };
  14503. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14504. << "sans() should report the dNSName SAN";
  14505. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14506. << "sans() should report the iPAddress SAN";
  14507. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14508. << "sans() must not report the dNSName SAN as an address";
  14509. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14510. << "sans() must not report the iPAddress SAN as a DNS name";
  14511. }
  14512. #endif
  14513. // mbedTLS-specific callback constructor test
  14514. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14515. #ifdef CPPHTTPLIB_SSL_ENABLED
  14516. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14518. ASSERT_TRUE(svr.is_valid());
  14519. // Set up a handler to verify client certificate is present
  14520. bool client_cert_verified = false;
  14521. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14522. // Verify that client certificate was provided
  14523. client_cert_verified = true;
  14524. res.set_content("success", "text/plain");
  14525. });
  14526. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14527. auto se = detail::scope_exit([&] {
  14528. svr.stop();
  14529. t.join();
  14530. ASSERT_FALSE(svr.is_running());
  14531. });
  14532. svr.wait_until_ready();
  14533. // Client with certificate
  14534. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14535. cli.enable_server_certificate_verification(false);
  14536. cli.set_connection_timeout(30);
  14537. auto res = cli.Get("/test");
  14538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14539. ASSERT_EQ(StatusCode::OK_200, res->status);
  14540. ASSERT_TRUE(client_cert_verified);
  14541. EXPECT_EQ("success", res->body);
  14542. }
  14543. #endif
  14544. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14545. // backends
  14546. #ifdef CPPHTTPLIB_SSL_ENABLED
  14547. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14548. using namespace httplib::tls;
  14549. // Test that when client CA cert file is provided,
  14550. // the server properly requests and validates client certificates
  14551. // Create a server with client authentication
  14552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14553. ASSERT_TRUE(svr.is_valid());
  14554. bool handler_called = false;
  14555. svr.Get("/test", [&](const Request &req, Response &res) {
  14556. handler_called = true;
  14557. // Verify that a client certificate was provided
  14558. auto cert = req.peer_cert();
  14559. ASSERT_TRUE(static_cast<bool>(cert));
  14560. // Get the issuer name
  14561. std::string issuer_str = cert.issuer_name();
  14562. ASSERT_FALSE(issuer_str.empty());
  14563. // The client certificate should be issued by our test CA
  14564. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14565. res.set_content("authenticated", "text/plain");
  14566. });
  14567. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14568. auto se = detail::scope_exit([&] {
  14569. svr.stop();
  14570. t.join();
  14571. ASSERT_FALSE(svr.is_running());
  14572. });
  14573. svr.wait_until_ready();
  14574. // Connect with a client certificate issued by the CA
  14575. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14576. cli.enable_server_certificate_verification(false);
  14577. cli.set_connection_timeout(30);
  14578. auto res = cli.Get("/test");
  14579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14580. ASSERT_EQ(StatusCode::OK_200, res->status);
  14581. ASSERT_TRUE(handler_called);
  14582. EXPECT_EQ("authenticated", res->body);
  14583. }
  14584. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14585. using namespace httplib::tls;
  14586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14587. ASSERT_TRUE(svr.is_valid());
  14588. svr.Get("/test", [](const Request &, Response &res) {
  14589. res.set_content("ok", "text/plain");
  14590. });
  14591. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14592. auto se = detail::scope_exit([&] {
  14593. svr.stop();
  14594. t.join();
  14595. });
  14596. svr.wait_until_ready();
  14597. SSLClient cli(HOST, PORT);
  14598. cli.enable_server_certificate_verification(false);
  14599. cli.set_connection_timeout(30);
  14600. bool cert_checked = false;
  14601. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14602. if (ctx.cert) {
  14603. auto sans = ctx.sans();
  14604. // Test certificate may or may not have SANs - just verify the API
  14605. // works If SANs exist, verify the types are valid
  14606. for (const auto &san : sans) {
  14607. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14608. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14609. san.type == SanType::OTHER);
  14610. EXPECT_FALSE(san.value.empty());
  14611. }
  14612. cert_checked = true;
  14613. }
  14614. return true;
  14615. });
  14616. auto res = cli.Get("/test");
  14617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14618. EXPECT_TRUE(cert_checked);
  14619. }
  14620. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14621. using namespace httplib::tls;
  14622. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14623. ASSERT_TRUE(svr.is_valid());
  14624. svr.Get("/test", [](const Request &, Response &res) {
  14625. res.set_content("ok", "text/plain");
  14626. });
  14627. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14628. auto se = detail::scope_exit([&] {
  14629. svr.stop();
  14630. t.join();
  14631. });
  14632. svr.wait_until_ready();
  14633. SSLClient cli(HOST, PORT);
  14634. cli.enable_server_certificate_verification(false);
  14635. cli.set_connection_timeout(30);
  14636. bool validity_checked = false;
  14637. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14638. if (ctx.cert) {
  14639. time_t not_before = 0, not_after = 0;
  14640. bool result = ctx.validity(not_before, not_after);
  14641. EXPECT_TRUE(result);
  14642. // Verify that not_before < now < not_after for a valid cert
  14643. time_t now = time(nullptr);
  14644. EXPECT_LT(not_before, now);
  14645. EXPECT_GT(not_after, now);
  14646. validity_checked = true;
  14647. }
  14648. return true;
  14649. });
  14650. auto res = cli.Get("/test");
  14651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14652. EXPECT_TRUE(validity_checked);
  14653. }
  14654. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14655. using namespace httplib::tls;
  14656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14657. ASSERT_TRUE(svr.is_valid());
  14658. svr.Get("/test", [](const Request &, Response &res) {
  14659. res.set_content("ok", "text/plain");
  14660. });
  14661. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14662. auto se = detail::scope_exit([&] {
  14663. svr.stop();
  14664. t.join();
  14665. });
  14666. svr.wait_until_ready();
  14667. SSLClient cli(HOST, PORT);
  14668. cli.enable_server_certificate_verification(false);
  14669. cli.set_connection_timeout(30);
  14670. bool serial_checked = false;
  14671. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14672. if (ctx.cert) {
  14673. std::string serial = ctx.serial();
  14674. EXPECT_FALSE(serial.empty());
  14675. // Serial should be a hex string
  14676. for (char c : serial) {
  14677. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14678. (c >= 'a' && c <= 'f'));
  14679. }
  14680. serial_checked = true;
  14681. }
  14682. return true;
  14683. });
  14684. auto res = cli.Get("/test");
  14685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14686. EXPECT_TRUE(serial_checked);
  14687. }
  14688. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14689. // Test 1: Valid CA file - no error should be recorded
  14690. {
  14691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14692. CLIENT_CA_CERT_FILE);
  14693. ASSERT_TRUE(svr.is_valid());
  14694. // With valid setup, last_ssl_error should be 0
  14695. EXPECT_EQ(0, svr.ssl_last_error());
  14696. }
  14697. // Test 2: Invalid CA file content
  14698. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14699. {
  14700. // Create a temporary file with completely invalid content
  14701. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14702. {
  14703. std::ofstream ofs(temp_invalid_ca);
  14704. ofs << "This is not a certificate file at all\n";
  14705. ofs << "Just plain text content\n";
  14706. }
  14707. // Create server with invalid CA file
  14708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14709. // Clean up temporary file
  14710. std::remove(temp_invalid_ca);
  14711. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14712. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14713. // Note: SSL_CTX_load_verify_locations typically fails first,
  14714. // but our error handling code path is still exercised
  14715. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14716. }
  14717. }
  14718. TEST(VerifyCallbackTest, VerifyContextFields) {
  14719. using namespace httplib::tls;
  14720. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14721. ASSERT_TRUE(svr.is_valid());
  14722. svr.Get("/test", [](const Request &, Response &res) {
  14723. res.set_content("ok", "text/plain");
  14724. });
  14725. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14726. auto se = detail::scope_exit([&] {
  14727. svr.stop();
  14728. t.join();
  14729. });
  14730. svr.wait_until_ready();
  14731. SSLClient cli(HOST, PORT);
  14732. cli.enable_server_certificate_verification(false);
  14733. cli.set_connection_timeout(30);
  14734. int callback_count = 0;
  14735. bool saw_leaf_cert = false;
  14736. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14737. if (ctx.cert) {
  14738. callback_count++;
  14739. // We should see at least one certificate (the leaf)
  14740. std::string cn = ctx.subject_cn();
  14741. if (!cn.empty()) { saw_leaf_cert = true; }
  14742. // Verify context fields are populated
  14743. EXPECT_NE(ctx.session, nullptr);
  14744. EXPECT_GE(ctx.depth, 0);
  14745. }
  14746. return true;
  14747. });
  14748. auto res = cli.Get("/test");
  14749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14750. EXPECT_GT(callback_count, 0);
  14751. EXPECT_TRUE(saw_leaf_cert);
  14752. }
  14753. // A verifier that accepts runs alongside the built-in verification, and is the
  14754. // only check once that is turned off.
  14755. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14756. using namespace httplib::tls;
  14757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14758. ASSERT_TRUE(svr.is_valid());
  14759. svr.Get("/test", [](const Request &, Response &res) {
  14760. res.set_content("ok", "text/plain");
  14761. });
  14762. auto port = svr.bind_to_any_port(HOST);
  14763. thread t([&]() { svr.listen_after_bind(); });
  14764. auto se = detail::scope_exit([&] {
  14765. svr.stop();
  14766. t.join();
  14767. });
  14768. svr.wait_until_ready();
  14769. SSLClient cli(HOST, port);
  14770. cli.enable_server_hostname_verification(false);
  14771. auto calls = 0;
  14772. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14773. calls++;
  14774. return true;
  14775. });
  14776. // cert.pem is not trusted
  14777. auto res = cli.Get("/test");
  14778. ASSERT_FALSE(res);
  14779. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14780. EXPECT_GT(calls, 0);
  14781. cli.enable_server_certificate_verification(false);
  14782. res = cli.Get("/test");
  14783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14784. EXPECT_EQ("ok", res->body);
  14785. }
  14786. // A verifier belongs to the client that set it, not to the thread that set it.
  14787. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14788. using namespace httplib::tls;
  14789. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14790. ASSERT_TRUE(svr.is_valid());
  14791. svr.Get("/test", [](const Request &, Response &res) {
  14792. res.set_content("ok", "text/plain");
  14793. });
  14794. auto port = svr.bind_to_any_port(HOST);
  14795. thread t([&]() { svr.listen_after_bind(); });
  14796. auto se = detail::scope_exit([&] {
  14797. svr.stop();
  14798. t.join();
  14799. });
  14800. svr.wait_until_ready();
  14801. auto rejecting_calls = 0;
  14802. SSLClient rejecting(HOST, port);
  14803. rejecting.enable_server_certificate_verification(false);
  14804. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14805. rejecting_calls++;
  14806. return false;
  14807. });
  14808. auto accepting_calls = 0;
  14809. SSLClient accepting(HOST, port);
  14810. accepting.enable_server_certificate_verification(false);
  14811. // Set on another thread than the requests below.
  14812. thread([&]() {
  14813. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14814. accepting_calls++;
  14815. return true;
  14816. });
  14817. }).join();
  14818. // Requested on another thread than the verifier was set on.
  14819. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14820. EXPECT_GT(rejecting_calls, 0);
  14821. auto res = accepting.Get("/test");
  14822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14823. EXPECT_GT(accepting_calls, 0);
  14824. }
  14825. // A verifier replaced while a handshake runs it lives until it returns.
  14826. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14827. using namespace httplib::tls;
  14828. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14829. ASSERT_TRUE(svr.is_valid());
  14830. svr.Get("/test", [](const Request &, Response &res) {
  14831. res.set_content("ok", "text/plain");
  14832. });
  14833. auto port = svr.bind_to_any_port(HOST);
  14834. thread t([&]() { svr.listen_after_bind(); });
  14835. auto se = detail::scope_exit([&] {
  14836. svr.stop();
  14837. t.join();
  14838. });
  14839. svr.wait_until_ready();
  14840. SSLClient cli(HOST, port);
  14841. cli.enable_server_certificate_verification(false);
  14842. std::promise<void> entered;
  14843. std::promise<void> replaced;
  14844. auto replaced_future = replaced.get_future();
  14845. auto first_call = true;
  14846. // Long enough to live on the heap
  14847. std::string expected(64, 'v');
  14848. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14849. if (first_call) {
  14850. first_call = false;
  14851. entered.set_value();
  14852. replaced_future.wait();
  14853. }
  14854. return expected == std::string(64, 'v');
  14855. });
  14856. thread request([&]() {
  14857. auto res = cli.Get("/test");
  14858. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14859. });
  14860. entered.get_future().wait();
  14861. cli.set_server_certificate_verifier(
  14862. [](const VerifyContext &) { return true; });
  14863. replaced.set_value();
  14864. request.join();
  14865. }
  14866. // VerifyContext::session is the same handle the other tls:: functions take.
  14867. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14868. using namespace httplib::tls;
  14869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14870. ASSERT_TRUE(svr.is_valid());
  14871. svr.Get("/test", [](const Request &, Response &res) {
  14872. res.set_content("ok", "text/plain");
  14873. });
  14874. auto port = svr.bind_to_any_port(HOST);
  14875. thread t([&]() { svr.listen_after_bind(); });
  14876. auto se = detail::scope_exit([&] {
  14877. svr.stop();
  14878. t.join();
  14879. });
  14880. svr.wait_until_ready();
  14881. SSLClient cli(HOST, port);
  14882. cli.enable_server_certificate_verification(false);
  14883. session_t verifier_session = nullptr;
  14884. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14885. verifier_session = ctx.session;
  14886. return true;
  14887. });
  14888. session_t session_verifier_session = nullptr;
  14889. cli.set_session_verifier([&](session_t session) {
  14890. session_verifier_session = session;
  14891. return SSLVerifierResponse::NoDecisionMade;
  14892. });
  14893. auto res = cli.Get("/test");
  14894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14895. EXPECT_NE(nullptr, verifier_session);
  14896. EXPECT_EQ(session_verifier_session, verifier_session);
  14897. }
  14898. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14899. using httplib::tls::TlsError;
  14900. // Test that verify_error_to_string returns empty for success
  14901. std::string success_str = TlsError::verify_error_to_string(0);
  14902. EXPECT_TRUE(success_str.empty());
  14903. // Test that verify_error_to_string returns non-empty for error codes
  14904. // Using a common error code (certificate expired)
  14905. std::string error_str =
  14906. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14907. EXPECT_FALSE(error_str.empty());
  14908. }
  14909. TEST(SessionVerifierTest, CertificateAccepted) {
  14910. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14911. ASSERT_TRUE(svr.is_valid());
  14912. svr.Get("/test", [](const Request &, Response &res) {
  14913. res.set_content("ok", "text/plain");
  14914. });
  14915. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14916. auto se = detail::scope_exit([&] {
  14917. svr.stop();
  14918. t.join();
  14919. });
  14920. svr.wait_until_ready();
  14921. SSLClient cli(HOST, PORT);
  14922. cli.enable_server_certificate_verification(false);
  14923. cli.set_connection_timeout(30);
  14924. bool callback_called = false;
  14925. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14926. EXPECT_NE(session, nullptr);
  14927. callback_called = true;
  14928. return SSLVerifierResponse::CertificateAccepted;
  14929. });
  14930. auto res = cli.Get("/test");
  14931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14932. EXPECT_EQ(200, res->status);
  14933. EXPECT_TRUE(callback_called);
  14934. }
  14935. TEST(SessionVerifierTest, CertificateRejected) {
  14936. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14937. ASSERT_TRUE(svr.is_valid());
  14938. svr.Get("/test", [](const Request &, Response &res) {
  14939. res.set_content("ok", "text/plain");
  14940. });
  14941. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14942. auto se = detail::scope_exit([&] {
  14943. svr.stop();
  14944. t.join();
  14945. });
  14946. svr.wait_until_ready();
  14947. SSLClient cli(HOST, PORT);
  14948. cli.enable_server_certificate_verification(false);
  14949. cli.set_connection_timeout(30);
  14950. bool callback_called = false;
  14951. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14952. EXPECT_NE(session, nullptr);
  14953. callback_called = true;
  14954. return SSLVerifierResponse::CertificateRejected;
  14955. });
  14956. auto res = cli.Get("/test");
  14957. EXPECT_FALSE(res);
  14958. EXPECT_TRUE(callback_called);
  14959. }
  14960. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14962. ASSERT_TRUE(svr.is_valid());
  14963. svr.Get("/test", [](const Request &, Response &res) {
  14964. res.set_content("ok", "text/plain");
  14965. });
  14966. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14967. auto se = detail::scope_exit([&] {
  14968. svr.stop();
  14969. t.join();
  14970. });
  14971. svr.wait_until_ready();
  14972. // NoDecisionMade with verification disabled should succeed (no default check)
  14973. SSLClient cli(HOST, PORT);
  14974. cli.enable_server_certificate_verification(false);
  14975. cli.set_connection_timeout(30);
  14976. bool callback_called = false;
  14977. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14978. EXPECT_NE(session, nullptr);
  14979. callback_called = true;
  14980. return SSLVerifierResponse::NoDecisionMade;
  14981. });
  14982. auto res = cli.Get("/test");
  14983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14984. EXPECT_EQ(200, res->status);
  14985. EXPECT_TRUE(callback_called);
  14986. }
  14987. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14988. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14989. ASSERT_TRUE(svr.is_valid());
  14990. svr.Get("/test", [](const Request &, Response &res) {
  14991. res.set_content("ok", "text/plain");
  14992. });
  14993. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14994. auto se = detail::scope_exit([&] {
  14995. svr.stop();
  14996. t.join();
  14997. });
  14998. svr.wait_until_ready();
  14999. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15000. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15001. // so we only check that the request fails, not whether the callback was
  15002. // called.
  15003. SSLClient cli(HOST, PORT);
  15004. cli.enable_server_certificate_verification(true);
  15005. cli.set_connection_timeout(30);
  15006. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15007. EXPECT_NE(session, nullptr);
  15008. return SSLVerifierResponse::NoDecisionMade;
  15009. });
  15010. auto res = cli.Get("/test");
  15011. EXPECT_FALSE(res);
  15012. }
  15013. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15014. // Test SSL server using PemMemory constructor with client CA certificates
  15015. // Read PEM files
  15016. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15017. read_file(SERVER_CERT_FILE, server_cert_pem);
  15018. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15019. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15020. // Create SSLServer with PemMemory constructor including client CA
  15021. SSLServer::PemMemory server_pem = {
  15022. server_cert_pem.c_str(),
  15023. server_cert_pem.size(),
  15024. server_key_pem.c_str(),
  15025. server_key_pem.size(),
  15026. client_ca_pem.c_str(),
  15027. client_ca_pem.size(),
  15028. nullptr // no password for server key
  15029. };
  15030. SSLServer svr(server_pem);
  15031. ASSERT_TRUE(svr.is_valid());
  15032. // No SSL error should be recorded for valid setup
  15033. EXPECT_EQ(0, svr.ssl_last_error());
  15034. // Set up server endpoints
  15035. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15036. res.set_content("ok", "text/plain");
  15037. });
  15038. // Start server in a thread
  15039. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15040. svr.wait_until_ready();
  15041. // Connect with client certificate (using constructor with paths)
  15042. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15043. cli.enable_server_certificate_verification(false);
  15044. auto res = cli.Get("/test-pem-ca");
  15045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15046. EXPECT_EQ(200, res->status);
  15047. EXPECT_EQ("ok", res->body);
  15048. svr.stop();
  15049. server_thread.join();
  15050. }
  15051. #endif
  15052. #ifdef _WIN32
  15053. TEST(CleanupTest, WSACleanup) {
  15054. int ret = WSACleanup();
  15055. ASSERT_EQ(0, ret);
  15056. }
  15057. #endif
  15058. #ifndef CPPHTTPLIB_SSL_ENABLED
  15059. TEST(NoSSLSupport, SimpleInterface) {
  15060. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15061. }
  15062. #endif
  15063. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15064. TEST(InvalidScheme, SimpleInterface) {
  15065. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15066. }
  15067. #endif
  15068. TEST(NoScheme, SimpleInterface) {
  15069. Client cli("yahoo.com:80");
  15070. ASSERT_TRUE(cli.is_valid());
  15071. }
  15072. TEST(SendAPI, SimpleInterface_Online) {
  15073. Client cli("http://yahoo.com");
  15074. Request req;
  15075. req.method = "GET";
  15076. req.path = "/";
  15077. auto res = cli.send(req);
  15078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15079. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15080. }
  15081. TEST(SendAPI, WithParamsInRequest) {
  15082. Server svr;
  15083. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15084. EXPECT_TRUE(req.has_param("test"));
  15085. EXPECT_EQ("test_value", req.get_param_value("test"));
  15086. });
  15087. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15088. auto se = detail::scope_exit([&] {
  15089. svr.stop();
  15090. t.join();
  15091. ASSERT_FALSE(svr.is_running());
  15092. });
  15093. svr.wait_until_ready();
  15094. Client cli(HOST, PORT);
  15095. {
  15096. Request req;
  15097. req.method = "GET";
  15098. req.path = "/";
  15099. req.params.emplace("test", "test_value");
  15100. auto res = cli.send(req);
  15101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15102. }
  15103. {
  15104. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15106. }
  15107. }
  15108. TEST(ClientImplMethods, GetSocketTest) {
  15109. httplib::Server svr;
  15110. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15111. res.status = StatusCode::OK_200;
  15112. });
  15113. auto port = svr.bind_to_any_port("127.0.0.1");
  15114. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15115. auto se = detail::scope_exit([&] {
  15116. svr.stop();
  15117. thread.join();
  15118. ASSERT_FALSE(svr.is_running());
  15119. });
  15120. svr.wait_until_ready();
  15121. {
  15122. httplib::Client cli("127.0.0.1", port);
  15123. cli.set_keep_alive(true);
  15124. // Use the behavior of cpp-httplib of opening the connection
  15125. // only when the first request happens. If that changes,
  15126. // this test would be obsolete.
  15127. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15128. // This also implicitly tests the server. But other tests would fail much
  15129. // earlier than this one to be considered.
  15130. auto res = cli.Get("/");
  15131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15132. EXPECT_EQ(StatusCode::OK_200, res->status);
  15133. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15134. }
  15135. }
  15136. #ifdef CPPHTTPLIB_SSL_ENABLED
  15137. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15138. Client cli("http://yahoo.com");
  15139. auto res = cli.Get("/");
  15140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15141. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15142. cli.set_follow_location(true);
  15143. res = cli.Get("/");
  15144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15145. EXPECT_EQ(StatusCode::OK_200, res->status);
  15146. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15147. }
  15148. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15149. Client cli("https://yahoo.com");
  15150. auto res = cli.Get("/");
  15151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15152. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15153. cli.set_follow_location(true);
  15154. res = cli.Get("/");
  15155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15156. EXPECT_EQ(StatusCode::OK_200, res->status);
  15157. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15158. }
  15159. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15160. Client cli("https://yahoo.com");
  15161. auto res = cli.Get("/");
  15162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15163. ASSERT_FALSE(!res);
  15164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15165. ASSERT_FALSE(res == nullptr);
  15166. ASSERT_TRUE(res != nullptr);
  15167. EXPECT_EQ(Error::Success, res.error());
  15168. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15169. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15170. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15171. cli.set_follow_location(true);
  15172. res = cli.Get("/");
  15173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15174. EXPECT_EQ(Error::Success, res.error());
  15175. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15176. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15177. EXPECT_EQ(StatusCode::OK_200, res->status);
  15178. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15179. }
  15180. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15181. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15182. Client cli("https://cdnjs.cloudflare.com");
  15183. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15184. Headers{{"Accept-Encoding", "br"}});
  15185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15186. EXPECT_EQ(StatusCode::OK_200, res->status);
  15187. EXPECT_EQ(287630U, res->body.size());
  15188. EXPECT_EQ("application/javascript; charset=utf-8",
  15189. res->get_header_value("Content-Type"));
  15190. }
  15191. #endif
  15192. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15193. #undef REDIR_HOST // Silence compiler warning
  15194. #define REDIR_HOST "https://httpbingo.org"
  15195. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15196. Client cli(REDIR_HOST);
  15197. cli.set_follow_location(true);
  15198. auto res =
  15199. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15201. EXPECT_EQ(StatusCode::OK_200, res->status);
  15202. }
  15203. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15204. Client cli(REDIR_HOST);
  15205. cli.set_follow_location(true);
  15206. Params params;
  15207. params.emplace("url", "http://example.com");
  15208. params.emplace("status_code", "302");
  15209. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15211. EXPECT_EQ(StatusCode::OK_200, res->status);
  15212. }
  15213. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15214. Client cli(REDIR_HOST);
  15215. cli.set_follow_location(true);
  15216. Params params;
  15217. params.emplace("url", "http://example.com");
  15218. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15220. EXPECT_EQ(StatusCode::OK_200, res->status);
  15221. }
  15222. TEST(HttpToHttpsRedirectTest, CertFile) {
  15223. auto ssl_port = PORT + 1;
  15224. Server svr;
  15225. ASSERT_TRUE(svr.is_valid());
  15226. svr.Get("/index", [&](const Request &, Response &res) {
  15227. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15228. "/index");
  15229. svr.stop();
  15230. });
  15231. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15232. ASSERT_TRUE(ssl_svr.is_valid());
  15233. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15234. res.set_content("test", "text/plain");
  15235. ssl_svr.stop();
  15236. });
  15237. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15238. thread t2 =
  15239. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15240. auto se = detail::scope_exit([&] {
  15241. t2.join();
  15242. t.join();
  15243. ASSERT_FALSE(svr.is_running());
  15244. });
  15245. svr.wait_until_ready();
  15246. ssl_svr.wait_until_ready();
  15247. Client cli("127.0.0.1", PORT);
  15248. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15249. cli.enable_server_certificate_verification(true);
  15250. cli.set_follow_location(true);
  15251. cli.set_connection_timeout(30);
  15252. auto res = cli.Get("/index");
  15253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15254. ASSERT_EQ(StatusCode::OK_200, res->status);
  15255. }
  15256. TEST(SSLClientRedirectTest, CertFile) {
  15257. auto ssl_port = PORT + 1;
  15258. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15259. ASSERT_TRUE(ssl_svr1.is_valid());
  15260. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15261. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15262. "/index");
  15263. ssl_svr1.stop();
  15264. });
  15265. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15266. ASSERT_TRUE(ssl_svr2.is_valid());
  15267. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15268. res.set_content("test", "text/plain");
  15269. ssl_svr2.stop();
  15270. });
  15271. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15272. thread t2 =
  15273. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15274. auto se = detail::scope_exit([&] {
  15275. t2.join();
  15276. t.join();
  15277. ASSERT_FALSE(ssl_svr1.is_running());
  15278. });
  15279. ssl_svr1.wait_until_ready();
  15280. ssl_svr2.wait_until_ready();
  15281. SSLClient cli("127.0.0.1", PORT);
  15282. std::string cert;
  15283. read_file(SERVER_CERT2_FILE, cert);
  15284. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15285. cli.enable_server_certificate_verification(true);
  15286. cli.set_follow_location(true);
  15287. cli.set_connection_timeout(30);
  15288. auto res = cli.Get("/index");
  15289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15290. ASSERT_EQ(StatusCode::OK_200, res->status);
  15291. }
  15292. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15293. // another port, so the client follows it with a new client.
  15294. static Result GetThroughTlsRedirectToDifferentPort(
  15295. const std::function<void(SSLClient &)> &setup,
  15296. const char *target_cert = SERVER_CERT2_FILE,
  15297. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15298. auto ssl_port = PORT + 1;
  15299. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15300. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15301. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15302. "/index");
  15303. });
  15304. SSLServer ssl_svr2(target_cert, target_key);
  15305. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15306. res.set_content("test", "text/plain");
  15307. });
  15308. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15309. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15310. auto se = detail::scope_exit([&] {
  15311. ssl_svr2.stop();
  15312. ssl_svr1.stop();
  15313. t2.join();
  15314. t.join();
  15315. });
  15316. ssl_svr1.wait_until_ready();
  15317. ssl_svr2.wait_until_ready();
  15318. SSLClient cli("127.0.0.1", PORT);
  15319. cli.set_follow_location(true);
  15320. cli.set_connection_timeout(30);
  15321. setup(cli);
  15322. return cli.Get("/index");
  15323. }
  15324. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15325. auto calls = 0;
  15326. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15327. cli.enable_server_certificate_verification(false);
  15328. // Accept the first server only.
  15329. cli.set_session_verifier([&](tls::session_t) {
  15330. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15331. : SSLVerifierResponse::CertificateRejected;
  15332. });
  15333. });
  15334. ASSERT_FALSE(res);
  15335. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15336. EXPECT_EQ(2, calls);
  15337. }
  15338. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15339. std::string pinned;
  15340. auto res = GetThroughTlsRedirectToDifferentPort(
  15341. [&](SSLClient &cli) {
  15342. cli.enable_server_certificate_verification(false);
  15343. // Pin the first certificate seen.
  15344. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15345. if (pinned.empty()) { pinned = ctx.serial(); }
  15346. return ctx.serial() == pinned;
  15347. });
  15348. },
  15349. // A certificate other than the first server's.
  15350. SERVER_CERT_FILE);
  15351. EXPECT_FALSE(res);
  15352. EXPECT_FALSE(pinned.empty());
  15353. }
  15354. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15355. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15356. std::string cert;
  15357. read_file(SERVER_CERT2_FILE, cert);
  15358. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15359. });
  15360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15361. EXPECT_EQ(StatusCode::OK_200, res->status);
  15362. }
  15363. // The target's certificate is signed by the root CA, which the first server's
  15364. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15365. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15366. auto res = GetThroughTlsRedirectToDifferentPort(
  15367. [](SSLClient &cli) {
  15368. std::string root_ca, cert;
  15369. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15370. read_file(SERVER_CERT2_FILE, cert);
  15371. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15372. cli.load_ca_cert_store(cert.data(), cert.size());
  15373. cli.enable_server_hostname_verification(false);
  15374. },
  15375. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15377. EXPECT_EQ(StatusCode::OK_200, res->status);
  15378. }
  15379. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15380. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15381. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15382. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15383. auto res = GetThroughTlsRedirectToDifferentPort(
  15384. [](SSLClient &cli) {
  15385. std::string root_ca, cert;
  15386. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15387. read_file(SERVER_CERT2_FILE, cert);
  15388. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15389. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15390. cli.enable_server_hostname_verification(false);
  15391. },
  15392. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15393. ASSERT_FALSE(res);
  15394. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15395. }
  15396. #endif
  15397. #endif
  15398. #ifdef CPPHTTPLIB_SSL_ENABLED
  15399. // Test that set_ca_cert_store() skips system certs (consistent with
  15400. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15401. // should be trusted - system certs should NOT be loaded.
  15402. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15403. // Load a specific cert that is NOT a system CA cert
  15404. std::string cert;
  15405. read_file(SERVER_CERT2_FILE, cert);
  15406. SSLClient cli("google.com");
  15407. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15408. cli.enable_server_certificate_verification(true);
  15409. // This should FAIL because:
  15410. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15411. // 2. System certs should NOT be loaded when custom store is set
  15412. // If system certs WERE loaded, this would succeed
  15413. auto res = cli.Get("/");
  15414. ASSERT_FALSE(res);
  15415. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15416. }
  15417. // Same as above, but through the native store handle path. Regression test:
  15418. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15419. // merged system certs into the user-provided store.
  15420. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15421. std::string cert;
  15422. read_file(SERVER_CERT2_FILE, cert);
  15423. SSLClient cli("google.com");
  15424. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15425. cli.enable_server_certificate_verification(true);
  15426. auto res = cli.Get("/");
  15427. ASSERT_FALSE(res);
  15428. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15429. }
  15430. // A custom store set via the native handle must still verify a server whose
  15431. // cert it does contain.
  15432. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15433. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15434. ASSERT_TRUE(svr.is_valid());
  15435. svr.Get("/test", [&](const Request &, Response &res) {
  15436. res.set_content("test", "text/plain");
  15437. });
  15438. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15439. auto se = detail::scope_exit([&] {
  15440. svr.stop();
  15441. t.join();
  15442. ASSERT_FALSE(svr.is_running());
  15443. });
  15444. svr.wait_until_ready();
  15445. SSLClient cli("127.0.0.1", PORT);
  15446. std::string cert;
  15447. read_file(SERVER_CERT2_FILE, cert);
  15448. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15449. cli.enable_server_certificate_verification(true);
  15450. cli.set_connection_timeout(30);
  15451. auto res = cli.Get("/test");
  15452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15453. ASSERT_EQ(StatusCode::OK_200, res->status);
  15454. }
  15455. // CA certs loaded through the universal Client must be transferred to the
  15456. // client created internally for following an HTTPS redirect. Regression test:
  15457. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15458. // the CA data for redirect transfer.
  15459. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15460. auto ssl_port = PORT + 1;
  15461. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15462. ASSERT_TRUE(ssl_svr1.is_valid());
  15463. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15464. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15465. "/index");
  15466. });
  15467. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15468. ASSERT_TRUE(ssl_svr2.is_valid());
  15469. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15470. res.set_content("test", "text/plain");
  15471. });
  15472. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15473. thread t2 =
  15474. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15475. auto se = detail::scope_exit([&] {
  15476. ssl_svr2.stop();
  15477. ssl_svr1.stop();
  15478. t2.join();
  15479. t.join();
  15480. ASSERT_FALSE(ssl_svr1.is_running());
  15481. });
  15482. ssl_svr1.wait_until_ready();
  15483. ssl_svr2.wait_until_ready();
  15484. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15485. std::string cert;
  15486. read_file(SERVER_CERT2_FILE, cert);
  15487. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15488. cli.enable_server_certificate_verification(true);
  15489. cli.set_follow_location(true);
  15490. cli.set_connection_timeout(30);
  15491. auto res = cli.Get("/index");
  15492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15493. ASSERT_EQ(StatusCode::OK_200, res->status);
  15494. }
  15495. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15496. // so a host signed by a system CA verifies even though a custom CA is set
  15497. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15498. std::string cert;
  15499. read_file(SERVER_CERT2_FILE, cert);
  15500. SSLClient cli("google.com");
  15501. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15502. cli.enable_system_ca(true);
  15503. cli.enable_server_certificate_verification(true);
  15504. auto res = cli.Get("/");
  15505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15506. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15507. }
  15508. // The custom CA remains effective when combined with the system CA
  15509. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15510. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15511. ASSERT_TRUE(svr.is_valid());
  15512. svr.Get("/test", [&](const Request &, Response &res) {
  15513. res.set_content("test", "text/plain");
  15514. });
  15515. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15516. auto se = detail::scope_exit([&] {
  15517. svr.stop();
  15518. t.join();
  15519. ASSERT_FALSE(svr.is_running());
  15520. });
  15521. svr.wait_until_ready();
  15522. SSLClient cli("127.0.0.1", PORT);
  15523. std::string cert;
  15524. read_file(SERVER_CERT2_FILE, cert);
  15525. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15526. cli.enable_system_ca(true);
  15527. cli.enable_server_certificate_verification(true);
  15528. cli.set_connection_timeout(30);
  15529. auto res = cli.Get("/test");
  15530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15531. ASSERT_EQ(StatusCode::OK_200, res->status);
  15532. }
  15533. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15534. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15535. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15536. static CFDictionaryRef
  15537. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15538. const SecTrustSettingsResult *result) {
  15539. auto constraint =
  15540. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15541. &kCFTypeDictionaryValueCallBacks);
  15542. if (policy) {
  15543. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15544. }
  15545. if (policy_string) {
  15546. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15547. kCFStringEncodingUTF8);
  15548. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15549. CFRelease(str);
  15550. }
  15551. if (result) {
  15552. auto number_value = static_cast<SInt32>(*result);
  15553. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15554. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15555. CFRelease(number);
  15556. }
  15557. return constraint;
  15558. }
  15559. static SecTrustSettingsResult
  15560. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15561. auto trust_settings =
  15562. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15563. for (auto constraint : constraints) {
  15564. CFArrayAppendValue(trust_settings, constraint);
  15565. CFRelease(constraint);
  15566. }
  15567. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15568. CFRelease(trust_settings);
  15569. return result;
  15570. }
  15571. // The system CA loader takes a Keychain certificate as a trusted root only
  15572. // when its Trust Settings say so for SSL, not merely because it has some.
  15573. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15574. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15575. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15576. const auto deny = kSecTrustSettingsResultDeny;
  15577. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15578. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15579. auto x509_policy = SecPolicyCreateBasicX509();
  15580. // "Always Trust", which stores no constraint at all
  15581. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15582. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15583. ssl_trust_settings_result(
  15584. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15585. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15586. ssl_trust_settings_result(
  15587. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15588. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15589. ssl_trust_settings_result(
  15590. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15591. // "Never Trust", for everything or for SSL
  15592. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15593. ssl_trust_settings_result(
  15594. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15595. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15596. ssl_trust_settings_result(
  15597. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15598. // Trusted for another policy, for one host, or not at all
  15599. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15600. ssl_trust_settings_result(
  15601. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15602. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15603. ssl_trust_settings_result({make_usage_constraint(
  15604. ssl_policy, "www.example.com", &trust_root)}));
  15605. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15606. ssl_trust_settings_result(
  15607. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15608. // The first constraint that applies to SSL decides
  15609. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15610. ssl_trust_settings_result(
  15611. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15612. make_usage_constraint(nullptr, nullptr, &deny)}));
  15613. CFRelease(x509_policy);
  15614. CFRelease(ssl_policy);
  15615. }
  15616. #endif
  15617. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15618. // skip chain verification entirely (only the certificate identity was
  15619. // checked), so a server presenting an untrusted certificate with a matching
  15620. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15621. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15622. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15623. ASSERT_TRUE(svr.is_valid());
  15624. svr.Get("/test", [&](const Request &, Response &res) {
  15625. res.set_content("test", "text/plain");
  15626. });
  15627. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15628. auto se = detail::scope_exit([&] {
  15629. svr.stop();
  15630. t.join();
  15631. ASSERT_FALSE(svr.is_running());
  15632. });
  15633. svr.wait_until_ready();
  15634. SSLClient cli("127.0.0.1", PORT);
  15635. std::string cert;
  15636. // A trusted CA that did not sign the server certificate. The server cert
  15637. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15638. // this connection.
  15639. read_file(CLIENT_CA_CERT_FILE, cert);
  15640. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15641. cli.enable_server_certificate_verification(true);
  15642. cli.set_connection_timeout(30);
  15643. auto res = cli.Get("/test");
  15644. ASSERT_FALSE(res);
  15645. }
  15646. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15647. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15648. // CA that failed to come through fails verification instead of trusting them.
  15649. // (wolfSSL does not list the system CAs it loaded.)
  15650. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15651. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15652. ASSERT_TRUE(svr.is_valid());
  15653. auto port = svr.bind_to_any_port("127.0.0.1");
  15654. ASSERT_LT(0, port);
  15655. thread t = thread([&] { svr.listen_after_bind(); });
  15656. auto se = detail::scope_exit([&] {
  15657. svr.stop();
  15658. t.join();
  15659. ASSERT_FALSE(svr.is_running());
  15660. });
  15661. svr.wait_until_ready();
  15662. // The CAs a client trusts once its first request has loaded them
  15663. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15664. Client cli("https://127.0.0.1:" + std::to_string(port));
  15665. setup(cli);
  15666. cli.Get("/");
  15667. return tls::get_ca_names(cli.tls_context()).size();
  15668. };
  15669. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15670. EXPECT_EQ(0u,
  15671. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15672. }
  15673. #endif
  15674. // A TLS setting changed between requests applies to the next one, not just to
  15675. // the next connection
  15676. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15677. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15678. ASSERT_TRUE(svr.is_valid());
  15679. svr.Get("/", [](const Request &req, Response &res) {
  15680. res.set_content(std::to_string(req.remote_port), "text/plain");
  15681. });
  15682. auto port = svr.bind_to_any_port("127.0.0.1");
  15683. ASSERT_LT(0, port);
  15684. thread t = thread([&] { svr.listen_after_bind(); });
  15685. auto se = detail::scope_exit([&] {
  15686. svr.stop();
  15687. t.join();
  15688. ASSERT_FALSE(svr.is_running());
  15689. });
  15690. svr.wait_until_ready();
  15691. SSLClient cli("127.0.0.1", port);
  15692. cli.set_keep_alive(true);
  15693. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15694. cli.enable_server_certificate_verification(false);
  15695. // The port the request went out from, so a new one means a new connection
  15696. auto client_port = [&] {
  15697. auto res = cli.Get("/");
  15698. return res ? res->body : std::string();
  15699. };
  15700. auto last = client_port();
  15701. ASSERT_FALSE(last.empty());
  15702. // Setting a value it already has keeps the connection
  15703. cli.enable_server_certificate_verification(false);
  15704. cli.enable_server_hostname_verification(true);
  15705. EXPECT_EQ(last, client_port());
  15706. cli.enable_server_certificate_verification(true);
  15707. auto res = cli.Get("/");
  15708. EXPECT_FALSE(res);
  15709. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15710. std::string ca;
  15711. read_file(SERVER_CERT2_FILE, ca);
  15712. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15713. last = client_port();
  15714. ASSERT_FALSE(last.empty());
  15715. std::vector<std::function<void()>> setters = {
  15716. [&] { cli.enable_server_hostname_verification(false); },
  15717. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15718. [&] {
  15719. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15720. },
  15721. [&] {
  15722. cli.set_server_certificate_verifier(
  15723. [](const tls::VerifyContext &) { return true; });
  15724. },
  15725. [&] {
  15726. cli.set_session_verifier(
  15727. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15728. },
  15729. };
  15730. for (const auto &setter : setters) {
  15731. setter();
  15732. auto next = client_port();
  15733. ASSERT_FALSE(next.empty());
  15734. EXPECT_NE(last, next);
  15735. last = next;
  15736. }
  15737. cli.set_session_verifier(
  15738. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15739. auto handle = cli.open_stream("GET", "/");
  15740. EXPECT_FALSE(handle.is_valid());
  15741. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15742. }
  15743. // A PEM given to create_ca_store() needs no NUL after it
  15744. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15745. std::string pem;
  15746. read_file(SERVER_CERT2_FILE, pem);
  15747. auto buf = pem + "X";
  15748. auto store = tls::create_ca_store(buf.data(), pem.size());
  15749. EXPECT_TRUE(store != nullptr);
  15750. SSLClient cli("localhost");
  15751. cli.set_ca_cert_store(store);
  15752. }
  15753. // enable_system_ca(false) prevents system CA loading entirely
  15754. TEST(SSLClientTest, DisableSystemCa_Online) {
  15755. SSLClient cli("google.com");
  15756. cli.enable_system_ca(false);
  15757. cli.enable_server_certificate_verification(true);
  15758. auto res = cli.Get("/");
  15759. ASSERT_FALSE(res);
  15760. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15761. // itself when the CA chain is empty
  15762. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15763. res.error() == Error::SSLConnection);
  15764. }
  15765. // The universal Client forwards enable_system_ca()
  15766. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15767. std::string cert;
  15768. read_file(SERVER_CERT2_FILE, cert);
  15769. Client cli("https://google.com");
  15770. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15771. cli.enable_system_ca(true);
  15772. cli.enable_server_certificate_verification(true);
  15773. auto res = cli.Get("/");
  15774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15775. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15776. }
  15777. // The system CA policy must carry over to the client created internally for
  15778. // following a cross-host HTTPS redirect
  15779. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15780. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15781. ASSERT_TRUE(svr.is_valid());
  15782. svr.Get("/index", [&](const Request &, Response &res) {
  15783. res.set_redirect("https://www.google.com/");
  15784. });
  15785. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15786. auto se = detail::scope_exit([&] {
  15787. svr.stop();
  15788. t.join();
  15789. ASSERT_FALSE(svr.is_running());
  15790. });
  15791. svr.wait_until_ready();
  15792. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15793. std::string cert;
  15794. read_file(SERVER_CERT2_FILE, cert);
  15795. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15796. cli.enable_system_ca(true);
  15797. cli.enable_server_certificate_verification(true);
  15798. cli.set_follow_location(true);
  15799. cli.set_connection_timeout(30);
  15800. // Receiving any response proves the redirect client completed the TLS
  15801. // handshake with a system-CA-signed host
  15802. auto res = cli.Get("/index");
  15803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15804. }
  15805. TEST(MultipartFormDataTest, LargeData) {
  15806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15807. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15808. const ContentReader &content_reader) {
  15809. if (req.is_multipart_form_data()) {
  15810. std::vector<FormData> items;
  15811. content_reader(
  15812. [&](const FormData &file) {
  15813. items.push_back(file);
  15814. return true;
  15815. },
  15816. [&](const char *data, size_t data_length) {
  15817. items.back().content.append(data, data_length);
  15818. return true;
  15819. });
  15820. EXPECT_TRUE(std::string(items[0].name) == "document");
  15821. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15822. EXPECT_TRUE(items[0].filename == "2MB_data");
  15823. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15824. EXPECT_TRUE(items[1].name == "hello");
  15825. EXPECT_TRUE(items[1].content == "world");
  15826. EXPECT_TRUE(items[1].filename == "");
  15827. EXPECT_TRUE(items[1].content_type == "");
  15828. } else {
  15829. std::string body;
  15830. content_reader([&](const char *data, size_t data_length) {
  15831. body.append(data, data_length);
  15832. return true;
  15833. });
  15834. }
  15835. });
  15836. auto port = svr.bind_to_any_port(HOST);
  15837. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15838. auto se = detail::scope_exit([&] {
  15839. svr.stop();
  15840. t.join();
  15841. ASSERT_FALSE(svr.is_running());
  15842. });
  15843. svr.wait_until_ready();
  15844. {
  15845. std::string data(1024 * 1024 * 2, '.');
  15846. std::stringstream buffer;
  15847. buffer << data;
  15848. SSLClient cli(HOST, port);
  15849. cli.enable_server_certificate_verification(false);
  15850. UploadFormDataItems items{
  15851. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15852. {"hello", "world", "", ""},
  15853. };
  15854. auto res = cli.Post("/post", items);
  15855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15856. ASSERT_EQ(StatusCode::OK_200, res->status);
  15857. }
  15858. }
  15859. TEST(MultipartFormDataTest, DataProviderItems) {
  15860. std::random_device seed_gen;
  15861. std::mt19937 random(seed_gen());
  15862. std::string rand1;
  15863. rand1.resize(1000);
  15864. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15865. std::string rand2;
  15866. rand2.resize(3000);
  15867. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15869. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15870. const ContentReader &content_reader) {
  15871. ASSERT_FALSE(req.is_multipart_form_data());
  15872. std::string body;
  15873. content_reader([&](const char *data, size_t data_length) {
  15874. body.append(data, data_length);
  15875. return true;
  15876. });
  15877. EXPECT_EQ(body, "");
  15878. });
  15879. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15880. const ContentReader &content_reader) {
  15881. ASSERT_TRUE(req.is_multipart_form_data());
  15882. std::vector<FormData> items;
  15883. content_reader(
  15884. [&](const FormData &file) {
  15885. items.push_back(file);
  15886. return true;
  15887. },
  15888. [&](const char *data, size_t data_length) {
  15889. items.back().content.append(data, data_length);
  15890. return true;
  15891. });
  15892. ASSERT_TRUE(items.size() == 2);
  15893. EXPECT_EQ(std::string(items[0].name), "name1");
  15894. EXPECT_EQ(items[0].content, "Testing123");
  15895. EXPECT_EQ(items[0].filename, "filename1");
  15896. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15897. EXPECT_EQ(items[1].name, "name2");
  15898. EXPECT_EQ(items[1].content, "Testing456");
  15899. EXPECT_EQ(items[1].filename, "");
  15900. EXPECT_EQ(items[1].content_type, "");
  15901. });
  15902. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15903. const ContentReader &content_reader) {
  15904. ASSERT_TRUE(req.is_multipart_form_data());
  15905. std::vector<FormData> items;
  15906. content_reader(
  15907. [&](const FormData &file) {
  15908. items.push_back(file);
  15909. return true;
  15910. },
  15911. [&](const char *data, size_t data_length) {
  15912. items.back().content.append(data, data_length);
  15913. return true;
  15914. });
  15915. ASSERT_TRUE(items.size() == 2);
  15916. EXPECT_EQ(items[0].name, "name3");
  15917. EXPECT_EQ(items[0].content, rand1);
  15918. EXPECT_EQ(items[0].filename, "filename3");
  15919. EXPECT_EQ(items[0].content_type, "");
  15920. EXPECT_EQ(items[1].name, "name4");
  15921. EXPECT_EQ(items[1].content, rand2);
  15922. EXPECT_EQ(items[1].filename, "filename4");
  15923. EXPECT_EQ(items[1].content_type, "");
  15924. });
  15925. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15926. const ContentReader &content_reader) {
  15927. ASSERT_TRUE(req.is_multipart_form_data());
  15928. std::vector<FormData> items;
  15929. content_reader(
  15930. [&](const FormData &file) {
  15931. items.push_back(file);
  15932. return true;
  15933. },
  15934. [&](const char *data, size_t data_length) {
  15935. items.back().content.append(data, data_length);
  15936. return true;
  15937. });
  15938. ASSERT_TRUE(items.size() == 4);
  15939. EXPECT_EQ(std::string(items[0].name), "name1");
  15940. EXPECT_EQ(items[0].content, "Testing123");
  15941. EXPECT_EQ(items[0].filename, "filename1");
  15942. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15943. EXPECT_EQ(items[1].name, "name2");
  15944. EXPECT_EQ(items[1].content, "Testing456");
  15945. EXPECT_EQ(items[1].filename, "");
  15946. EXPECT_EQ(items[1].content_type, "");
  15947. EXPECT_EQ(items[2].name, "name3");
  15948. EXPECT_EQ(items[2].content, rand1);
  15949. EXPECT_EQ(items[2].filename, "filename3");
  15950. EXPECT_EQ(items[2].content_type, "");
  15951. EXPECT_EQ(items[3].name, "name4");
  15952. EXPECT_EQ(items[3].content, rand2);
  15953. EXPECT_EQ(items[3].filename, "filename4");
  15954. EXPECT_EQ(items[3].content_type, "");
  15955. });
  15956. auto port = svr.bind_to_any_port("localhost");
  15957. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15958. auto se = detail::scope_exit([&] {
  15959. svr.stop();
  15960. t.join();
  15961. ASSERT_FALSE(svr.is_running());
  15962. });
  15963. svr.wait_until_ready();
  15964. {
  15965. SSLClient cli("localhost", port);
  15966. cli.enable_server_certificate_verification(false);
  15967. UploadFormDataItems items{
  15968. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15969. {"name2", "Testing456", "", ""}, // not a file
  15970. };
  15971. {
  15972. auto res = cli.Post("/post-none", {}, {}, {});
  15973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15974. ASSERT_EQ(StatusCode::OK_200, res->status);
  15975. }
  15976. FormDataProviderItems providers;
  15977. {
  15978. auto res =
  15979. cli.Post("/post-items", {}, items, providers); // empty providers
  15980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15981. ASSERT_EQ(StatusCode::OK_200, res->status);
  15982. }
  15983. providers.push_back({"name3",
  15984. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15985. // test the offset is given correctly at each step
  15986. if (!offset)
  15987. sink.os.write(rand1.data(), 30);
  15988. else if (offset == 30)
  15989. sink.os.write(rand1.data() + 30, 300);
  15990. else if (offset == 330)
  15991. sink.os.write(rand1.data() + 330, 670);
  15992. else if (offset == rand1.size())
  15993. sink.done();
  15994. return true;
  15995. },
  15996. "filename3",
  15997. {}});
  15998. providers.push_back({"name4",
  15999. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16000. // test the offset is given correctly at each step
  16001. if (!offset)
  16002. sink.os.write(rand2.data(), 2000);
  16003. else if (offset == 2000)
  16004. sink.os.write(rand2.data() + 2000, 1);
  16005. else if (offset == 2001)
  16006. sink.os.write(rand2.data() + 2001, 999);
  16007. else if (offset == rand2.size())
  16008. sink.done();
  16009. return true;
  16010. },
  16011. "filename4",
  16012. {}});
  16013. {
  16014. auto res = cli.Post("/post-providers", {}, {}, providers);
  16015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16016. ASSERT_EQ(StatusCode::OK_200, res->status);
  16017. }
  16018. {
  16019. auto res = cli.Post("/post-both", {}, items, providers);
  16020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16021. ASSERT_EQ(StatusCode::OK_200, res->status);
  16022. }
  16023. }
  16024. }
  16025. TEST(MultipartFormDataTest, BadHeader) {
  16026. Server svr;
  16027. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16028. res.set_content("ok", "text/plain");
  16029. });
  16030. thread t = thread([&] { svr.listen(HOST, PORT); });
  16031. auto se = detail::scope_exit([&] {
  16032. svr.stop();
  16033. t.join();
  16034. ASSERT_FALSE(svr.is_running());
  16035. });
  16036. svr.wait_until_ready();
  16037. const std::string body =
  16038. "This is the preamble. It is to be ignored, though it\r\n"
  16039. "is a handy place for composition agents to include an\r\n"
  16040. "explanatory note to non-MIME conformant readers.\r\n"
  16041. "\r\n"
  16042. "\r\n"
  16043. "--simple boundary\r\n"
  16044. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16045. ": BAD...\r\n"
  16046. "\r\n"
  16047. "value1\r\n"
  16048. "--simple boundary\r\n"
  16049. "Content-Disposition: form-data; name=\"field2\"; "
  16050. "filename=\"example.txt\"\r\n"
  16051. "\r\n"
  16052. "value2\r\n"
  16053. "--simple boundary--\r\n"
  16054. "This is the epilogue. It is also to be ignored.\r\n";
  16055. std::string content_type =
  16056. R"(multipart/form-data; boundary="simple boundary")";
  16057. Client cli(HOST, PORT);
  16058. auto res = cli.Post("/post", body, content_type.c_str());
  16059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16060. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16061. }
  16062. TEST(MultipartFormDataTest, WithPreamble) {
  16063. Server svr;
  16064. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16065. res.set_content("ok", "text/plain");
  16066. });
  16067. thread t = thread([&] { svr.listen(HOST, PORT); });
  16068. auto se = detail::scope_exit([&] {
  16069. svr.stop();
  16070. t.join();
  16071. ASSERT_FALSE(svr.is_running());
  16072. });
  16073. svr.wait_until_ready();
  16074. const std::string body =
  16075. "This is the preamble. It is to be ignored, though it\r\n"
  16076. "is a handy place for composition agents to include an\r\n"
  16077. "explanatory note to non-MIME conformant readers.\r\n"
  16078. "\r\n"
  16079. "\r\n"
  16080. "--simple boundary\r\n"
  16081. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16082. "\r\n"
  16083. "value1\r\n"
  16084. "--simple boundary\r\n"
  16085. "Content-Disposition: form-data; name=\"field2\"; "
  16086. "filename=\"example.txt\"\r\n"
  16087. "\r\n"
  16088. "value2\r\n"
  16089. "--simple boundary--\r\n"
  16090. "This is the epilogue. It is also to be ignored.\r\n";
  16091. std::string content_type =
  16092. R"(multipart/form-data; boundary="simple boundary")";
  16093. Client cli(HOST, PORT);
  16094. auto res = cli.Post("/post", body, content_type.c_str());
  16095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16096. EXPECT_EQ(StatusCode::OK_200, res->status);
  16097. }
  16098. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16099. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16100. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16101. const ContentReader &content_reader) {
  16102. if (req.is_multipart_form_data()) {
  16103. std::vector<FormData> items;
  16104. content_reader(
  16105. [&](const FormData &file) {
  16106. items.push_back(file);
  16107. return true;
  16108. },
  16109. [&](const char *data, size_t data_length) {
  16110. items.back().content.append(data, data_length);
  16111. return true;
  16112. });
  16113. EXPECT_TRUE(std::string(items[0].name) == "document");
  16114. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16115. EXPECT_TRUE(items[0].filename == "2MB_data");
  16116. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16117. EXPECT_TRUE(items[1].name == "hello");
  16118. EXPECT_TRUE(items[1].content == "world");
  16119. EXPECT_TRUE(items[1].filename == "");
  16120. EXPECT_TRUE(items[1].content_type == "");
  16121. } else {
  16122. std::string body;
  16123. content_reader([&](const char *data, size_t data_length) {
  16124. body.append(data, data_length);
  16125. return true;
  16126. });
  16127. }
  16128. });
  16129. auto port = svr.bind_to_any_port("localhost");
  16130. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16131. auto se = detail::scope_exit([&] {
  16132. svr.stop();
  16133. t.join();
  16134. ASSERT_FALSE(svr.is_running());
  16135. });
  16136. svr.wait_until_ready();
  16137. {
  16138. std::string data(1024 * 1024 * 2, '.');
  16139. std::stringstream buffer;
  16140. buffer << data;
  16141. SSLClient cli("localhost", port);
  16142. cli.enable_server_certificate_verification(false);
  16143. UploadFormDataItems items{
  16144. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16145. {"hello", "world", "", ""},
  16146. };
  16147. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16149. ASSERT_EQ(StatusCode::OK_200, res->status);
  16150. }
  16151. }
  16152. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16153. std::string data(1024 * 1024 * 2, '&');
  16154. std::stringstream buffer;
  16155. buffer << data;
  16156. Client cli("https://localhost:8080");
  16157. UploadFormDataItems items{
  16158. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16159. {"hello", "world", "", ""},
  16160. };
  16161. for (const char &c : " \t\r\n") {
  16162. auto res =
  16163. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16164. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16165. ASSERT_FALSE(res);
  16166. }
  16167. }
  16168. TEST(MultipartFormDataTest, PutFormData) {
  16169. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16170. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16171. const ContentReader &content_reader) {
  16172. if (req.is_multipart_form_data()) {
  16173. std::vector<FormData> items;
  16174. content_reader(
  16175. [&](const FormData &file) {
  16176. items.push_back(file);
  16177. return true;
  16178. },
  16179. [&](const char *data, size_t data_length) {
  16180. items.back().content.append(data, data_length);
  16181. return true;
  16182. });
  16183. EXPECT_TRUE(std::string(items[0].name) == "document");
  16184. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16185. EXPECT_TRUE(items[0].filename == "2MB_data");
  16186. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16187. EXPECT_TRUE(items[1].name == "hello");
  16188. EXPECT_TRUE(items[1].content == "world");
  16189. EXPECT_TRUE(items[1].filename == "");
  16190. EXPECT_TRUE(items[1].content_type == "");
  16191. } else {
  16192. std::string body;
  16193. content_reader([&](const char *data, size_t data_length) {
  16194. body.append(data, data_length);
  16195. return true;
  16196. });
  16197. }
  16198. });
  16199. auto port = svr.bind_to_any_port("localhost");
  16200. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16201. auto se = detail::scope_exit([&] {
  16202. svr.stop();
  16203. t.join();
  16204. ASSERT_FALSE(svr.is_running());
  16205. });
  16206. svr.wait_until_ready();
  16207. {
  16208. std::string data(1024 * 1024 * 2, '&');
  16209. std::stringstream buffer;
  16210. buffer << data;
  16211. SSLClient cli("localhost", port);
  16212. cli.enable_server_certificate_verification(false);
  16213. UploadFormDataItems items{
  16214. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16215. {"hello", "world", "", ""},
  16216. };
  16217. auto res = cli.Put("/put", items);
  16218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16219. ASSERT_EQ(StatusCode::OK_200, res->status);
  16220. }
  16221. }
  16222. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16224. svr.Put("/put_customboundary",
  16225. [&](const Request &req, const Response & /*res*/,
  16226. const ContentReader &content_reader) {
  16227. if (req.is_multipart_form_data()) {
  16228. std::vector<FormData> items;
  16229. content_reader(
  16230. [&](const FormData &file) {
  16231. items.push_back(file);
  16232. return true;
  16233. },
  16234. [&](const char *data, size_t data_length) {
  16235. items.back().content.append(data, data_length);
  16236. return true;
  16237. });
  16238. EXPECT_TRUE(std::string(items[0].name) == "document");
  16239. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16240. EXPECT_TRUE(items[0].filename == "2MB_data");
  16241. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16242. EXPECT_TRUE(items[1].name == "hello");
  16243. EXPECT_TRUE(items[1].content == "world");
  16244. EXPECT_TRUE(items[1].filename == "");
  16245. EXPECT_TRUE(items[1].content_type == "");
  16246. } else {
  16247. std::string body;
  16248. content_reader([&](const char *data, size_t data_length) {
  16249. body.append(data, data_length);
  16250. return true;
  16251. });
  16252. }
  16253. });
  16254. auto port = svr.bind_to_any_port("localhost");
  16255. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16256. auto se = detail::scope_exit([&] {
  16257. svr.stop();
  16258. t.join();
  16259. ASSERT_FALSE(svr.is_running());
  16260. });
  16261. svr.wait_until_ready();
  16262. {
  16263. std::string data(1024 * 1024 * 2, '&');
  16264. std::stringstream buffer;
  16265. buffer << data;
  16266. SSLClient cli("localhost", port);
  16267. cli.enable_server_certificate_verification(false);
  16268. UploadFormDataItems items{
  16269. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16270. {"hello", "world", "", ""},
  16271. };
  16272. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16274. ASSERT_EQ(StatusCode::OK_200, res->status);
  16275. }
  16276. }
  16277. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16278. std::string data(1024 * 1024 * 2, '&');
  16279. std::stringstream buffer;
  16280. buffer << data;
  16281. Client cli("https://localhost:8080");
  16282. cli.enable_server_certificate_verification(false);
  16283. UploadFormDataItems items{
  16284. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16285. {"hello", "world", "", ""},
  16286. };
  16287. for (const char &c : " \t\r\n") {
  16288. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16289. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16290. ASSERT_FALSE(res);
  16291. }
  16292. }
  16293. TEST(MultipartFormDataTest, AlternateFilename) {
  16294. auto handled = false;
  16295. Server svr;
  16296. svr.Post("/test", [&](const Request &req, Response &res) {
  16297. ASSERT_EQ(2u, req.form.files.size());
  16298. ASSERT_EQ(1u, req.form.fields.size());
  16299. // Test files
  16300. const auto &file1 = req.form.get_file("file1");
  16301. ASSERT_EQ("file1", file1.name);
  16302. ASSERT_EQ("A.txt", file1.filename);
  16303. ASSERT_EQ("text/plain", file1.content_type);
  16304. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16305. const auto &file2 = req.form.get_file("file2");
  16306. ASSERT_EQ("file2", file2.name);
  16307. ASSERT_EQ("a.html", file2.filename);
  16308. ASSERT_EQ("text/html", file2.content_type);
  16309. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16310. file2.content);
  16311. // Test text field
  16312. const auto &text = req.form.get_field("text");
  16313. ASSERT_EQ("text default", text);
  16314. res.set_content("ok", "text/plain");
  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: 399\r\n"
  16329. "\r\n"
  16330. "----------\r\n"
  16331. "Content-Disposition: form-data; name=\"text\"\r\n"
  16332. "\r\n"
  16333. "text default\r\n"
  16334. "----------\r\n"
  16335. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16336. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16337. "Content-Type: text/plain\r\n"
  16338. "\r\n"
  16339. "Content of a.txt.\r\n"
  16340. "\r\n"
  16341. "----------\r\n"
  16342. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16343. "\"a.html\"\r\n"
  16344. "Content-Type: text/html\r\n"
  16345. "\r\n"
  16346. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16347. "\r\n"
  16348. "------------\r\n";
  16349. ASSERT_TRUE(send_request(1, req));
  16350. }
  16351. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16352. auto handled = false;
  16353. Server svr;
  16354. svr.Post("/test", [&](const Request &req, Response &res) {
  16355. // Case-insensitive "utf-8''" prefix with a long value
  16356. const auto &file = req.form.get_file("file1");
  16357. ASSERT_EQ("file1", file.name);
  16358. // 8000 chars exercises both the Content-Disposition parser and the
  16359. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16360. // Prior to the fix, std::regex_match on this header would cause O(N)
  16361. // stack recursion in libstdc++, leading to SIGSEGV.
  16362. std::string expected_filename(8000, 'A');
  16363. ASSERT_EQ(expected_filename, file.filename);
  16364. res.set_content("ok", "text/plain");
  16365. handled = true;
  16366. });
  16367. thread t = thread([&] { svr.listen(HOST, PORT); });
  16368. auto se = detail::scope_exit([&] {
  16369. svr.stop();
  16370. t.join();
  16371. ASSERT_FALSE(svr.is_running());
  16372. ASSERT_TRUE(handled);
  16373. });
  16374. svr.wait_until_ready();
  16375. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16376. // Regression test for GHSA-qq6v-r583-3h69
  16377. std::string long_filename(8000, 'A');
  16378. std::string body = "----------\r\n"
  16379. "Content-Disposition: form-data; name=\"file1\"; "
  16380. "filename*=\"Utf-8''" +
  16381. long_filename +
  16382. "\"\r\n"
  16383. "\r\n"
  16384. "hello\r\n"
  16385. "------------\r\n";
  16386. auto req = "POST /test HTTP/1.1\r\n"
  16387. "Host: localhost\r\n"
  16388. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16389. "Content-Length: " +
  16390. std::to_string(body.size()) + "\r\n\r\n" + body;
  16391. ASSERT_TRUE(send_request(1, req));
  16392. }
  16393. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16394. auto handled = false;
  16395. Server svr;
  16396. svr.Post("/test", [&](const Request &req, Response &) {
  16397. ASSERT_EQ(2u, req.form.fields.size());
  16398. const auto &text1 = req.form.get_field("text1");
  16399. ASSERT_EQ("text1", text1);
  16400. const auto &text2 = req.form.get_field("text2");
  16401. ASSERT_EQ("text2", text2);
  16402. handled = true;
  16403. });
  16404. thread t = thread([&] { svr.listen(HOST, PORT); });
  16405. auto se = detail::scope_exit([&] {
  16406. svr.stop();
  16407. t.join();
  16408. ASSERT_FALSE(svr.is_running());
  16409. ASSERT_TRUE(handled);
  16410. });
  16411. svr.wait_until_ready();
  16412. auto req = "POST /test HTTP/1.1\r\n"
  16413. "Host: localhost\r\n"
  16414. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16415. "Content-Length: 146\r\n"
  16416. "\r\n----------\r\n"
  16417. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16418. "\r\n"
  16419. "text1"
  16420. "\r\n----------\r\n"
  16421. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16422. "\r\n"
  16423. "text2"
  16424. "\r\n------------";
  16425. std::string response;
  16426. ASSERT_TRUE(send_request(1, req, &response));
  16427. ASSERT_EQ("200", response.substr(9, 3));
  16428. }
  16429. TEST(MultipartFormDataTest, ContentLength) {
  16430. auto handled = false;
  16431. Server svr;
  16432. svr.Post("/test", [&](const Request &req, Response &) {
  16433. ASSERT_EQ(2u, req.form.fields.size());
  16434. const auto &text1 = req.form.get_field("text1");
  16435. ASSERT_EQ("text1", text1);
  16436. const auto &text2 = req.form.get_field("text2");
  16437. ASSERT_EQ("text2", text2);
  16438. handled = true;
  16439. });
  16440. thread t = thread([&] { svr.listen(HOST, PORT); });
  16441. auto se = detail::scope_exit([&] {
  16442. svr.stop();
  16443. t.join();
  16444. ASSERT_FALSE(svr.is_running());
  16445. ASSERT_TRUE(handled);
  16446. });
  16447. svr.wait_until_ready();
  16448. auto req = "POST /test HTTP/1.1\r\n"
  16449. "Host: localhost\r\n"
  16450. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16451. "Content-Length: 167\r\n"
  16452. "\r\n----------\r\n"
  16453. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16454. "Content-Length: 5\r\n"
  16455. "\r\n"
  16456. "text1"
  16457. "\r\n----------\r\n"
  16458. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16459. "\r\n"
  16460. "text2"
  16461. "\r\n------------\r\n";
  16462. std::string response;
  16463. ASSERT_TRUE(send_request(1, req, &response));
  16464. ASSERT_EQ("200", response.substr(9, 3));
  16465. }
  16466. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16467. auto handled = false;
  16468. Server svr;
  16469. svr.Post("/test", [&](const Request &req, Response &) {
  16470. ASSERT_EQ(2u, req.form.fields.size());
  16471. const auto &text1 = req.form.get_field("text1");
  16472. ASSERT_EQ("text1", text1);
  16473. // TODO: Add header access for text fields if needed
  16474. const auto &text2 = req.form.get_field("text2");
  16475. ASSERT_EQ("text2", text2);
  16476. // TODO: Header access for text fields needs to be implemented
  16477. // auto &headers = it->second.headers;
  16478. // ASSERT_EQ(3U, headers.size());
  16479. // auto custom_header = headers.find("x-whatever");
  16480. // ASSERT_TRUE(custom_header != headers.end());
  16481. // ASSERT_NE("customvalue", custom_header->second);
  16482. // ASSERT_EQ("CustomValue", custom_header->second);
  16483. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16484. handled = true;
  16485. });
  16486. thread t = thread([&] { svr.listen(HOST, PORT); });
  16487. auto se = detail::scope_exit([&] {
  16488. svr.stop();
  16489. t.join();
  16490. ASSERT_FALSE(svr.is_running());
  16491. ASSERT_TRUE(handled);
  16492. });
  16493. svr.wait_until_ready();
  16494. auto req = "POST /test HTTP/1.1\r\n"
  16495. "Host: localhost\r\n"
  16496. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16497. "Content-Length: 232\r\n"
  16498. "\r\n----------\r\n"
  16499. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16500. "Content-Length: 5\r\n"
  16501. "X-Test: 1\r\n"
  16502. "\r\n"
  16503. "text1"
  16504. "\r\n----------\r\n"
  16505. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16506. "Content-Type: text/plain\r\n"
  16507. "X-Whatever: CustomValue\r\n"
  16508. "\r\n"
  16509. "text2"
  16510. "\r\n------------\r\n"
  16511. "That should be disregarded. Not even read";
  16512. std::string response;
  16513. ASSERT_TRUE(send_request(1, req, &response));
  16514. ASSERT_EQ("200", response.substr(9, 3));
  16515. }
  16516. TEST(MultipartFormDataTest, LargeHeader) {
  16517. auto handled = false;
  16518. Server svr;
  16519. svr.Post("/test", [&](const Request &req, Response &) {
  16520. ASSERT_EQ(1u, req.form.fields.size());
  16521. const auto &text = req.form.get_field("name1");
  16522. ASSERT_EQ("text1", text);
  16523. handled = true;
  16524. });
  16525. thread t = thread([&] { svr.listen(HOST, PORT); });
  16526. auto se = detail::scope_exit([&] {
  16527. svr.stop();
  16528. t.join();
  16529. ASSERT_FALSE(svr.is_running());
  16530. ASSERT_TRUE(handled);
  16531. });
  16532. svr.wait_until_ready();
  16533. auto boundary = std::string("cpp-httplib-multipart-data");
  16534. std::string content = "--" + boundary +
  16535. "\r\n"
  16536. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16537. "\r\n"
  16538. "text1\r\n"
  16539. "--" +
  16540. boundary + "--\r\n";
  16541. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16542. "Host: localhost\r\n"
  16543. "Content-Type: multipart/form-data;boundary=" +
  16544. boundary +
  16545. "\r\n"
  16546. "Content-Length: " +
  16547. std::to_string(content.size()) +
  16548. "\r\n"
  16549. "Dummy-Header: ";
  16550. std::string header_suffix = "\r\n"
  16551. "\r\n";
  16552. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16553. size_t header_dummy_size =
  16554. read_buff_size -
  16555. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16556. auto header_dummy = std::string(header_dummy_size, '@');
  16557. auto req = header_prefix + header_dummy + header_suffix + content;
  16558. std::string response;
  16559. ASSERT_TRUE(send_request(1, req, &response));
  16560. ASSERT_EQ("200", response.substr(9, 3));
  16561. }
  16562. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16563. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16564. // (not chunked Transfer-Encoding) after the streaming refactor.
  16565. auto handled = false;
  16566. Server svr;
  16567. svr.Post("/upload", [&](const Request &req, Response &res) {
  16568. auto cl_it = req.headers.find("Content-Length");
  16569. EXPECT_TRUE(cl_it != req.headers.end());
  16570. auto te_it = req.headers.find("Transfer-Encoding");
  16571. EXPECT_TRUE(te_it == req.headers.end());
  16572. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16573. res.set_content("ok", "text/plain");
  16574. handled = true;
  16575. });
  16576. auto port = svr.bind_to_any_port(HOST);
  16577. auto t = thread([&] { svr.listen_after_bind(); });
  16578. auto se = detail::scope_exit([&] {
  16579. svr.stop();
  16580. t.join();
  16581. ASSERT_FALSE(svr.is_running());
  16582. ASSERT_TRUE(handled);
  16583. });
  16584. svr.wait_until_ready();
  16585. UploadFormDataItems items = {
  16586. {"field1", "hello", "", "text/plain"},
  16587. {"file1", "world", "test.txt", "application/octet-stream"},
  16588. };
  16589. Client cli(HOST, port);
  16590. auto res = cli.Post("/upload", {}, items);
  16591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16592. EXPECT_EQ(StatusCode::OK_200, res->status);
  16593. }
  16594. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16595. // Verify that make_multipart_content_provider coalesces many small segments
  16596. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16597. constexpr size_t kItemCount = 1000;
  16598. UploadFormDataItems items;
  16599. items.reserve(kItemCount);
  16600. for (size_t i = 0; i < kItemCount; i++) {
  16601. items.push_back(
  16602. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16603. }
  16604. const std::string boundary = "----test-boundary";
  16605. auto content_length = detail::get_multipart_content_length(items, boundary);
  16606. auto provider = detail::make_multipart_content_provider(items, boundary);
  16607. // Drive the provider the same way write_content_with_progress does
  16608. size_t write_count = 0;
  16609. size_t total_bytes = 0;
  16610. DataSink sink;
  16611. size_t offset = 0;
  16612. sink.write = [&](const char *d, size_t l) -> bool {
  16613. (void)d;
  16614. write_count++;
  16615. total_bytes += l;
  16616. offset += l;
  16617. return true;
  16618. };
  16619. sink.is_writable = []() -> bool { return true; };
  16620. while (offset < content_length) {
  16621. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16622. }
  16623. EXPECT_EQ(content_length, total_bytes);
  16624. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16625. // With buffering into 64KB blocks, write_count should be much smaller.
  16626. auto segment_count = 3 * kItemCount + 1;
  16627. EXPECT_LT(write_count, segment_count / 10);
  16628. }
  16629. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16630. // Integration test: send many UploadFormDataItems and verify the server
  16631. // receives all of them correctly (#2410).
  16632. constexpr size_t kItemCount = 500;
  16633. auto handled = false;
  16634. Server svr;
  16635. svr.Post("/upload", [&](const Request &req, Response &res) {
  16636. EXPECT_EQ(kItemCount, req.form.fields.size());
  16637. for (size_t i = 0; i < kItemCount; i++) {
  16638. auto key = "field" + std::to_string(i);
  16639. auto val = "value" + std::to_string(i);
  16640. auto it = req.form.fields.find(key);
  16641. if (it != req.form.fields.end()) {
  16642. EXPECT_EQ(val, it->second.content);
  16643. } else {
  16644. ADD_FAILURE() << "Missing field: " << key;
  16645. }
  16646. }
  16647. res.set_content("ok", "text/plain");
  16648. handled = true;
  16649. });
  16650. auto port = svr.bind_to_any_port(HOST);
  16651. auto t = thread([&] { svr.listen_after_bind(); });
  16652. auto se = detail::scope_exit([&] {
  16653. svr.stop();
  16654. t.join();
  16655. ASSERT_FALSE(svr.is_running());
  16656. ASSERT_TRUE(handled);
  16657. });
  16658. svr.wait_until_ready();
  16659. UploadFormDataItems items;
  16660. items.reserve(kItemCount);
  16661. for (size_t i = 0; i < kItemCount; i++) {
  16662. items.push_back(
  16663. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16664. }
  16665. Client cli(HOST, port);
  16666. auto res = cli.Post("/upload", items);
  16667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16668. EXPECT_EQ(StatusCode::OK_200, res->status);
  16669. }
  16670. TEST(MultipartFormDataTest, MakeFileProvider) {
  16671. // Verify make_file_provider sends a file's contents correctly.
  16672. const std::string file_content(4096, 'Z');
  16673. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16674. {
  16675. std::ofstream ofs(tmp_path, std::ios::binary);
  16676. ofs.write(file_content.data(),
  16677. static_cast<std::streamsize>(file_content.size()));
  16678. }
  16679. auto handled = false;
  16680. Server svr;
  16681. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16682. const ContentReader &content_reader) {
  16683. ASSERT_TRUE(req.is_multipart_form_data());
  16684. std::vector<FormData> items;
  16685. content_reader(
  16686. [&](const FormData &file) {
  16687. items.push_back(file);
  16688. return true;
  16689. },
  16690. [&](const char *data, size_t data_length) {
  16691. items.back().content.append(data, data_length);
  16692. return true;
  16693. });
  16694. ASSERT_EQ(1u, items.size());
  16695. EXPECT_EQ("myfile", items[0].name);
  16696. EXPECT_EQ("data.bin", items[0].filename);
  16697. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16698. EXPECT_EQ(file_content, items[0].content);
  16699. handled = true;
  16700. });
  16701. auto port = svr.bind_to_any_port(HOST);
  16702. auto t = thread([&] { svr.listen_after_bind(); });
  16703. auto se = detail::scope_exit([&] {
  16704. svr.stop();
  16705. t.join();
  16706. ASSERT_FALSE(svr.is_running());
  16707. ASSERT_TRUE(handled);
  16708. std::remove(tmp_path.c_str());
  16709. });
  16710. svr.wait_until_ready();
  16711. FormDataProviderItems providers;
  16712. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16713. "application/octet-stream"));
  16714. Client cli(HOST, port);
  16715. auto res = cli.Post("/upload", {}, {}, providers);
  16716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16717. EXPECT_EQ(StatusCode::OK_200, res->status);
  16718. }
  16719. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16720. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16721. // (100) headers is rejected with a 400 Bad Request response.
  16722. Server svr;
  16723. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16724. res.set_content("ok", "text/plain");
  16725. });
  16726. thread t = thread([&] { svr.listen(HOST, PORT); });
  16727. auto se = detail::scope_exit([&] {
  16728. svr.stop();
  16729. t.join();
  16730. ASSERT_FALSE(svr.is_running());
  16731. });
  16732. svr.wait_until_ready();
  16733. // Build a multipart part with 101 custom headers (exceeding
  16734. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16735. std::stringstream body;
  16736. body << "--simpleboundary\r\n"
  16737. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16738. for (int i = 0; i < 101; i++) {
  16739. body << "X-Custom-Header-" << i << ": value\r\n";
  16740. }
  16741. body << "\r\n"
  16742. << "value1\r\n"
  16743. << "--simpleboundary--\r\n";
  16744. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16745. Client cli(HOST, PORT);
  16746. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16748. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16749. }
  16750. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16751. // A body that never contains the declared boundary must not be accumulated
  16752. // while the parser waits for it. Buffering it would also make every read
  16753. // rescan everything seen so far, which is quadratic in the body size.
  16754. Server svr;
  16755. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16756. res.set_content("ok", "text/plain");
  16757. });
  16758. auto port = svr.bind_to_any_port(HOST);
  16759. thread t = thread([&] { svr.listen_after_bind(); });
  16760. auto se = detail::scope_exit([&] {
  16761. svr.stop();
  16762. t.join();
  16763. ASSERT_FALSE(svr.is_running());
  16764. });
  16765. svr.wait_until_ready();
  16766. Client cli(HOST, port);
  16767. cli.set_read_timeout(60, 0);
  16768. cli.set_write_timeout(60, 0);
  16769. // '-' is the worst case: it matches the first character of the boundary, so
  16770. // every position has to be checked against it.
  16771. auto post_dashes = [&](size_t size) {
  16772. const std::string body(size, '-');
  16773. auto start = std::chrono::steady_clock::now();
  16774. auto res =
  16775. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16776. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16777. std::chrono::steady_clock::now() - start)
  16778. .count();
  16779. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16780. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16781. return ms;
  16782. };
  16783. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16784. // Windows.
  16785. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16786. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16787. // Comparing the two sizes rather than checking an absolute duration keeps
  16788. // this meaningful across build types and CI load, both of which move the
  16789. // absolute numbers by more than an order of magnitude. Four times the bytes
  16790. // costs about four times the time when parsing is linear, and about sixteen
  16791. // times when the body is buffered and rescanned.
  16792. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16793. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16794. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16795. << "ms, which suggests the body is being buffered and rescanned";
  16796. }
  16797. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16798. // A boundary can only be followed by CRLF or by "--", so anything else is
  16799. // malformed no matter what comes next. The parser must say so right away
  16800. // instead of buffering the rest of the declared body.
  16801. Server svr;
  16802. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16803. res.set_content("ok", "text/plain");
  16804. });
  16805. auto port = svr.bind_to_any_port(HOST);
  16806. thread t = thread([&] { svr.listen_after_bind(); });
  16807. auto se = detail::scope_exit([&] {
  16808. svr.stop();
  16809. t.join();
  16810. ASSERT_FALSE(svr.is_running());
  16811. });
  16812. svr.wait_until_ready();
  16813. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16814. // buffers instead of failing would still be waiting for the remaining bytes.
  16815. const std::string body = "--zzzz\r\n"
  16816. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16817. "\r\n"
  16818. "text1"
  16819. "\r\n--zzzzXX";
  16820. const std::string req = "POST /post HTTP/1.1\r\n"
  16821. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16822. "Content-Length: 1048576\r\n"
  16823. "\r\n" +
  16824. body;
  16825. std::string response;
  16826. ASSERT_TRUE(send_request(3, req, &response, port));
  16827. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16828. EXPECT_EQ("400", response.substr(9, 3));
  16829. }
  16830. // Posts a multipart body split into two writes, so that the server sees the
  16831. // split at whatever offset the caller chose, and expects the single "text1"
  16832. // field to come through.
  16833. static void expect_split_multipart_ok(const std::string &body1,
  16834. const std::string &body2) {
  16835. auto handled = false;
  16836. Server svr;
  16837. svr.Post("/post", [&](const Request &req, Response &) {
  16838. EXPECT_EQ(1u, req.form.fields.size());
  16839. EXPECT_EQ("text1", req.form.get_field("text1"));
  16840. handled = true;
  16841. });
  16842. auto port = svr.bind_to_any_port(HOST);
  16843. thread t = thread([&] { svr.listen_after_bind(); });
  16844. auto se = detail::scope_exit([&] {
  16845. svr.stop();
  16846. t.join();
  16847. ASSERT_FALSE(svr.is_running());
  16848. ASSERT_TRUE(handled);
  16849. });
  16850. svr.wait_until_ready();
  16851. // "Connection: close" makes the server close once it has answered, so the
  16852. // response drain ends immediately instead of idling until the read timeout.
  16853. const std::string head =
  16854. "POST /post HTTP/1.1\r\n"
  16855. "Host: localhost\r\n"
  16856. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16857. "Connection: close\r\n"
  16858. "Content-Length: " +
  16859. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16860. std::string response;
  16861. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16862. ASSERT_GE(response.size(), 12u) << "no response";
  16863. EXPECT_EQ("200", response.substr(9, 3));
  16864. }
  16865. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16866. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16867. // ignored, including when it does not arrive in the same read as the
  16868. // close-delimiter itself.
  16869. expect_split_multipart_ok("--zzzz\r\n"
  16870. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16871. "\r\n"
  16872. "text1"
  16873. "\r\n--zzzz--",
  16874. "\r\nthis epilogue must be ignored\r\n");
  16875. }
  16876. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16877. // The initial boundary may be preceded by a preamble of any length and may
  16878. // straddle a read boundary. Discarding data while waiting for it must not
  16879. // throw away a partial boundary sitting at the end of the buffer.
  16880. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16881. "zz\r\n"
  16882. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16883. "\r\n"
  16884. "text1"
  16885. "\r\n--zzzz--\r\n");
  16886. }
  16887. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16888. // The received boundary was only checked for being non-empty, so it could be
  16889. // as long as a header is allowed to be. The parser scans the body for
  16890. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16891. // costs a nearly full comparison at nearly every position, making the
  16892. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16893. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16894. Server svr;
  16895. svr.Post("/post", [](const Request &req, Response &res) {
  16896. EXPECT_EQ(1u, req.form.fields.size());
  16897. EXPECT_EQ("text1", req.form.get_field("text1"));
  16898. res.set_content("ok", "text/plain");
  16899. });
  16900. auto port = svr.bind_to_any_port(HOST);
  16901. thread t = thread([&] { svr.listen_after_bind(); });
  16902. auto se = detail::scope_exit([&] {
  16903. svr.stop();
  16904. t.join();
  16905. ASSERT_FALSE(svr.is_running());
  16906. });
  16907. svr.wait_until_ready();
  16908. Client cli(HOST, port);
  16909. auto post_with_boundary_of_length = [&](size_t len) {
  16910. const std::string boundary(len, 'a');
  16911. const std::string body =
  16912. "--" + boundary +
  16913. "\r\n"
  16914. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16915. "\r\n"
  16916. "text1"
  16917. "\r\n--" +
  16918. boundary + "--\r\n";
  16919. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16920. };
  16921. auto res = post_with_boundary_of_length(70);
  16922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16923. EXPECT_EQ(StatusCode::OK_200, res->status);
  16924. res = post_with_boundary_of_length(71);
  16925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16926. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16927. }
  16928. TEST(MakeFileBodyTest, Basic) {
  16929. const std::string file_content(4096, 'Z');
  16930. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16931. {
  16932. std::ofstream ofs(tmp_path, std::ios::binary);
  16933. ofs.write(file_content.data(),
  16934. static_cast<std::streamsize>(file_content.size()));
  16935. }
  16936. auto handled = false;
  16937. Server svr;
  16938. svr.Post("/upload", [&](const Request &req, Response &res) {
  16939. EXPECT_EQ(file_content, req.body);
  16940. handled = true;
  16941. res.status = StatusCode::OK_200;
  16942. });
  16943. auto port = svr.bind_to_any_port(HOST);
  16944. auto t = thread([&] { svr.listen_after_bind(); });
  16945. auto se = detail::scope_exit([&] {
  16946. svr.stop();
  16947. t.join();
  16948. ASSERT_FALSE(svr.is_running());
  16949. ASSERT_TRUE(handled);
  16950. std::remove(tmp_path.c_str());
  16951. });
  16952. svr.wait_until_ready();
  16953. auto fb = make_file_body(tmp_path);
  16954. ASSERT_GT(fb.first, 0u);
  16955. Client cli(HOST, port);
  16956. auto res =
  16957. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16959. EXPECT_EQ(StatusCode::OK_200, res->status);
  16960. }
  16961. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16962. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16963. {
  16964. std::ofstream ofs(path, std::ios::binary);
  16965. const std::string content(100, 'A');
  16966. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16967. }
  16968. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16969. auto body = make_file_body(path);
  16970. ASSERT_EQ(100u, body.first);
  16971. ASSERT_TRUE(static_cast<bool>(body.second));
  16972. // Rewritten shorter after its length was measured - and, on a server, after
  16973. // that length has already gone out as Content-Length.
  16974. {
  16975. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16976. const std::string content(10, 'A');
  16977. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16978. }
  16979. std::string written;
  16980. DataSink sink;
  16981. sink.write = [&](const char *d, size_t l) {
  16982. written.append(d, l);
  16983. return true;
  16984. };
  16985. // The provider has to report failure. write_content_with_progress() advances
  16986. // its offset only by what was written, so a provider that returns true
  16987. // without completing the length it promised is called again straight away,
  16988. // and again.
  16989. EXPECT_FALSE(body.second(0, body.first, sink));
  16990. EXPECT_EQ(std::string(10, 'A'), written);
  16991. }
  16992. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16993. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16994. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16995. {
  16996. std::ofstream ofs(path, std::ios::binary);
  16997. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16998. }
  16999. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17000. auto body = make_file_body(path);
  17001. ASSERT_EQ(content.size(), body.first);
  17002. ASSERT_TRUE(static_cast<bool>(body.second));
  17003. std::string written;
  17004. DataSink sink;
  17005. sink.write = [&](const char *d, size_t l) {
  17006. written.append(d, l);
  17007. return true;
  17008. };
  17009. EXPECT_TRUE(body.second(0, body.first, sink));
  17010. EXPECT_EQ(content, written);
  17011. }
  17012. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17013. static constexpr unsigned int number_of_tasks{1000000};
  17014. std::atomic_uint count{0};
  17015. std::unique_ptr<TaskQueue> task_queue{
  17016. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17017. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17018. auto queued = task_queue->enqueue(
  17019. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17020. EXPECT_TRUE(queued);
  17021. }
  17022. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17023. task_queue->shutdown();
  17024. #else
  17025. EXPECT_NO_THROW(task_queue->shutdown());
  17026. #endif
  17027. EXPECT_EQ(number_of_tasks, count.load());
  17028. }
  17029. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17030. static constexpr unsigned int number_of_tasks{1000000};
  17031. static constexpr unsigned int qlimit{2};
  17032. unsigned int queued_count{0};
  17033. std::atomic_uint count{0};
  17034. std::unique_ptr<TaskQueue> task_queue{
  17035. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17036. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17037. if (task_queue->enqueue(
  17038. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17039. queued_count++;
  17040. }
  17041. }
  17042. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17043. task_queue->shutdown();
  17044. #else
  17045. EXPECT_NO_THROW(task_queue->shutdown());
  17046. #endif
  17047. EXPECT_EQ(queued_count, count.load());
  17048. EXPECT_TRUE(queued_count <= number_of_tasks);
  17049. EXPECT_TRUE(queued_count >= qlimit);
  17050. }
  17051. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17052. // Use a short idle timeout so a dynamic thread spawns, times out and
  17053. // exits during the test, and the pool keeps working afterwards.
  17054. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17055. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17056. /*idle_timeout_sec=*/1}};
  17057. std::atomic_uint count{0};
  17058. std::condition_variable cv;
  17059. std::mutex mtx;
  17060. bool release = false;
  17061. // Block the base thread so the second task spawns a dynamic thread.
  17062. EXPECT_TRUE(task_queue->enqueue([&] {
  17063. std::unique_lock<std::mutex> lock(mtx);
  17064. while (!release) {
  17065. cv.wait(lock);
  17066. }
  17067. count++;
  17068. }));
  17069. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17070. // Let the dynamic thread finish its task and exceed the idle timeout.
  17071. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17072. {
  17073. std::unique_lock<std::mutex> lock(mtx);
  17074. release = true;
  17075. }
  17076. cv.notify_all();
  17077. // The pool must still accept and run tasks after the dynamic thread exited.
  17078. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17079. task_queue->shutdown();
  17080. EXPECT_EQ(3u, count.load());
  17081. }
  17082. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17083. static constexpr size_t number_of_tasks{32};
  17084. std::unique_ptr<TaskQueue> task_queue{
  17085. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17086. // Let the base threads go idle so the burst below finds them waiting.
  17087. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17088. std::mutex mtx;
  17089. std::condition_variable cv;
  17090. size_t running = 0;
  17091. bool release = false;
  17092. for (size_t i = 0; i < number_of_tasks; i++) {
  17093. EXPECT_TRUE(task_queue->enqueue([&] {
  17094. std::unique_lock<std::mutex> lock(mtx);
  17095. running++;
  17096. cv.notify_all();
  17097. cv.wait(lock, [&] { return release; });
  17098. }));
  17099. }
  17100. {
  17101. std::unique_lock<std::mutex> lock(mtx);
  17102. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17103. [&] { return running == number_of_tasks; }));
  17104. release = true;
  17105. }
  17106. cv.notify_all();
  17107. task_queue->shutdown();
  17108. }
  17109. TEST(TaskQueueTest, MaxQueuedRequests) {
  17110. static constexpr unsigned int qlimit{3};
  17111. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17112. std::condition_variable sem_cv;
  17113. std::mutex sem_mtx;
  17114. int credits = 0;
  17115. bool queued;
  17116. /* Fill up the queue with tasks that will block until we give them credits to
  17117. * complete. */
  17118. for (unsigned int n = 0; n <= qlimit;) {
  17119. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17120. std::unique_lock<std::mutex> lock(sem_mtx);
  17121. while (credits <= 0) {
  17122. sem_cv.wait(lock);
  17123. }
  17124. /* Consume the credit and signal the test code if they are all gone. */
  17125. if (--credits == 0) { sem_cv.notify_one(); }
  17126. });
  17127. if (n < qlimit) {
  17128. /* The first qlimit enqueues must succeed. */
  17129. EXPECT_TRUE(queued);
  17130. } else {
  17131. /* The last one will succeed only when the worker thread
  17132. * starts and dequeues the first blocking task. Although
  17133. * not necessary for the correctness of this test, we sleep for
  17134. * a short while to avoid busy waiting. */
  17135. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17136. }
  17137. if (queued) { n++; }
  17138. }
  17139. /* Further enqueues must fail since the queue is full. */
  17140. for (auto i = 0; i < 4; i++) {
  17141. queued = task_queue->enqueue([] {});
  17142. EXPECT_FALSE(queued);
  17143. }
  17144. /* Give the credits to allow the previous tasks to complete. */
  17145. {
  17146. std::unique_lock<std::mutex> lock(sem_mtx);
  17147. credits += qlimit + 1;
  17148. }
  17149. sem_cv.notify_all();
  17150. /* Wait for all the credits to be consumed. */
  17151. {
  17152. std::unique_lock<std::mutex> lock(sem_mtx);
  17153. while (credits > 0) {
  17154. sem_cv.wait(lock);
  17155. }
  17156. }
  17157. /* Check that we are able again to enqueue at least qlimit tasks. */
  17158. for (unsigned int i = 0; i < qlimit; i++) {
  17159. queued = task_queue->enqueue([] {});
  17160. EXPECT_TRUE(queued);
  17161. }
  17162. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17163. task_queue->shutdown();
  17164. #else
  17165. EXPECT_NO_THROW(task_queue->shutdown());
  17166. #endif
  17167. }
  17168. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17169. Server svr;
  17170. std::string method;
  17171. std::string body;
  17172. auto has_content_length = false;
  17173. auto has_transfer_encoding = false;
  17174. std::atomic<int> bad_requests{0};
  17175. // Leftover body bytes get parsed as a malformed request and answered with
  17176. // 400
  17177. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17178. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17179. });
  17180. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17181. res.set_redirect("/down", StatusCode::SeeOther_303);
  17182. });
  17183. svr.Get("/down", [&](const Request &req, Response &res) {
  17184. method = req.method;
  17185. body = req.body;
  17186. has_content_length = req.has_header("Content-Length");
  17187. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17188. res.set_content("ok", "text/plain");
  17189. });
  17190. auto port = svr.bind_to_any_port(HOST);
  17191. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17192. auto se = detail::scope_exit([&] {
  17193. svr.stop();
  17194. thread.join();
  17195. ASSERT_FALSE(svr.is_running());
  17196. });
  17197. svr.wait_until_ready();
  17198. const std::string payload = "SECRET-BODY";
  17199. auto check = [&](Client &cli, const Result &res) {
  17200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17201. EXPECT_EQ(StatusCode::OK_200, res->status);
  17202. EXPECT_EQ("ok", res->body);
  17203. EXPECT_EQ("GET", method);
  17204. EXPECT_TRUE(body.empty());
  17205. EXPECT_FALSE(has_content_length);
  17206. EXPECT_FALSE(has_transfer_encoding);
  17207. // Nothing of the original body may be left on the connection
  17208. auto res2 = cli.Get("/down");
  17209. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17210. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17211. EXPECT_EQ("ok", res2->body);
  17212. EXPECT_EQ(0, bad_requests);
  17213. };
  17214. // With content length
  17215. {
  17216. Client cli(HOST, port);
  17217. cli.set_keep_alive(true);
  17218. cli.set_follow_location(true);
  17219. auto res = cli.Post(
  17220. "/up", payload.size(),
  17221. [&](size_t offset, size_t length, DataSink &sink) {
  17222. return sink.write(payload.data() + offset, length);
  17223. },
  17224. "text/plain");
  17225. check(cli, res);
  17226. }
  17227. // Without content length (chunked)
  17228. {
  17229. Client cli(HOST, port);
  17230. cli.set_keep_alive(true);
  17231. cli.set_follow_location(true);
  17232. auto res = cli.Post(
  17233. "/up",
  17234. [&](size_t /*offset*/, DataSink &sink) {
  17235. sink.write(payload.data(), payload.size());
  17236. sink.done();
  17237. return true;
  17238. },
  17239. "text/plain");
  17240. check(cli, res);
  17241. }
  17242. }
  17243. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17244. Server svr;
  17245. std::string target;
  17246. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17247. // Echo the still-encoded name back in the Location
  17248. const std::string prefix = "/start/";
  17249. res.status = StatusCode::Found_302;
  17250. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17251. });
  17252. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17253. target = req.target;
  17254. res.set_content("ok", "text/plain");
  17255. });
  17256. auto port = svr.bind_to_any_port(HOST);
  17257. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17258. auto se = detail::scope_exit([&] {
  17259. svr.stop();
  17260. thread.join();
  17261. ASSERT_FALSE(svr.is_running());
  17262. });
  17263. svr.wait_until_ready();
  17264. // Decoding the Location path would turn the first four into a path
  17265. // separator, a query delimiter, a fragment delimiter and a different
  17266. // percent-encoded octet. The rest must keep reaching the server as they are.
  17267. const std::vector<std::string> names = {
  17268. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17269. };
  17270. for (auto path_encode : {true, false}) {
  17271. Client cli(HOST, port);
  17272. cli.set_follow_location(true);
  17273. cli.set_path_encode(path_encode);
  17274. for (const auto &name : names) {
  17275. target.clear();
  17276. auto res = cli.Get("/start/" + name);
  17277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17278. EXPECT_EQ(StatusCode::OK_200, res->status);
  17279. EXPECT_EQ("/dest/" + name, target);
  17280. }
  17281. }
  17282. }
  17283. TEST(RedirectTest, NotModifiedIsReturned) {
  17284. Server svr;
  17285. svr.Get("/cached", [](const Request &, Response &res) {
  17286. res.status = StatusCode::NotModified_304;
  17287. });
  17288. auto port = svr.bind_to_any_port(HOST);
  17289. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17290. auto se = detail::scope_exit([&] {
  17291. svr.stop();
  17292. thread.join();
  17293. ASSERT_FALSE(svr.is_running());
  17294. });
  17295. svr.wait_until_ready();
  17296. Client cli(HOST, port);
  17297. cli.set_follow_location(true);
  17298. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17300. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17301. }
  17302. TEST(RedirectTest, NoLocationIsReturned) {
  17303. Server svr;
  17304. svr.Get("/no-location", [](const Request &, Response &res) {
  17305. res.status = StatusCode::Found_302;
  17306. res.set_content("no location", "text/plain");
  17307. });
  17308. auto port = svr.bind_to_any_port(HOST);
  17309. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17310. auto se = detail::scope_exit([&] {
  17311. svr.stop();
  17312. thread.join();
  17313. ASSERT_FALSE(svr.is_running());
  17314. });
  17315. svr.wait_until_ready();
  17316. Client cli(HOST, port);
  17317. cli.set_follow_location(true);
  17318. auto res = cli.Get("/no-location");
  17319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17320. EXPECT_EQ(StatusCode::Found_302, res->status);
  17321. EXPECT_EQ("no location", res->body);
  17322. // The callbacks see the body of the response that is returned
  17323. auto handler_called = false;
  17324. auto progress_called = false;
  17325. std::string body;
  17326. auto res2 = cli.Get(
  17327. "/no-location",
  17328. [&](const Response &) {
  17329. handler_called = true;
  17330. return true;
  17331. },
  17332. [&](const char *data, size_t data_length) {
  17333. body.append(data, data_length);
  17334. return true;
  17335. },
  17336. [&](size_t, size_t) {
  17337. progress_called = true;
  17338. return true;
  17339. });
  17340. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17341. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17342. EXPECT_TRUE(handler_called);
  17343. EXPECT_TRUE(progress_called);
  17344. EXPECT_EQ("no location", body);
  17345. }
  17346. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17347. Server svr;
  17348. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17349. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17350. });
  17351. svr.Get("/hello", [](const Request &req, Response &res) {
  17352. res.set_content(req.get_param_value("key"), "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. {
  17362. Client cli(HOST, PORT);
  17363. cli.set_follow_location(true);
  17364. auto res = cli.Get("/");
  17365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17366. EXPECT_EQ(StatusCode::OK_200, res->status);
  17367. EXPECT_EQ("val&key2=val2", res->body);
  17368. }
  17369. }
  17370. #endif
  17371. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17372. Server svr;
  17373. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17374. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17375. });
  17376. svr.Get("/hello", [](const Request &req, Response &res) {
  17377. res.set_content(req.get_param_value("key"), "text/plain");
  17378. });
  17379. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17380. auto se = detail::scope_exit([&] {
  17381. svr.stop();
  17382. thread.join();
  17383. ASSERT_FALSE(svr.is_running());
  17384. });
  17385. svr.wait_until_ready();
  17386. {
  17387. Client cli(HOST, PORT);
  17388. cli.set_follow_location(true);
  17389. auto res = cli.Get("/");
  17390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17391. EXPECT_EQ(StatusCode::OK_200, res->status);
  17392. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17393. }
  17394. }
  17395. TEST(RedirectTest, RedirectWithPlusInPath) {
  17396. Server svr;
  17397. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17398. res.set_redirect("/a+b");
  17399. });
  17400. // Route pattern uses regex; escape + as \\+
  17401. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17402. res.set_content(req.path, "text/plain");
  17403. });
  17404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17405. auto se = detail::scope_exit([&] {
  17406. svr.stop();
  17407. thread.join();
  17408. ASSERT_FALSE(svr.is_running());
  17409. });
  17410. svr.wait_until_ready();
  17411. {
  17412. Client cli(HOST, PORT);
  17413. cli.set_follow_location(true);
  17414. auto res = cli.Get("/");
  17415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17416. EXPECT_EQ(StatusCode::OK_200, res->status);
  17417. EXPECT_EQ("/a+b", res->body);
  17418. }
  17419. }
  17420. TEST(RedirectTest, ResolveRelativeLocation) {
  17421. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17422. const std::vector<std::pair<std::string, std::string>> cases = {
  17423. {"g", "/b/c/g"},
  17424. {"./g", "/b/c/g"},
  17425. {"g/", "/b/c/g/"},
  17426. {"?y", "/b/c/d;p?y"},
  17427. {"g?y", "/b/c/g?y"},
  17428. {"#s", "/b/c/d;p?q#s"},
  17429. {"g#s", "/b/c/g#s"},
  17430. {"g?y#s", "/b/c/g?y#s"},
  17431. {";x", "/b/c/;x"},
  17432. {"g;x", "/b/c/g;x"},
  17433. {".", "/b/c/"},
  17434. {"./", "/b/c/"},
  17435. {"..", "/b/"},
  17436. {"../", "/b/"},
  17437. {"../g", "/b/g"},
  17438. {"../..", "/"},
  17439. {"../../", "/"},
  17440. {"../../g", "/g"},
  17441. {"../../../g", "/g"},
  17442. {"g.", "/b/c/g."},
  17443. {".g", "/b/c/.g"},
  17444. {"g..", "/b/c/g.."},
  17445. {"..g", "/b/c/..g"},
  17446. {"./../g", "/b/g"},
  17447. {"./g/.", "/b/c/g/"},
  17448. {"g/./h", "/b/c/g/h"},
  17449. {"g/../h", "/b/c/h"},
  17450. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17451. {"g;x=1/../y", "/b/c/y"},
  17452. {"g?y/./x", "/b/c/g?y/./x"},
  17453. {"g#s/../x", "/b/c/g#s/../x"},
  17454. // Not relative-path references, so left for parse_url.
  17455. {"/g", "/g"},
  17456. {"//g", "//g"},
  17457. {"http://g/x", "http://g/x"},
  17458. {"g:h", "g:h"},
  17459. };
  17460. for (const auto &c : cases) {
  17461. EXPECT_EQ(c.second,
  17462. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17463. << c.first;
  17464. }
  17465. // A result starting with "//" is still a path, not a network-path reference
  17466. EXPECT_EQ("/.//g",
  17467. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  17468. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  17469. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  17470. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  17471. }
  17472. TEST(RedirectTest, RemoveDotSegments) {
  17473. // RFC 3986 section 5.2.4
  17474. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17475. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17476. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17477. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17478. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17479. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17480. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17481. }
  17482. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17483. Server svr;
  17484. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17485. res.set_redirect("/dir/../target?x=1");
  17486. });
  17487. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17488. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17489. "/dir/./../target");
  17490. });
  17491. svr.Get("/target", [](const Request &req, Response &res) {
  17492. res.set_content(req.path, "text/plain");
  17493. });
  17494. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17495. auto se = detail::scope_exit([&] {
  17496. svr.stop();
  17497. th.join();
  17498. ASSERT_FALSE(svr.is_running());
  17499. });
  17500. svr.wait_until_ready();
  17501. Client cli("localhost", PORT);
  17502. cli.set_follow_location(true);
  17503. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17504. auto res = cli.Get(path);
  17505. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17506. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17507. EXPECT_EQ("/target", res->body) << path;
  17508. }
  17509. }
  17510. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17511. Server svr;
  17512. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17513. res.set_redirect(req.get_param_value("to"));
  17514. });
  17515. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17516. res.set_content(req.target, "text/plain");
  17517. });
  17518. svr.Get("/other", [](const Request &req, Response &res) {
  17519. res.set_content(req.target, "text/plain");
  17520. });
  17521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17522. auto se = detail::scope_exit([&] {
  17523. svr.stop();
  17524. thread.join();
  17525. ASSERT_FALSE(svr.is_running());
  17526. });
  17527. svr.wait_until_ready();
  17528. const std::vector<std::pair<std::string, std::string>> cases = {
  17529. {"next", "/dir/next"},
  17530. {"./next?x=1", "/dir/next?x=1"},
  17531. {"../other", "/other"},
  17532. };
  17533. for (const auto &c : cases) {
  17534. Client cli(HOST, PORT);
  17535. cli.set_follow_location(true);
  17536. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17537. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17538. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17539. EXPECT_EQ(c.second, res->body) << c.first;
  17540. }
  17541. }
  17542. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  17543. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  17544. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  17545. Server other;
  17546. std::atomic<int> other_hits{0};
  17547. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  17548. other_hits++;
  17549. res.set_content("other", "text/plain");
  17550. });
  17551. auto other_port = other.bind_to_any_port("127.0.0.1");
  17552. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  17553. Server svr;
  17554. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17555. res.set_redirect(req.get_param_value("to"));
  17556. });
  17557. svr.Get(".*", [](const Request &req, Response &res) {
  17558. res.set_content(req.path, "text/plain");
  17559. });
  17560. auto port = svr.bind_to_any_port(HOST);
  17561. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17562. auto se = detail::scope_exit([&] {
  17563. svr.stop();
  17564. thread.join();
  17565. other.stop();
  17566. other_thread.join();
  17567. ASSERT_FALSE(svr.is_running());
  17568. ASSERT_FALSE(other.is_running());
  17569. });
  17570. svr.wait_until_ready();
  17571. other.wait_until_ready();
  17572. auto authority = "127.0.0.1:" + std::to_string(other_port);
  17573. for (const auto &to :
  17574. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  17575. Client cli(HOST, port);
  17576. cli.set_follow_location(true);
  17577. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  17578. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  17579. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  17580. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  17581. }
  17582. EXPECT_EQ(0, other_hits.load());
  17583. }
  17584. #ifdef CPPHTTPLIB_SSL_ENABLED
  17585. TEST(RedirectTest, Issue2185_Online) {
  17586. SSLClient client("github.com");
  17587. client.set_follow_location(true);
  17588. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17589. "Coollab-Windows.zip");
  17590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17591. EXPECT_EQ(StatusCode::OK_200, res->status);
  17592. EXPECT_EQ(9920427U, res->body.size());
  17593. }
  17594. #endif
  17595. TEST(VulnerabilityTest, CRLFInjection) {
  17596. Server svr;
  17597. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17598. res.set_content("Hello 1", "text/plain");
  17599. });
  17600. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17601. res.set_content("Hello 2", "text/plain");
  17602. });
  17603. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17604. res.set_content("Hello 3", "text/plain");
  17605. });
  17606. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17607. res.set_content("Hello 4", "text/plain");
  17608. });
  17609. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17610. for (const auto &x : req.headers) {
  17611. auto key = x.first;
  17612. EXPECT_STRNE("evil", key.c_str());
  17613. }
  17614. });
  17615. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17616. auto se = detail::scope_exit([&] {
  17617. svr.stop();
  17618. thread.join();
  17619. ASSERT_FALSE(svr.is_running());
  17620. });
  17621. svr.wait_until_ready();
  17622. {
  17623. Client cli(HOST, PORT);
  17624. cli.Post("/test1", "A=B",
  17625. "application/x-www-form-urlencoded\r\nevil: hello1");
  17626. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17627. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17628. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17629. }
  17630. }
  17631. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17632. auto server_thread = std::thread([] {
  17633. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17634. default_socket_options(srv);
  17635. sockaddr_in addr{};
  17636. addr.sin_family = AF_INET;
  17637. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17638. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17639. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17640. ::listen(srv, 1);
  17641. sockaddr_in cli_addr{};
  17642. socklen_t cli_len = sizeof(cli_addr);
  17643. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17644. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17645. std::string buf_all;
  17646. char buf[2048];
  17647. ssize_t n;
  17648. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17649. buf_all.append(buf, static_cast<size_t>(n));
  17650. size_t pos;
  17651. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17652. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17653. auto e = request_block.find("\r\n");
  17654. if (e != std::string::npos) {
  17655. auto request_line = request_block.substr(0, e);
  17656. std::string msg =
  17657. "CRLF injection detected in request line: '" + request_line + "'";
  17658. EXPECT_FALSE(true) << msg;
  17659. }
  17660. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17661. ::send(cli,
  17662. #ifdef _WIN32
  17663. static_cast<const char *>(resp.c_str()),
  17664. static_cast<int>(resp.size()),
  17665. #else
  17666. resp.c_str(), resp.size(),
  17667. #endif
  17668. 0);
  17669. buf_all.erase(0, pos + 4);
  17670. }
  17671. }
  17672. detail::close_socket(cli);
  17673. detail::close_socket(srv);
  17674. });
  17675. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17676. auto cli = Client("127.0.0.1", PORT + 1);
  17677. auto headers = Headers{
  17678. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17679. {"Connection", "keep-alive"}};
  17680. auto res = cli.Get("/hi", headers);
  17681. EXPECT_FALSE(res);
  17682. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17683. server_thread.join();
  17684. }
  17685. // A request rejected before any byte reaches the socket must fail right away
  17686. // instead of waiting for a response the server will never send.
  17687. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17688. // The kernel completes the TCP handshake from the listen backlog, so the
  17689. // client connects, but nothing ever reads, responds or closes.
  17690. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17691. default_socket_options(srv);
  17692. sockaddr_in addr{};
  17693. addr.sin_family = AF_INET;
  17694. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17695. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17696. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17697. ASSERT_EQ(0, ::listen(srv, 8));
  17698. auto cli = Client("127.0.0.1", PORT + 1);
  17699. cli.set_read_timeout(10, 0);
  17700. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17701. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17702. std::chrono::steady_clock::now() - start)
  17703. .count();
  17704. };
  17705. {
  17706. Request req;
  17707. req.method = "GE T";
  17708. req.path = "/";
  17709. auto start = std::chrono::steady_clock::now();
  17710. auto res = cli.send(req);
  17711. EXPECT_FALSE(res);
  17712. EXPECT_EQ(Error::Write, res.error());
  17713. EXPECT_LT(elapsed_ms(start), 1000);
  17714. }
  17715. {
  17716. auto start = std::chrono::steady_clock::now();
  17717. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17718. EXPECT_FALSE(res);
  17719. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17720. EXPECT_LT(elapsed_ms(start), 1000);
  17721. }
  17722. EXPECT_FALSE(cli.is_socket_open());
  17723. detail::close_socket(srv);
  17724. }
  17725. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17726. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17727. default_socket_options(srv);
  17728. sockaddr_in addr{};
  17729. addr.sin_family = AF_INET;
  17730. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17731. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17732. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17733. ASSERT_EQ(0, ::listen(srv, 1));
  17734. std::string received;
  17735. auto server_thread = std::thread([&] {
  17736. auto sock = ::accept(srv, nullptr, nullptr);
  17737. if (sock == INVALID_SOCKET) { return; }
  17738. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17739. char buf[2048];
  17740. ssize_t n;
  17741. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17742. received.append(buf, static_cast<size_t>(n));
  17743. }
  17744. detail::close_socket(sock);
  17745. });
  17746. {
  17747. auto cli = Client("127.0.0.1", PORT + 1);
  17748. // "Z" sorts after the default headers, so writing straight to the socket
  17749. // would have sent the request line and those headers before the rejection.
  17750. auto handle =
  17751. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17752. EXPECT_FALSE(handle.is_valid());
  17753. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17754. }
  17755. server_thread.join();
  17756. detail::close_socket(srv);
  17757. EXPECT_TRUE(received.empty()) << received;
  17758. }
  17759. TEST(PathParamsTest, StaticMatch) {
  17760. const auto pattern = "/users/all";
  17761. detail::PathParamsMatcher matcher(pattern);
  17762. Request request;
  17763. request.path = "/users/all";
  17764. ASSERT_TRUE(matcher.match(request));
  17765. std::unordered_map<std::string, std::string> expected_params = {};
  17766. EXPECT_EQ(request.path_params, expected_params);
  17767. }
  17768. TEST(PathParamsTest, StaticMismatch) {
  17769. const auto pattern = "/users/all";
  17770. detail::PathParamsMatcher matcher(pattern);
  17771. Request request;
  17772. request.path = "/users/1";
  17773. ASSERT_FALSE(matcher.match(request));
  17774. }
  17775. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17776. const auto pattern = "/users/:id/subscriptions";
  17777. detail::PathParamsMatcher matcher(pattern);
  17778. Request request;
  17779. request.path = "/users/42/subscriptions";
  17780. ASSERT_TRUE(matcher.match(request));
  17781. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17782. EXPECT_EQ(request.path_params, expected_params);
  17783. }
  17784. TEST(PathParamsTest, SingleParamInTheEnd) {
  17785. const auto pattern = "/users/:id";
  17786. detail::PathParamsMatcher matcher(pattern);
  17787. Request request;
  17788. request.path = "/users/24";
  17789. ASSERT_TRUE(matcher.match(request));
  17790. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17791. EXPECT_EQ(request.path_params, expected_params);
  17792. }
  17793. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17794. const auto pattern = "/users/:id/";
  17795. detail::PathParamsMatcher matcher(pattern);
  17796. Request request;
  17797. request.path = "/users/42/";
  17798. ASSERT_TRUE(matcher.match(request));
  17799. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17800. EXPECT_EQ(request.path_params, expected_params);
  17801. }
  17802. TEST(PathParamsTest, EmptyParam) {
  17803. const auto pattern = "/users/:id/";
  17804. detail::PathParamsMatcher matcher(pattern);
  17805. Request request;
  17806. request.path = "/users//";
  17807. ASSERT_TRUE(matcher.match(request));
  17808. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17809. EXPECT_EQ(request.path_params, expected_params);
  17810. }
  17811. TEST(PathParamsTest, FragmentMismatch) {
  17812. const auto pattern = "/users/:id/";
  17813. detail::PathParamsMatcher matcher(pattern);
  17814. Request request;
  17815. request.path = "/admins/24/";
  17816. ASSERT_FALSE(matcher.match(request));
  17817. }
  17818. TEST(PathParamsTest, ExtraFragments) {
  17819. const auto pattern = "/users/:id";
  17820. detail::PathParamsMatcher matcher(pattern);
  17821. Request request;
  17822. request.path = "/users/42/subscriptions";
  17823. ASSERT_FALSE(matcher.match(request));
  17824. }
  17825. TEST(PathParamsTest, MissingTrailingParam) {
  17826. const auto pattern = "/users/:id";
  17827. detail::PathParamsMatcher matcher(pattern);
  17828. Request request;
  17829. request.path = "/users";
  17830. ASSERT_FALSE(matcher.match(request));
  17831. }
  17832. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17833. const auto pattern = "/users/:id/subscriptions";
  17834. detail::PathParamsMatcher matcher(pattern);
  17835. Request request;
  17836. request.path = "/users/subscriptions";
  17837. ASSERT_FALSE(matcher.match(request));
  17838. }
  17839. TEST(PathParamsTest, MultipleParams) {
  17840. const auto pattern = "/users/:userid/subscriptions/:subid";
  17841. detail::PathParamsMatcher matcher(pattern);
  17842. Request request;
  17843. request.path = "/users/42/subscriptions/2";
  17844. ASSERT_TRUE(matcher.match(request));
  17845. std::unordered_map<std::string, std::string> expected_params = {
  17846. {"userid", "42"}, {"subid", "2"}};
  17847. EXPECT_EQ(request.path_params, expected_params);
  17848. }
  17849. TEST(PathParamsTest, SequenceOfParams) {
  17850. const auto pattern = "/values/:x/:y/:z";
  17851. detail::PathParamsMatcher matcher(pattern);
  17852. Request request;
  17853. request.path = "/values/1/2/3";
  17854. ASSERT_TRUE(matcher.match(request));
  17855. std::unordered_map<std::string, std::string> expected_params = {
  17856. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17857. EXPECT_EQ(request.path_params, expected_params);
  17858. }
  17859. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17860. const auto pattern = "/prefix:suffix";
  17861. detail::PathParamsMatcher matcher(pattern);
  17862. Request request;
  17863. request.path = "/prefix:suffix";
  17864. ASSERT_TRUE(matcher.match(request));
  17865. const std::unordered_map<std::string, std::string> expected_params = {};
  17866. EXPECT_EQ(request.path_params, expected_params);
  17867. }
  17868. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17869. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17870. // calling thread's stack on a long enough path for a quantified pattern;
  17871. // RegexMatcher must refuse to run regex matching on paths beyond
  17872. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17873. detail::RegexMatcher matcher("/files/(.*)");
  17874. Request within_limit;
  17875. within_limit.path = "/files/" + std::string(10, 'A');
  17876. EXPECT_TRUE(matcher.match(within_limit));
  17877. Request over_limit;
  17878. over_limit.path =
  17879. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17880. EXPECT_FALSE(matcher.match(over_limit));
  17881. }
  17882. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17883. Server svr;
  17884. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17885. res.set_content("ok", "text/plain");
  17886. });
  17887. auto port = svr.bind_to_any_port(HOST);
  17888. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17889. auto se = detail::scope_exit([&] {
  17890. svr.stop();
  17891. thread.join();
  17892. ASSERT_FALSE(svr.is_running());
  17893. });
  17894. svr.wait_until_ready();
  17895. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17896. // request URI limit; this used to be able to crash the process.
  17897. std::string path =
  17898. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17899. std::string req = "GET " + path +
  17900. " HTTP/1.1\r\n"
  17901. "Host: " +
  17902. std::string(HOST) + ":" + std::to_string(port) +
  17903. "\r\n"
  17904. "Connection: close\r\n"
  17905. "\r\n";
  17906. std::string response;
  17907. ASSERT_TRUE(send_request(5, req, &response, port));
  17908. EXPECT_NE(std::string::npos, response.find("404"));
  17909. }
  17910. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17911. Server svr;
  17912. auto handler = [](const Request & /*req*/, Response &res) {
  17913. res.set_content("hit", "text/plain");
  17914. };
  17915. // No regex metacharacter, so this one is compared literally
  17916. svr.Get("/literal/route", handler);
  17917. // '.' is a regex metacharacter, so this one must keep regex semantics
  17918. svr.Get("/a.c", handler);
  17919. auto port = svr.bind_to_any_port(HOST);
  17920. std::thread t([&]() { svr.listen_after_bind(); });
  17921. auto se = detail::scope_exit([&] {
  17922. svr.stop();
  17923. t.join();
  17924. ASSERT_FALSE(svr.is_running());
  17925. });
  17926. svr.wait_until_ready();
  17927. Client cli(HOST, port);
  17928. struct {
  17929. const char *path;
  17930. int status;
  17931. } cases[] = {
  17932. {"/literal/route", StatusCode::OK_200},
  17933. {"/literal/routes", StatusCode::NotFound_404},
  17934. {"/literal/rout", StatusCode::NotFound_404},
  17935. {"/abc", StatusCode::OK_200},
  17936. {"/a.c", StatusCode::OK_200},
  17937. };
  17938. for (const auto &x : cases) {
  17939. auto res = cli.Get(x.path);
  17940. ASSERT_TRUE(res) << x.path;
  17941. EXPECT_EQ(x.status, res->status) << x.path;
  17942. }
  17943. }
  17944. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17945. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17946. // from exhausting the stack, so it must only constrain routes that actually
  17947. // run a regular expression. A literal route is matched by comparison and
  17948. // stays usable at any length.
  17949. Server svr;
  17950. const std::string pattern =
  17951. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17952. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17953. res.set_content("hit", "text/plain");
  17954. });
  17955. auto port = svr.bind_to_any_port(HOST);
  17956. std::thread t([&]() { svr.listen_after_bind(); });
  17957. auto se = detail::scope_exit([&] {
  17958. svr.stop();
  17959. t.join();
  17960. ASSERT_FALSE(svr.is_running());
  17961. });
  17962. svr.wait_until_ready();
  17963. Client cli(HOST, port);
  17964. auto res = cli.Get(pattern);
  17965. ASSERT_TRUE(res);
  17966. EXPECT_EQ(StatusCode::OK_200, res->status);
  17967. }
  17968. TEST(ParseUrlTest, VariousPatterns) {
  17969. {
  17970. detail::UrlComponents uc;
  17971. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17972. EXPECT_EQ("http", uc.scheme);
  17973. EXPECT_EQ("example.com", uc.host);
  17974. EXPECT_EQ("8080", uc.port);
  17975. EXPECT_EQ("/path", uc.path);
  17976. EXPECT_EQ("?q=1", uc.query);
  17977. }
  17978. {
  17979. detail::UrlComponents uc;
  17980. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17981. EXPECT_EQ("https", uc.scheme);
  17982. EXPECT_EQ("example.com", uc.host);
  17983. EXPECT_TRUE(uc.port.empty());
  17984. EXPECT_EQ("/path", uc.path);
  17985. }
  17986. {
  17987. detail::UrlComponents uc;
  17988. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17989. EXPECT_EQ("::1", uc.host);
  17990. EXPECT_EQ("8080", uc.port);
  17991. EXPECT_EQ("/path", uc.path);
  17992. }
  17993. {
  17994. detail::UrlComponents uc;
  17995. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17996. }
  17997. {
  17998. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17999. // the path while the connection still targets the bracketed host.
  18000. detail::UrlComponents uc;
  18001. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18002. }
  18003. {
  18004. detail::UrlComponents uc;
  18005. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18006. }
  18007. {
  18008. detail::UrlComponents uc;
  18009. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18010. EXPECT_EQ("::1", uc.host);
  18011. EXPECT_TRUE(uc.port.empty());
  18012. EXPECT_EQ("/path", uc.path);
  18013. }
  18014. {
  18015. detail::UrlComponents uc;
  18016. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18017. EXPECT_TRUE(uc.scheme.empty());
  18018. EXPECT_EQ("example.com", uc.host);
  18019. EXPECT_EQ("/path", uc.path);
  18020. EXPECT_EQ("?q=1", uc.query);
  18021. }
  18022. {
  18023. detail::UrlComponents uc;
  18024. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18025. EXPECT_TRUE(uc.host.empty());
  18026. EXPECT_EQ("/path", uc.path);
  18027. EXPECT_EQ("?q=1", uc.query);
  18028. }
  18029. {
  18030. detail::UrlComponents uc;
  18031. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18032. EXPECT_EQ("example.com", uc.host);
  18033. EXPECT_EQ("8080", uc.port);
  18034. }
  18035. {
  18036. // Unix socket path — must not be parsed as host
  18037. detail::UrlComponents uc;
  18038. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18039. EXPECT_TRUE(uc.host.empty());
  18040. }
  18041. {
  18042. detail::UrlComponents uc;
  18043. ASSERT_TRUE(detail::parse_url("", uc));
  18044. EXPECT_TRUE(uc.host.empty());
  18045. EXPECT_TRUE(uc.path.empty());
  18046. }
  18047. {
  18048. detail::UrlComponents uc;
  18049. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18050. }
  18051. {
  18052. detail::UrlComponents uc;
  18053. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18054. }
  18055. {
  18056. // Accepted by parse_url; callers restrict to http/https
  18057. detail::UrlComponents uc;
  18058. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18059. EXPECT_EQ("ftp", uc.scheme);
  18060. }
  18061. {
  18062. detail::UrlComponents uc;
  18063. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18064. }
  18065. {
  18066. detail::UrlComponents uc;
  18067. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18068. }
  18069. }
  18070. TEST(ParseUrlTest, FragmentHandling) {
  18071. {
  18072. detail::UrlComponents uc;
  18073. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18074. EXPECT_EQ("/path", uc.path);
  18075. EXPECT_TRUE(uc.query.empty());
  18076. }
  18077. {
  18078. detail::UrlComponents uc;
  18079. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18080. EXPECT_TRUE(uc.path.empty());
  18081. EXPECT_TRUE(uc.query.empty());
  18082. }
  18083. }
  18084. TEST(ParseUrlTest, UserinfoHandling) {
  18085. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18086. // parsers would see evil.com as the host.
  18087. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18088. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18089. for (auto url : urls) {
  18090. detail::UrlComponents uc;
  18091. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18092. }
  18093. }
  18094. TEST(ParseUrlTest, IPv6EdgeCases) {
  18095. {
  18096. detail::UrlComponents uc;
  18097. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18098. EXPECT_TRUE(uc.scheme.empty());
  18099. EXPECT_EQ("::1", uc.host);
  18100. EXPECT_EQ("8080", uc.port);
  18101. }
  18102. {
  18103. // Zone ID '%25' is not in [a-fA-F0-9:]
  18104. detail::UrlComponents uc;
  18105. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18106. }
  18107. }
  18108. TEST(ParseUrlTest, SchemeEdgeCases) {
  18109. {
  18110. detail::UrlComponents uc;
  18111. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18112. }
  18113. {
  18114. detail::UrlComponents uc;
  18115. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18116. }
  18117. {
  18118. detail::UrlComponents uc;
  18119. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18120. }
  18121. }
  18122. TEST(ParseUrlTest, PortEdgeCases) {
  18123. {
  18124. detail::UrlComponents uc;
  18125. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18126. EXPECT_TRUE(uc.port.empty());
  18127. EXPECT_EQ("/path", uc.path);
  18128. }
  18129. {
  18130. // parse_url accepts any port string; validation is done by parse_port
  18131. detail::UrlComponents uc;
  18132. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18133. EXPECT_EQ("abc", uc.port);
  18134. }
  18135. }
  18136. TEST(ParseUrlTest, WebSocketPatterns) {
  18137. {
  18138. detail::UrlComponents uc;
  18139. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18140. EXPECT_EQ("ws", uc.scheme);
  18141. EXPECT_EQ("echo.example.com", uc.host);
  18142. EXPECT_EQ("8080", uc.port);
  18143. EXPECT_EQ("/ws", uc.path);
  18144. }
  18145. {
  18146. detail::UrlComponents uc;
  18147. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18148. EXPECT_EQ("wss", uc.scheme);
  18149. EXPECT_EQ("echo.example.com", uc.host);
  18150. EXPECT_TRUE(uc.port.empty());
  18151. EXPECT_EQ("/ws", uc.path);
  18152. }
  18153. }
  18154. TEST(ParseUrlTest, QueryOnly) {
  18155. detail::UrlComponents uc;
  18156. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18157. EXPECT_TRUE(uc.host.empty());
  18158. EXPECT_TRUE(uc.path.empty());
  18159. EXPECT_EQ("?q=1&r=2", uc.query);
  18160. }
  18161. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18162. detail::UrlComponents uc;
  18163. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18164. EXPECT_TRUE(uc.scheme.empty());
  18165. EXPECT_EQ("example.com", uc.host);
  18166. EXPECT_EQ("443", uc.port);
  18167. EXPECT_EQ("/path", uc.path);
  18168. }
  18169. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18170. // If ipv6 regex working, regex match codepath is taken.
  18171. // else port will default to 80 in Client impl
  18172. int clientImplMagicPort = 80;
  18173. int port = 4321;
  18174. // above ports must be different to avoid false negative
  18175. EXPECT_NE(clientImplMagicPort, port);
  18176. std::string ipV6TestURL = "http://[ff06::c3]";
  18177. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18178. CLIENT_PRIVATE_KEY_FILE);
  18179. EXPECT_EQ(cli.port(), port);
  18180. }
  18181. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18182. auto file_path = "./www/dir/index.html";
  18183. auto dir_path = "./www/dir";
  18184. detail::FileStat stat_file(file_path);
  18185. EXPECT_TRUE(stat_file.is_file());
  18186. EXPECT_FALSE(stat_file.is_dir());
  18187. detail::FileStat stat_dir(dir_path);
  18188. EXPECT_FALSE(stat_dir.is_file());
  18189. EXPECT_TRUE(stat_dir.is_dir());
  18190. }
  18191. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18192. // IPv4 with default HTTP port (80)
  18193. EXPECT_EQ("example.com",
  18194. detail::make_host_and_port_string("example.com", 80, false));
  18195. // IPv4 with default HTTPS port (443)
  18196. EXPECT_EQ("example.com",
  18197. detail::make_host_and_port_string("example.com", 443, true));
  18198. // IPv4 with non-default HTTP port
  18199. EXPECT_EQ("example.com:8080",
  18200. detail::make_host_and_port_string("example.com", 8080, false));
  18201. // IPv4 with non-default HTTPS port
  18202. EXPECT_EQ("example.com:8443",
  18203. detail::make_host_and_port_string("example.com", 8443, true));
  18204. // IPv6 with default HTTP port (80)
  18205. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18206. // IPv6 with default HTTPS port (443)
  18207. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18208. // IPv6 with non-default HTTP port
  18209. EXPECT_EQ("[::1]:8080",
  18210. detail::make_host_and_port_string("::1", 8080, false));
  18211. // IPv6 with non-default HTTPS port
  18212. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18213. // IPv6 full address with default port
  18214. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18215. detail::make_host_and_port_string(
  18216. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18217. // IPv6 full address with non-default port
  18218. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18219. detail::make_host_and_port_string(
  18220. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18221. // IPv6 localhost with non-default port
  18222. EXPECT_EQ("[::1]:3000",
  18223. detail::make_host_and_port_string("::1", 3000, false));
  18224. // IPv6 with zone ID (link-local address) with default port
  18225. EXPECT_EQ("[fe80::1%eth0]",
  18226. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18227. // IPv6 with zone ID (link-local address) with non-default port
  18228. EXPECT_EQ("[fe80::1%eth0]:8080",
  18229. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18230. // Edge case: Port 443 with is_ssl=false (should add port)
  18231. EXPECT_EQ("example.com:443",
  18232. detail::make_host_and_port_string("example.com", 443, false));
  18233. // Edge case: Port 80 with is_ssl=true (should add port)
  18234. EXPECT_EQ("example.com:80",
  18235. detail::make_host_and_port_string("example.com", 80, true));
  18236. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18237. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18238. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18239. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18240. // Security fix: Already bracketed IPv6 should not get double brackets
  18241. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18242. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18243. EXPECT_EQ("[::1]:8080",
  18244. detail::make_host_and_port_string("[::1]", 8080, false));
  18245. EXPECT_EQ("[2001:db8::1]:8080",
  18246. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18247. EXPECT_EQ("[fe80::1%eth0]",
  18248. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18249. EXPECT_EQ("[fe80::1%eth0]:8080",
  18250. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18251. // Edge case: Empty host (should return as-is)
  18252. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18253. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18254. // This is a known limitation but shouldn't crash
  18255. EXPECT_EQ("[host:name]",
  18256. detail::make_host_and_port_string("host:name", 80, false));
  18257. // Port number edge cases (no validation, but should not crash)
  18258. EXPECT_EQ("example.com:0",
  18259. detail::make_host_and_port_string("example.com", 0, false));
  18260. EXPECT_EQ("example.com:-1",
  18261. detail::make_host_and_port_string("example.com", -1, false));
  18262. EXPECT_EQ("example.com:65535",
  18263. detail::make_host_and_port_string("example.com", 65535, false));
  18264. EXPECT_EQ("example.com:65536",
  18265. detail::make_host_and_port_string("example.com", 65536, false));
  18266. }
  18267. namespace httplib {
  18268. namespace detail {
  18269. std::string
  18270. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18271. const std::string &host, int port);
  18272. } // namespace detail
  18273. } // namespace httplib
  18274. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18275. std::map<std::string, std::string> addr_map = {
  18276. {"ipv4.example", "192.0.2.10"},
  18277. {"ipv6.example", "2001:db8::1"},
  18278. {"name.example", "internal.example.lan"},
  18279. {"empty.example", ""}};
  18280. EXPECT_EQ("192.0.2.10:443",
  18281. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18282. EXPECT_EQ("[2001:db8::1]:443",
  18283. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18284. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18285. addr_map, "name.example", 8443));
  18286. // An empty or absent mapping keeps the hostname as the target
  18287. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18288. addr_map, "empty.example", 443));
  18289. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18290. addr_map, "other.example", 443));
  18291. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18292. }
  18293. #ifdef CPPHTTPLIB_SSL_ENABLED
  18294. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18295. httplib::SSLClient cli("roblox.com", 443);
  18296. cli.set_follow_location(true);
  18297. auto res = cli.Get("/");
  18298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18299. EXPECT_EQ(StatusCode::OK_200, res->status);
  18300. }
  18301. #endif
  18302. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18303. Server svr;
  18304. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18305. EXPECT_EQ(res.status, 400);
  18306. });
  18307. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18308. auto se = detail::scope_exit([&] {
  18309. svr.stop();
  18310. thread.join();
  18311. ASSERT_FALSE(svr.is_running());
  18312. });
  18313. svr.wait_until_ready();
  18314. Client cli(HOST, PORT);
  18315. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18316. }
  18317. TEST(InvalidHeaderCharsTest, is_field_name) {
  18318. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18319. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18320. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18321. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18322. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18323. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18324. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18325. EXPECT_FALSE(detail::fields::is_field_name(""));
  18326. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18327. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18328. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18329. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18330. }
  18331. TEST(InvalidHeaderCharsTest, is_field_value) {
  18332. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18333. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18334. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18335. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18336. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18337. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18338. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18339. EXPECT_TRUE(detail::fields::is_field_value(""));
  18340. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18341. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18342. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18343. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18344. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18345. }
  18346. TEST(InvalidHeaderCharsTest, OnServer) {
  18347. Server svr;
  18348. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18349. std::string header = "Not Set";
  18350. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18351. res.set_header(header, "value");
  18352. res.set_content("Page Content Page Content", "text/plain");
  18353. });
  18354. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18355. std::string header = "Not Set";
  18356. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18357. res.set_header("X-Test", header);
  18358. res.set_content("Page Content Page Content", "text/plain");
  18359. });
  18360. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18361. auto se = detail::scope_exit([&] {
  18362. svr.stop();
  18363. thread.join();
  18364. ASSERT_FALSE(svr.is_running());
  18365. });
  18366. svr.wait_until_ready();
  18367. Client cli(HOST, PORT);
  18368. {
  18369. auto res = cli.Get(
  18370. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18372. EXPECT_EQ("Page Content Page Content", res->body);
  18373. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18374. }
  18375. {
  18376. auto res = cli.Get(
  18377. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18379. EXPECT_EQ("Page Content Page Content", res->body);
  18380. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18381. }
  18382. }
  18383. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18384. auto handled = false;
  18385. Server svr;
  18386. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18387. thread t = thread([&] { svr.listen(HOST, PORT); });
  18388. auto se = detail::scope_exit([&] {
  18389. svr.stop();
  18390. t.join();
  18391. ASSERT_FALSE(svr.is_running());
  18392. ASSERT_FALSE(handled);
  18393. });
  18394. svr.wait_until_ready();
  18395. auto req = "POST /test HTTP/1.1\r\n"
  18396. "Content-Length: x\r\n"
  18397. "\r\n";
  18398. std::string response;
  18399. ASSERT_TRUE(send_request(1, req, &response));
  18400. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18401. response.substr(0, response.find("\r\n")));
  18402. }
  18403. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18404. // case-insensitive, and a server that receives a 100-continue expectation in
  18405. // an HTTP/1.0 request MUST ignore it.
  18406. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18407. std::string response;
  18408. ASSERT_TRUE(send_request(1, req, &response, port));
  18409. *got_100 = response.find("100 Continue") != std::string::npos;
  18410. }
  18411. class ExpectTokenTest : public ::testing::Test {
  18412. protected:
  18413. void SetUp() override {
  18414. svr_.Post("/p", [](const Request &, Response &res) {
  18415. res.set_content("ok", "text/plain");
  18416. });
  18417. port_ = svr_.bind_to_any_port(HOST);
  18418. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18419. svr_.wait_until_ready();
  18420. }
  18421. void TearDown() override {
  18422. svr_.stop();
  18423. if (thread_.joinable()) { thread_.join(); }
  18424. }
  18425. std::string request(const char *version, const char *expect_value) const {
  18426. return std::string("POST /p ") + version +
  18427. "\r\n"
  18428. "Host: localhost\r\n"
  18429. "Content-Length: 2\r\n"
  18430. "Connection: close\r\n"
  18431. "Expect: " +
  18432. expect_value +
  18433. "\r\n"
  18434. "\r\n"
  18435. "hi";
  18436. }
  18437. Server svr_;
  18438. int port_ = 0;
  18439. thread thread_;
  18440. };
  18441. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18442. bool got_100 = false;
  18443. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18444. EXPECT_TRUE(got_100);
  18445. }
  18446. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18447. bool got_100 = true;
  18448. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18449. EXPECT_FALSE(got_100);
  18450. }
  18451. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18452. bool got_100 = false;
  18453. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18454. EXPECT_TRUE(got_100);
  18455. }
  18456. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18457. bool got_100 = false;
  18458. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18459. EXPECT_TRUE(got_100);
  18460. }
  18461. // `100 Continue` is sent only when the server starts reading the body, so a
  18462. // request rejected before that never invites the client to send it. The
  18463. // requests below carry the expectation but withhold the body, as a client
  18464. // waiting for `100 Continue` would.
  18465. // A POST that expects `100 Continue` and withholds its two-byte body.
  18466. static std::string expect_headers_only(const std::string &path) {
  18467. return "POST " + path +
  18468. " HTTP/1.1\r\n"
  18469. "Host: localhost\r\n"
  18470. "Content-Length: 2\r\n"
  18471. "Expect: 100-continue\r\n"
  18472. "\r\n";
  18473. }
  18474. class ExpectLazyContinueTest : public ::testing::Test {
  18475. protected:
  18476. void SetUp() override {
  18477. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18478. if (req.path == "/pre-routing") {
  18479. res.status = StatusCode::Unauthorized_401;
  18480. return Server::HandlerResponse::Handled;
  18481. }
  18482. return Server::HandlerResponse::Unhandled;
  18483. });
  18484. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18485. if (req.matched_route == "/pre-request") {
  18486. res.status = StatusCode::Forbidden_403;
  18487. return Server::HandlerResponse::Handled;
  18488. }
  18489. return Server::HandlerResponse::Unhandled;
  18490. });
  18491. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18492. res.set_content("ok", "text/plain");
  18493. });
  18494. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18495. res.set_content("ok", "text/plain");
  18496. });
  18497. svr_.Post("/reader-used", [](const Request &, Response &res,
  18498. const ContentReader &content_reader) {
  18499. std::string body;
  18500. content_reader([&](const char *data, size_t len) {
  18501. body.append(data, len);
  18502. return true;
  18503. });
  18504. res.set_content(body, "text/plain");
  18505. });
  18506. svr_.Post("/reader-unused",
  18507. [](const Request &, Response &res, const ContentReader &) {
  18508. res.set_content("ignored", "text/plain");
  18509. });
  18510. port_ = svr_.bind_to_any_port(HOST);
  18511. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18512. svr_.wait_until_ready();
  18513. }
  18514. void TearDown() override {
  18515. svr_.stop();
  18516. if (thread_.joinable()) { thread_.join(); }
  18517. }
  18518. // Sends `req` and reads until the server closes the connection. Returns
  18519. // false if the read had to wait for the client-side timeout instead.
  18520. bool send_until_closed(const std::string &req, std::string *resp) const {
  18521. auto start = std::chrono::steady_clock::now();
  18522. if (!send_request(3, req, resp, port_)) { return false; }
  18523. auto elapsed = std::chrono::steady_clock::now() - start;
  18524. return elapsed < std::chrono::seconds(2);
  18525. }
  18526. // The final response comes without `100 Continue`, and the server closes
  18527. // the connection since the body may or may not follow.
  18528. void expect_final_without_interim(const std::string &path,
  18529. const char *status_line) const {
  18530. std::string resp;
  18531. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18532. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18533. EXPECT_EQ(0u, resp.find(status_line));
  18534. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18535. }
  18536. Server svr_;
  18537. int port_ = 0;
  18538. thread thread_;
  18539. };
  18540. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18541. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18542. }
  18543. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18544. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18545. }
  18546. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18547. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18548. }
  18549. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18550. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18551. }
  18552. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18553. // The body follows once `100 Continue` has had time to arrive.
  18554. auto req = expect_headers_only("/reader-used");
  18555. req.insert(req.size() - 2, "Connection: close\r\n");
  18556. std::string resp;
  18557. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18558. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18559. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18560. EXPECT_NE(std::string::npos, resp.find("hi"));
  18561. }
  18562. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18563. // Large enough for the client to add `Expect: 100-continue` itself.
  18564. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18565. std::atomic<bool> body_sent{false};
  18566. Client cli(HOST, port_);
  18567. auto res = cli.Post(
  18568. "/pre-request", length,
  18569. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18570. body_sent = true;
  18571. std::string chunk(len, 'x');
  18572. sink.write(chunk.data(), chunk.size());
  18573. return true;
  18574. },
  18575. "application/octet-stream");
  18576. ASSERT_TRUE(res);
  18577. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18578. EXPECT_FALSE(body_sent);
  18579. }
  18580. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18581. Server svr;
  18582. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18583. return StatusCode::ExpectationFailed_417;
  18584. });
  18585. svr.Post("/p", [](const Request &, Response &res) {
  18586. res.set_content("ok", "text/plain");
  18587. });
  18588. auto port = svr.bind_to_any_port(HOST);
  18589. thread t = thread([&] { svr.listen_after_bind(); });
  18590. auto se = detail::scope_exit([&] {
  18591. svr.stop();
  18592. t.join();
  18593. });
  18594. svr.wait_until_ready();
  18595. std::string resp;
  18596. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18597. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18598. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18599. // Exactly one response: the route handler must not run after the 417.
  18600. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18601. }
  18602. #ifndef _WIN32
  18603. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18604. static constexpr char reject[] = "Unauthorized";
  18605. static constexpr char accept[] = "Upload accepted";
  18606. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18607. Server svr;
  18608. svr.set_expect_100_continue_handler(
  18609. [](const Request & /*req*/, Response &res) {
  18610. res.status = StatusCode::Unauthorized_401;
  18611. res.set_content(reject, "text/plain");
  18612. return res.status;
  18613. });
  18614. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18615. res.set_content(accept, "text/plain");
  18616. });
  18617. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18618. auto se = detail::scope_exit([&] {
  18619. svr.stop();
  18620. thread.join();
  18621. ASSERT_FALSE(svr.is_running());
  18622. });
  18623. svr.wait_until_ready();
  18624. {
  18625. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18626. curl_easy_init(), &curl_easy_cleanup};
  18627. ASSERT_NE(curl, nullptr);
  18628. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18629. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18630. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18631. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18632. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18633. &curl_slist_free_all};
  18634. ASSERT_NE(list, nullptr);
  18635. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18636. struct read_data {
  18637. uint64_t read_size;
  18638. uint64_t total_size;
  18639. } data = {0, total_size};
  18640. using read_callback_t =
  18641. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18642. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18643. void *userdata) -> size_t {
  18644. read_data *d = (read_data *)userdata;
  18645. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18646. std::fill_n(ptr, size * nmemb, 'A');
  18647. d->read_size += size * nmemb;
  18648. return size * nmemb;
  18649. };
  18650. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18651. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18652. std::vector<char> buffer;
  18653. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18654. using write_callback_t =
  18655. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18656. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18657. void *userdata) -> size_t {
  18658. std::vector<char> *buf = (std::vector<char> *)userdata;
  18659. buf->reserve(buf->size() + size * nmemb + 1);
  18660. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18661. return size * nmemb;
  18662. };
  18663. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18664. {
  18665. const auto res = curl_easy_perform(curl.get());
  18666. ASSERT_EQ(res, CURLE_OK);
  18667. }
  18668. {
  18669. auto response_code = long{};
  18670. const auto res =
  18671. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18672. ASSERT_EQ(res, CURLE_OK);
  18673. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18674. }
  18675. {
  18676. auto dl = curl_off_t{};
  18677. const auto res =
  18678. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18679. ASSERT_EQ(res, CURLE_OK);
  18680. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18681. }
  18682. {
  18683. buffer.push_back('\0');
  18684. ASSERT_STRCASEEQ(buffer.data(), reject);
  18685. }
  18686. }
  18687. }
  18688. #endif
  18689. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18690. // Regression test for #2458.
  18691. //
  18692. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18693. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18694. // ticket can make the client socket spuriously readable during the
  18695. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18696. // the client withholds the body and then blocks reading a response that never
  18697. // comes, failing with `Failed to read connection`.
  18698. //
  18699. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18700. // within the timeout. This raw OpenSSL server deliberately never sends
  18701. // `100 Continue`; the client must still deliver the body and receive 200.
  18702. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18703. signal(SIGPIPE, SIG_IGN);
  18704. const auto port = PORT + 4;
  18705. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18706. ASSERT_NE(srv, INVALID_SOCKET);
  18707. int opt = 1;
  18708. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18709. sockaddr_in addr{};
  18710. addr.sin_family = AF_INET;
  18711. addr.sin_port = htons(static_cast<uint16_t>(port));
  18712. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18713. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18714. ASSERT_EQ(0, ::listen(srv, 1));
  18715. std::atomic<size_t> server_body_bytes{0};
  18716. auto server_thread = std::thread([&] {
  18717. sockaddr_in cli_addr{};
  18718. socklen_t cli_len = sizeof(cli_addr);
  18719. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18720. if (cli == INVALID_SOCKET) { return; }
  18721. // Bound the lifetime of the server side so a buggy client (which never
  18722. // sends the body) cannot make this thread block forever on join.
  18723. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18724. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18725. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18726. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18727. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18728. SSL *ssl = SSL_new(ctx);
  18729. SSL_set_fd(ssl, static_cast<int>(cli));
  18730. if (SSL_accept(ssl) > 0) {
  18731. // Read the request headers. Reading here also flushes the TLS 1.3
  18732. // session tickets to the client. Deliberately do NOT send
  18733. // `100 Continue`.
  18734. std::string buf;
  18735. char tmp[1024];
  18736. while (buf.find("\r\n\r\n") == std::string::npos) {
  18737. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18738. if (n <= 0) { break; }
  18739. buf.append(tmp, static_cast<size_t>(n));
  18740. }
  18741. // A correct client sends the body now; count what arrives.
  18742. auto pos = buf.find("\r\n\r\n");
  18743. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18744. while (body < 4096) {
  18745. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18746. if (n <= 0) { break; }
  18747. body += static_cast<size_t>(n);
  18748. }
  18749. server_body_bytes = body;
  18750. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18751. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18752. SSL_shutdown(ssl);
  18753. }
  18754. SSL_free(ssl);
  18755. detail::close_socket(cli);
  18756. SSL_CTX_free(ctx);
  18757. });
  18758. auto se = detail::scope_exit([&] {
  18759. server_thread.join();
  18760. detail::close_socket(srv);
  18761. });
  18762. SSLClient cli("127.0.0.1", port);
  18763. cli.enable_server_certificate_verification(false);
  18764. cli.set_connection_timeout(5, 0);
  18765. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18766. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18767. std::string body(4096, 'A');
  18768. auto res = cli.Put("/api/test", body, "application/json");
  18769. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18770. EXPECT_EQ(StatusCode::OK_200, res->status);
  18771. EXPECT_EQ(body.size(), server_body_bytes.load());
  18772. }
  18773. #endif
  18774. template <typename S, typename C>
  18775. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18776. svr.Get("/stream", [&](const Request &, Response &res) {
  18777. auto data = new std::string("01234567890123456789");
  18778. res.set_content_provider(
  18779. data->size(), "text/plain",
  18780. [&, data](size_t offset, size_t length, DataSink &sink) {
  18781. const size_t DATA_CHUNK_SIZE = 4;
  18782. const auto &d = *data;
  18783. std::this_thread::sleep_for(std::chrono::seconds(1));
  18784. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18785. return true;
  18786. },
  18787. [data](bool success) {
  18788. EXPECT_FALSE(success);
  18789. delete data;
  18790. });
  18791. });
  18792. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18793. auto i = new size_t(0);
  18794. res.set_content_provider(
  18795. "text/plain",
  18796. [i](size_t, DataSink &sink) {
  18797. if (*i < 5) {
  18798. std::this_thread::sleep_for(std::chrono::seconds(1));
  18799. sink.write("abcd", 4);
  18800. (*i)++;
  18801. } else {
  18802. sink.done();
  18803. }
  18804. return true;
  18805. },
  18806. [i](bool success) {
  18807. EXPECT_FALSE(success);
  18808. delete i;
  18809. });
  18810. });
  18811. svr.Get("/chunked", [&](const Request &, Response &res) {
  18812. auto i = new size_t(0);
  18813. res.set_chunked_content_provider(
  18814. "text/plain",
  18815. [i](size_t, DataSink &sink) {
  18816. if (*i < 5) {
  18817. std::this_thread::sleep_for(std::chrono::seconds(1));
  18818. sink.os << "abcd";
  18819. (*i)++;
  18820. } else {
  18821. sink.done();
  18822. }
  18823. return true;
  18824. },
  18825. [i](bool success) {
  18826. EXPECT_FALSE(success);
  18827. delete i;
  18828. });
  18829. });
  18830. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18831. auto se = detail::scope_exit([&] {
  18832. svr.stop();
  18833. listen_thread.join();
  18834. ASSERT_FALSE(svr.is_running());
  18835. });
  18836. svr.wait_until_ready();
  18837. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18838. {
  18839. auto start = std::chrono::steady_clock::now();
  18840. auto res = cli.Get("/stream");
  18841. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18842. std::chrono::steady_clock::now() - start)
  18843. .count();
  18844. ASSERT_FALSE(res);
  18845. EXPECT_EQ(Error::Read, res.error());
  18846. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18847. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18848. }
  18849. {
  18850. auto start = std::chrono::steady_clock::now();
  18851. auto res = cli.Get("/stream_without_length");
  18852. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18853. std::chrono::steady_clock::now() - start)
  18854. .count();
  18855. ASSERT_FALSE(res);
  18856. EXPECT_EQ(Error::Read, res.error());
  18857. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18858. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18859. }
  18860. {
  18861. auto start = std::chrono::steady_clock::now();
  18862. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18863. EXPECT_EQ("abcd", string(data, data_length));
  18864. return true;
  18865. });
  18866. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18867. std::chrono::steady_clock::now() - start)
  18868. .count();
  18869. ASSERT_FALSE(res);
  18870. EXPECT_EQ(Error::Read, res.error());
  18871. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18872. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18873. }
  18874. }
  18875. TEST(MaxTimeoutTest, ContentStream) {
  18876. time_t timeout = 2000;
  18877. time_t threshold = 200;
  18878. Server svr;
  18879. Client cli("localhost", PORT);
  18880. max_timeout_test(svr, cli, timeout, threshold);
  18881. }
  18882. #ifdef CPPHTTPLIB_SSL_ENABLED
  18883. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18884. time_t timeout = 2000;
  18885. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18886. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18887. SSLClient cli("localhost", PORT);
  18888. cli.enable_server_certificate_verification(false);
  18889. max_timeout_test(svr, cli, timeout, threshold);
  18890. }
  18891. #endif
  18892. class EventDispatcher {
  18893. public:
  18894. EventDispatcher() {}
  18895. bool wait_event(DataSink *sink) {
  18896. unique_lock<mutex> lk(m_);
  18897. int id = id_;
  18898. // Wait with timeout to prevent hanging if client disconnects
  18899. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18900. [&] { return cid_ == id; })) {
  18901. return false; // Timeout occurred
  18902. }
  18903. sink->write(message_.data(), message_.size());
  18904. return true;
  18905. }
  18906. void send_event(const string &message) {
  18907. lock_guard<mutex> lk(m_);
  18908. cid_ = id_++;
  18909. message_ = message;
  18910. cv_.notify_all();
  18911. }
  18912. private:
  18913. mutex m_;
  18914. condition_variable cv_;
  18915. atomic_int id_{0};
  18916. atomic_int cid_{-1};
  18917. string message_;
  18918. };
  18919. TEST(ClientInThreadTest, Issue2068) {
  18920. EventDispatcher ed;
  18921. Server svr;
  18922. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18923. res.set_chunked_content_provider("text/event-stream",
  18924. [&](size_t /*offset*/, DataSink &sink) {
  18925. return ed.wait_event(&sink);
  18926. });
  18927. });
  18928. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18929. svr.wait_until_ready();
  18930. thread event_thread([&] {
  18931. int id = 0;
  18932. while (svr.is_running()) {
  18933. this_thread::sleep_for(chrono::milliseconds(500));
  18934. std::stringstream ss;
  18935. ss << "data: " << id << "\n\n";
  18936. ed.send_event(ss.str());
  18937. id++;
  18938. }
  18939. });
  18940. auto se = detail::scope_exit([&] {
  18941. svr.stop();
  18942. listen_thread.join();
  18943. event_thread.join();
  18944. ASSERT_FALSE(svr.is_running());
  18945. });
  18946. {
  18947. auto client = detail::make_unique<Client>(HOST, PORT);
  18948. client->set_read_timeout(std::chrono::minutes(10));
  18949. std::atomic<bool> stop{false};
  18950. std::thread t([&] {
  18951. client->Get("/event1",
  18952. [&](const char *, size_t) -> bool { return !stop; });
  18953. });
  18954. std::this_thread::sleep_for(std::chrono::seconds(2));
  18955. stop = true;
  18956. client->stop();
  18957. t.join();
  18958. // Reset client after thread has finished
  18959. client.reset();
  18960. }
  18961. }
  18962. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18963. auto handled = false;
  18964. Server svr;
  18965. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18966. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18967. auto se = detail::scope_exit([&] {
  18968. svr.stop();
  18969. t.join();
  18970. ASSERT_FALSE(svr.is_running());
  18971. ASSERT_FALSE(handled);
  18972. });
  18973. svr.wait_until_ready();
  18974. // Two Content-Length headers with different values — must be rejected
  18975. auto req = "POST /test HTTP/1.1\r\n"
  18976. "Content-Length: 5\r\n"
  18977. "Content-Length: 10\r\n"
  18978. "\r\n"
  18979. "hello";
  18980. std::string response;
  18981. ASSERT_TRUE(send_request(1, req, &response));
  18982. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18983. response.substr(0, response.find("\r\n")));
  18984. }
  18985. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18986. auto handled = false;
  18987. Server svr;
  18988. svr.Post("/test", [&](const Request &, Response &res) {
  18989. handled = true;
  18990. res.set_content("ok", "text/plain");
  18991. });
  18992. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18993. auto se = detail::scope_exit([&] {
  18994. svr.stop();
  18995. t.join();
  18996. ASSERT_FALSE(svr.is_running());
  18997. ASSERT_TRUE(handled);
  18998. });
  18999. svr.wait_until_ready();
  19000. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19001. auto req = "POST /test HTTP/1.1\r\n"
  19002. "Host: localhost\r\n"
  19003. "Content-Length: 5\r\n"
  19004. "Content-Length: 5\r\n"
  19005. "\r\n"
  19006. "hello";
  19007. std::string response;
  19008. ASSERT_TRUE(send_request(1, req, &response));
  19009. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19010. }
  19011. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19012. Server svr;
  19013. svr.Get("/test", [](const Request &, Response &res) {
  19014. res.set_content("ok", "text/plain");
  19015. });
  19016. auto port = svr.bind_to_any_port(HOST);
  19017. thread t = thread([&] { svr.listen_after_bind(); });
  19018. auto se = detail::scope_exit([&] {
  19019. svr.stop();
  19020. t.join();
  19021. ASSERT_FALSE(svr.is_running());
  19022. });
  19023. svr.wait_until_ready();
  19024. auto status_line = [&](const std::string &host_lines) {
  19025. std::string res;
  19026. send_request(
  19027. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19028. &res, port);
  19029. return res.substr(0, res.find("\r\n"));
  19030. };
  19031. const char *accepted[] = {
  19032. "Host: localhost\r\n",
  19033. "Host: a.example:8080\r\n",
  19034. "Host: my_service\r\n",
  19035. "Host: [::1]:8080\r\n",
  19036. "Host: [fe80::1%25eth0]\r\n",
  19037. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19038. };
  19039. for (auto host_lines : accepted) {
  19040. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19041. }
  19042. const char *rejected[] = {
  19043. "Host: a.example\r\nHost: b.example\r\n",
  19044. "Host: a.example\r\nHost: a.example\r\n",
  19045. "Host: a@b.example\r\n",
  19046. "Host: a.example/b\r\n",
  19047. "Host: a.example\\b\r\n",
  19048. "Host: a.example?b\r\n",
  19049. "Host: a.example#b\r\n",
  19050. "Host: a.example b.example\r\n",
  19051. };
  19052. for (auto host_lines : rejected) {
  19053. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19054. << host_lines;
  19055. }
  19056. }
  19057. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19058. Server svr;
  19059. svr.Get("/", [](const Request &req, Response &res) {
  19060. EXPECT_EQ(2U, req.trailers.size());
  19061. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19062. // Denied
  19063. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19064. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19065. // Accepted
  19066. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19067. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19068. EXPECT_TRUE(req.has_trailer("X-World"));
  19069. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19070. res.set_content("ok", "text/plain");
  19071. });
  19072. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19073. auto se = detail::scope_exit([&] {
  19074. svr.stop();
  19075. t.join();
  19076. ASSERT_FALSE(svr.is_running());
  19077. });
  19078. svr.wait_until_ready();
  19079. const std::string req = "GET / HTTP/1.1\r\n"
  19080. "Transfer-Encoding: chunked\r\n"
  19081. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19082. "\r\n"
  19083. "0\r\n"
  19084. "Content-Length: 10\r\n"
  19085. "Host: internal.local\r\n"
  19086. "Content-Type: malicious/content\r\n"
  19087. "Cookie: any\r\n"
  19088. "Set-Cookie: any\r\n"
  19089. "X-Forwarded-For: attacker.com\r\n"
  19090. "X-Real-Ip: 1.1.1.1\r\n"
  19091. "X-Hello: hello\r\n"
  19092. "X-World: world\r\n"
  19093. "\r\n";
  19094. std::string res;
  19095. ASSERT_TRUE(send_request(1, req, &res));
  19096. }
  19097. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19098. // several field lines, and the combined value is what has to be parsed. A
  19099. // Trailer field split across lines therefore declares every name it lists;
  19100. // reading only the first line silently drops the trailers the later lines
  19101. // declare. The prohibited-trailer filter still applies to every line.
  19102. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19103. Server svr;
  19104. size_t observed_trailer_count = 0;
  19105. std::string observed_hello;
  19106. std::string observed_world;
  19107. bool observed_content_length = true;
  19108. svr.Get("/", [&](const Request &req, Response &res) {
  19109. observed_trailer_count = req.trailers.size();
  19110. observed_hello = req.get_trailer_value("X-Hello");
  19111. observed_world = req.get_trailer_value("X-World");
  19112. observed_content_length = req.has_trailer("Content-Length");
  19113. res.set_content("ok", "text/plain");
  19114. });
  19115. auto port = svr.bind_to_any_port(HOST);
  19116. thread t = thread([&]() { svr.listen_after_bind(); });
  19117. auto se = detail::scope_exit([&] {
  19118. svr.stop();
  19119. t.join();
  19120. ASSERT_FALSE(svr.is_running());
  19121. });
  19122. svr.wait_until_ready();
  19123. const std::string req = "GET / HTTP/1.1\r\n"
  19124. "Host: localhost\r\n"
  19125. "Transfer-Encoding: chunked\r\n"
  19126. "Trailer: X-Hello\r\n"
  19127. "Trailer: X-World, Content-Length\r\n"
  19128. "\r\n"
  19129. "0\r\n"
  19130. "X-Hello: hello\r\n"
  19131. "X-World: world\r\n"
  19132. "Content-Length: 10\r\n"
  19133. "\r\n";
  19134. std::string res;
  19135. ASSERT_TRUE(send_request(1, req, &res, port));
  19136. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19137. // Accepted: both field lines contribute to the declared set
  19138. EXPECT_EQ(2U, observed_trailer_count);
  19139. EXPECT_EQ(observed_hello, "hello");
  19140. EXPECT_EQ(observed_world, "world");
  19141. // Denied: a prohibited name stays prohibited on a later field line
  19142. EXPECT_FALSE(observed_content_length);
  19143. }
  19144. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19145. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19146. // unbounded run of fields that are never declared, because the counter would
  19147. // only advance for declared fields.
  19148. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19149. Server svr;
  19150. bool handler_called = false;
  19151. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19152. handler_called = true;
  19153. res.set_content("ok", "text/plain");
  19154. });
  19155. auto port = svr.bind_to_any_port(HOST);
  19156. thread t = thread([&]() { svr.listen_after_bind(); });
  19157. auto se = detail::scope_exit([&] {
  19158. svr.stop();
  19159. t.join();
  19160. ASSERT_FALSE(svr.is_running());
  19161. });
  19162. svr.wait_until_ready();
  19163. // Declare nothing, then send far more undeclared trailer fields than the
  19164. // header-count limit. Parsing must stop and reject the request rather than
  19165. // read every line.
  19166. std::string req = "GET / HTTP/1.1\r\n"
  19167. "Transfer-Encoding: chunked\r\n"
  19168. "\r\n"
  19169. "0\r\n";
  19170. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19171. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19172. }
  19173. req += "\r\n";
  19174. std::string res;
  19175. ASSERT_TRUE(send_request(1, req, &res, port));
  19176. // The request is rejected before the handler runs.
  19177. EXPECT_FALSE(handler_called);
  19178. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19179. }
  19180. // The set of declared trailer names is capped so a peer cannot grow it without
  19181. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19182. // declared past the cap is not honored, even if the field is actually sent.
  19183. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19184. Server svr;
  19185. // One name inside the cap and one past it, so the test tracks the cap rather
  19186. // than a fixed count.
  19187. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19188. const std::string within_cap_name = "X-T-0";
  19189. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19190. bool observed_within_cap = false;
  19191. bool observed_past_cap = false;
  19192. svr.Get("/", [&](const Request &req, Response &res) {
  19193. observed_within_cap = req.has_trailer(within_cap_name);
  19194. observed_past_cap = req.has_trailer(past_cap_name);
  19195. res.set_content("ok", "text/plain");
  19196. });
  19197. auto port = svr.bind_to_any_port(HOST);
  19198. thread t = thread([&]() { svr.listen_after_bind(); });
  19199. auto se = detail::scope_exit([&] {
  19200. svr.stop();
  19201. t.join();
  19202. ASSERT_FALSE(svr.is_running());
  19203. });
  19204. svr.wait_until_ready();
  19205. // Declare more trailer names than the cap in a single Trailer field, then
  19206. // actually send the first (within the cap) and the last (past it).
  19207. std::string trailer_decl = "Trailer: ";
  19208. for (int i = 0; i < declared_count; i++) {
  19209. if (i != 0) { trailer_decl += ", "; }
  19210. trailer_decl += "X-T-" + std::to_string(i);
  19211. }
  19212. trailer_decl += "\r\n";
  19213. const std::string req = "GET / HTTP/1.1\r\n"
  19214. "Host: localhost\r\n"
  19215. "Transfer-Encoding: chunked\r\n" +
  19216. trailer_decl +
  19217. "\r\n"
  19218. "0\r\n" +
  19219. within_cap_name + ": a\r\n" + past_cap_name +
  19220. ": b\r\n"
  19221. "\r\n";
  19222. std::string res;
  19223. ASSERT_TRUE(send_request(1, req, &res, port));
  19224. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19225. // A name within the cap is honored; one declared past the cap is dropped.
  19226. EXPECT_TRUE(observed_within_cap);
  19227. EXPECT_FALSE(observed_past_cap);
  19228. }
  19229. // A direct client that is not listed in trusted_proxies must not be able to
  19230. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19231. // the peer address on the actual TCP connection determines whether the
  19232. // header is honored.
  19233. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19234. Server svr;
  19235. // Deliberately does NOT include the loopback address the test client
  19236. // actually connects from, so the direct connection is not a trusted proxy.
  19237. svr.set_trusted_proxies({"203.0.113.66"});
  19238. std::string observed_remote_addr;
  19239. svr.Get("/ip", [&](const Request &req, Response &res) {
  19240. observed_remote_addr = req.remote_addr;
  19241. res.set_content("ok", "text/plain");
  19242. });
  19243. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19244. auto se = detail::scope_exit([&] {
  19245. svr.stop();
  19246. t.join();
  19247. ASSERT_FALSE(svr.is_running());
  19248. });
  19249. svr.wait_until_ready();
  19250. Client cli(HOST, PORT);
  19251. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19253. EXPECT_EQ(StatusCode::OK_200, res->status);
  19254. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19255. // ignored entirely and the real connection-level address retained.
  19256. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19257. observed_remote_addr == "127.0.0.1");
  19258. }
  19259. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19260. Server svr;
  19261. std::string observed_remote_addr;
  19262. std::string observed_xff;
  19263. svr.Get("/ip", [&](const Request &req, Response &res) {
  19264. observed_remote_addr = req.remote_addr;
  19265. observed_xff = req.get_header_value("X-Forwarded-For");
  19266. res.set_content("ok", "text/plain");
  19267. });
  19268. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19269. auto se = detail::scope_exit([&] {
  19270. svr.stop();
  19271. t.join();
  19272. ASSERT_FALSE(svr.is_running());
  19273. });
  19274. svr.wait_until_ready();
  19275. Client cli(HOST, PORT);
  19276. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19278. EXPECT_EQ(StatusCode::OK_200, res->status);
  19279. EXPECT_EQ(observed_xff, "203.0.113.66");
  19280. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19281. observed_remote_addr == "127.0.0.1");
  19282. }
  19283. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19284. Server svr;
  19285. svr.set_trusted_proxies({"203.0.113.66"});
  19286. std::string observed_remote_addr;
  19287. std::string observed_xff;
  19288. svr.Get("/ip", [&](const Request &req, Response &res) {
  19289. observed_remote_addr = req.remote_addr;
  19290. observed_xff = req.get_header_value("X-Forwarded-For");
  19291. res.set_content("ok", "text/plain");
  19292. });
  19293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19294. auto se = detail::scope_exit([&] {
  19295. svr.stop();
  19296. t.join();
  19297. ASSERT_FALSE(svr.is_running());
  19298. });
  19299. svr.wait_until_ready();
  19300. Client cli(HOST, PORT);
  19301. auto res = cli.Get("/ip");
  19302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19303. EXPECT_EQ(StatusCode::OK_200, res->status);
  19304. EXPECT_EQ(observed_xff, "");
  19305. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19306. observed_remote_addr == "127.0.0.1");
  19307. }
  19308. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19309. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19310. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19311. Server svr;
  19312. svr.set_trusted_proxies({"127.0.0.1"});
  19313. svr.Get("/ip", [](const Request &req, Response &res) {
  19314. res.set_content(req.remote_addr, "text/plain");
  19315. });
  19316. auto port = svr.bind_to_any_port("::");
  19317. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19318. thread t = thread([&] { svr.listen_after_bind(); });
  19319. auto se = detail::scope_exit([&] {
  19320. svr.stop();
  19321. t.join();
  19322. ASSERT_FALSE(svr.is_running());
  19323. });
  19324. svr.wait_until_ready();
  19325. Client cli("127.0.0.1", port);
  19326. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19328. EXPECT_EQ("198.51.100.23", res->body);
  19329. }
  19330. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19331. Server svr;
  19332. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19333. svr.Get("/ip", [](const Request &req, Response &res) {
  19334. res.set_content(req.remote_addr, "text/plain");
  19335. });
  19336. auto port = svr.bind_to_any_port(HOST);
  19337. ASSERT_GT(port, 0);
  19338. thread t = thread([&] { svr.listen_after_bind(); });
  19339. auto se = detail::scope_exit([&] {
  19340. svr.stop();
  19341. t.join();
  19342. ASSERT_FALSE(svr.is_running());
  19343. });
  19344. svr.wait_until_ready();
  19345. Client cli(HOST, port);
  19346. auto res = cli.Get(
  19347. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19349. EXPECT_EQ("198.51.100.23", res->body);
  19350. }
  19351. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19352. Server svr;
  19353. // Include the loopback address the test client actually connects from, so
  19354. // the direct connection itself is recognized as the trusted proxy hop.
  19355. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19356. std::string observed_remote_addr;
  19357. std::string observed_xff;
  19358. svr.Get("/ip", [&](const Request &req, Response &res) {
  19359. observed_remote_addr = req.remote_addr;
  19360. observed_xff = req.get_header_value("X-Forwarded-For");
  19361. res.set_content("ok", "text/plain");
  19362. });
  19363. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19364. auto se = detail::scope_exit([&] {
  19365. svr.stop();
  19366. t.join();
  19367. ASSERT_FALSE(svr.is_running());
  19368. });
  19369. svr.wait_until_ready();
  19370. Client cli(HOST, PORT);
  19371. auto res = cli.Get(
  19372. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19374. EXPECT_EQ(StatusCode::OK_200, res->status);
  19375. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19376. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19377. }
  19378. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19379. Server svr;
  19380. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19381. std::string observed_remote_addr;
  19382. std::string observed_xff;
  19383. svr.Get("/ip", [&](const Request &req, Response &res) {
  19384. observed_remote_addr = req.remote_addr;
  19385. observed_xff = req.get_header_value("X-Forwarded-For");
  19386. res.set_content("ok", "text/plain");
  19387. });
  19388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19389. auto se = detail::scope_exit([&] {
  19390. svr.stop();
  19391. t.join();
  19392. ASSERT_FALSE(svr.is_running());
  19393. });
  19394. svr.wait_until_ready();
  19395. Client cli(HOST, PORT);
  19396. auto res = cli.Get(
  19397. "/ip",
  19398. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19400. EXPECT_EQ(StatusCode::OK_200, res->status);
  19401. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19402. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19403. }
  19404. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19405. Server svr;
  19406. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19407. std::string observed_remote_addr;
  19408. std::string observed_xff;
  19409. svr.Get("/ip", [&](const Request &req, Response &res) {
  19410. observed_remote_addr = req.remote_addr;
  19411. observed_xff = req.get_header_value("X-Forwarded-For");
  19412. res.set_content("ok", "text/plain");
  19413. });
  19414. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19415. auto se = detail::scope_exit([&] {
  19416. svr.stop();
  19417. t.join();
  19418. ASSERT_FALSE(svr.is_running());
  19419. });
  19420. svr.wait_until_ready();
  19421. Client cli(HOST, PORT);
  19422. auto res = cli.Get(
  19423. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19425. EXPECT_EQ(StatusCode::OK_200, res->status);
  19426. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19427. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19428. // and must not be selected.
  19429. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19430. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19431. }
  19432. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19433. Server svr;
  19434. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19435. std::string observed_remote_addr;
  19436. svr.Get("/ip", [&](const Request &req, Response &res) {
  19437. observed_remote_addr = req.remote_addr;
  19438. res.set_content("ok", "text/plain");
  19439. });
  19440. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19441. auto se = detail::scope_exit([&] {
  19442. svr.stop();
  19443. t.join();
  19444. ASSERT_FALSE(svr.is_running());
  19445. });
  19446. svr.wait_until_ready();
  19447. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19448. // a forged address and the trusted proxy's own address; the forged value must
  19449. // not win over the address the trusted proxy actually recorded.
  19450. Client cli(HOST, PORT);
  19451. auto res = cli.Get(
  19452. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19454. EXPECT_EQ(StatusCode::OK_200, res->status);
  19455. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19456. }
  19457. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19458. Server svr;
  19459. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19460. std::string observed_remote_addr;
  19461. std::string observed_xff;
  19462. svr.Get("/ip", [&](const Request &req, Response &res) {
  19463. observed_remote_addr = req.remote_addr;
  19464. observed_xff = req.get_header_value("X-Forwarded-For");
  19465. res.set_content("ok", "text/plain");
  19466. });
  19467. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19468. auto se = detail::scope_exit([&] {
  19469. svr.stop();
  19470. t.join();
  19471. ASSERT_FALSE(svr.is_running());
  19472. });
  19473. svr.wait_until_ready();
  19474. Client cli(HOST, PORT);
  19475. auto res = cli.Get(
  19476. "/ip",
  19477. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19479. EXPECT_EQ(StatusCode::OK_200, res->status);
  19480. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19481. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19482. }
  19483. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19484. Server svr;
  19485. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19486. std::string observed_remote_addr;
  19487. std::string observed_xff;
  19488. svr.Get("/ip", [&](const Request &req, Response &res) {
  19489. observed_remote_addr = req.remote_addr;
  19490. observed_xff = req.get_header_value("X-Forwarded-For");
  19491. res.set_content("ok", "text/plain");
  19492. });
  19493. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19494. auto se = detail::scope_exit([&] {
  19495. svr.stop();
  19496. t.join();
  19497. ASSERT_FALSE(svr.is_running());
  19498. });
  19499. svr.wait_until_ready();
  19500. std::string raw_req =
  19501. "GET /ip HTTP/1.1\r\n"
  19502. "Host: localhost\r\n"
  19503. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19504. "Connection: close\r\n"
  19505. "\r\n";
  19506. std::string out;
  19507. ASSERT_TRUE(send_request(5, raw_req, &out));
  19508. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19509. // Header parser trims surrounding whitespace of the header value
  19510. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19511. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19512. }
  19513. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19514. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19515. // their own X-Forwarded-For as a separate field line rather than extending the
  19516. // one the client sent, so every occurrence has to be taken into account.
  19517. // Reading only the first one hands back the address the client chose.
  19518. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19519. Server svr;
  19520. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19521. std::string observed_remote_addr;
  19522. size_t observed_xff_count = 0;
  19523. svr.Get("/ip", [&](const Request &req, Response &res) {
  19524. observed_remote_addr = req.remote_addr;
  19525. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19526. res.set_content("ok", "text/plain");
  19527. });
  19528. auto port = svr.bind_to_any_port(HOST);
  19529. thread t = thread([&]() { svr.listen_after_bind(); });
  19530. auto se = detail::scope_exit([&] {
  19531. svr.stop();
  19532. t.join();
  19533. ASSERT_FALSE(svr.is_running());
  19534. });
  19535. svr.wait_until_ready();
  19536. // The client supplies the first field line; the trusted proxy appends the
  19537. // address it observed as a second one.
  19538. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19539. "Host: localhost\r\n"
  19540. "X-Forwarded-For: 1.2.3.4\r\n"
  19541. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19542. "Connection: close\r\n"
  19543. "\r\n";
  19544. std::string out;
  19545. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19546. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19547. EXPECT_EQ(observed_xff_count, 2U);
  19548. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19549. // The same chain spread over one field line per hop derives the same client
  19550. // address, i.e. the split and the comma-joined representations agree.
  19551. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19552. "Host: localhost\r\n"
  19553. "X-Forwarded-For: 1.2.3.4\r\n"
  19554. "X-Forwarded-For: 198.51.100.23\r\n"
  19555. "X-Forwarded-For: 192.0.2.45\r\n"
  19556. "Connection: close\r\n"
  19557. "\r\n";
  19558. out.clear();
  19559. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19560. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19561. EXPECT_EQ(observed_xff_count, 3U);
  19562. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19563. }
  19564. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19565. // crash the server (it used to call front() on an empty vector inside
  19566. // get_client_ip). The connection-level remote address must be retained instead.
  19567. static void run_malformed_xff_test(const std::string &xff_value) {
  19568. Server svr;
  19569. svr.set_trusted_proxies({"192.0.2.45"});
  19570. std::string observed_remote_addr;
  19571. svr.Get("/ip", [&](const Request &req, Response &res) {
  19572. observed_remote_addr = req.remote_addr;
  19573. res.set_content("ok", "text/plain");
  19574. });
  19575. int port = 0;
  19576. thread t = thread([&]() {
  19577. port = svr.bind_to_any_port(HOST);
  19578. svr.listen_after_bind();
  19579. });
  19580. auto se = detail::scope_exit([&] {
  19581. svr.stop();
  19582. t.join();
  19583. ASSERT_FALSE(svr.is_running());
  19584. });
  19585. svr.wait_until_ready();
  19586. Client cli(HOST, port);
  19587. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19589. EXPECT_EQ(StatusCode::OK_200, res->status);
  19590. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19591. observed_remote_addr == "127.0.0.1");
  19592. }
  19593. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19594. run_malformed_xff_test("");
  19595. }
  19596. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19597. run_malformed_xff_test(",");
  19598. }
  19599. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19600. run_malformed_xff_test(", , ,");
  19601. }
  19602. // The same rule applies to Accept: a request whose acceptable types are spread
  19603. // over several field lines must be negotiated against all of them.
  19604. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19605. // case-insensitive connection options. Comparing the whole field value against
  19606. // one option misses a client that sends several of them, and misses every
  19607. // casing but the one written in the comparison.
  19608. //
  19609. // Sends req, reads the response, then reuses the same socket for a second
  19610. // request to find out whether the server kept the connection.
  19611. static void probe_connection_reuse(int port, const std::string &req,
  19612. bool *announced_close, bool *reusable) {
  19613. auto error = Error::Success;
  19614. auto sock = detail::create_client_socket(
  19615. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19616. /*connection_timeout_sec=*/5, 0,
  19617. /*read_timeout_sec=*/1, 0,
  19618. /*write_timeout_sec=*/5, 0, std::string(), error);
  19619. ASSERT_NE(sock, INVALID_SOCKET);
  19620. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19621. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19622. "Host: localhost\r\n"
  19623. "Connection: close\r\n"
  19624. "\r\n";
  19625. std::string first_response;
  19626. std::string second_response;
  19627. detail::process_client_socket(
  19628. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19629. [&](Stream &strm) {
  19630. if (strm.write(req.data(), req.size()) !=
  19631. static_cast<ssize_t>(req.size())) {
  19632. return false;
  19633. }
  19634. char buf[512];
  19635. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19636. // Headers plus the two-byte body of the handler below
  19637. while (reader.getline()) {
  19638. first_response += reader.ptr();
  19639. if (first_response.find("ok") != std::string::npos) { break; }
  19640. }
  19641. if (strm.write(second.data(), second.size()) !=
  19642. static_cast<ssize_t>(second.size())) {
  19643. return true;
  19644. }
  19645. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19646. while (reader2.getline()) {
  19647. second_response += reader2.ptr();
  19648. if (second_response.find("ok") != std::string::npos) { break; }
  19649. }
  19650. return true;
  19651. });
  19652. *announced_close =
  19653. first_response.find("Connection: close") != std::string::npos;
  19654. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19655. }
  19656. class ConnectionTokenTest : public ::testing::Test {
  19657. protected:
  19658. void SetUp() override {
  19659. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19660. res.set_content("ok", "text/plain");
  19661. });
  19662. port_ = svr_.bind_to_any_port(HOST);
  19663. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19664. svr_.wait_until_ready();
  19665. }
  19666. void TearDown() override {
  19667. svr_.stop();
  19668. if (thread_.joinable()) { thread_.join(); }
  19669. }
  19670. Server svr_;
  19671. int port_ = 0;
  19672. thread thread_;
  19673. };
  19674. // "close" alongside another option still closes the connection, and the
  19675. // response says so rather than leaving the peer to discover it.
  19676. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19677. bool announced_close = false;
  19678. bool reusable = true;
  19679. probe_connection_reuse(port_,
  19680. "GET /keepalive HTTP/1.1\r\n"
  19681. "Host: localhost\r\n"
  19682. "Connection: keep-alive, close\r\n"
  19683. "\r\n",
  19684. &announced_close, &reusable);
  19685. EXPECT_TRUE(announced_close);
  19686. EXPECT_FALSE(reusable);
  19687. }
  19688. // "close" split over two field lines is the same list, so it is honored too.
  19689. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19690. bool announced_close = false;
  19691. bool reusable = true;
  19692. probe_connection_reuse(port_,
  19693. "GET /keepalive HTTP/1.1\r\n"
  19694. "Host: localhost\r\n"
  19695. "Connection: keep-alive\r\n"
  19696. "Connection: close\r\n"
  19697. "\r\n",
  19698. &announced_close, &reusable);
  19699. EXPECT_TRUE(announced_close);
  19700. EXPECT_FALSE(reusable);
  19701. }
  19702. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19703. // keep-alive in the spelling everyone actually sends keeps its connection.
  19704. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19705. bool announced_close = false;
  19706. bool reusable = false;
  19707. probe_connection_reuse(port_,
  19708. "GET /keepalive HTTP/1.0\r\n"
  19709. "Host: localhost\r\n"
  19710. "Connection: keep-alive\r\n"
  19711. "\r\n",
  19712. &announced_close, &reusable);
  19713. EXPECT_FALSE(announced_close);
  19714. EXPECT_TRUE(reusable);
  19715. }
  19716. // A token the value merely contains is not the token itself.
  19717. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19718. bool announced_close = false;
  19719. bool reusable = false;
  19720. probe_connection_reuse(port_,
  19721. "GET /keepalive HTTP/1.1\r\n"
  19722. "Host: localhost\r\n"
  19723. "Connection: notclose\r\n"
  19724. "\r\n",
  19725. &announced_close, &reusable);
  19726. EXPECT_FALSE(announced_close);
  19727. EXPECT_TRUE(reusable);
  19728. }
  19729. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19730. Server svr;
  19731. std::vector<std::string> observed_types;
  19732. svr.Get("/", [&](const Request &req, Response &res) {
  19733. observed_types = req.accept_content_types;
  19734. res.set_content("ok", "text/plain");
  19735. });
  19736. auto port = svr.bind_to_any_port(HOST);
  19737. thread t = thread([&]() { svr.listen_after_bind(); });
  19738. auto se = detail::scope_exit([&] {
  19739. svr.stop();
  19740. t.join();
  19741. ASSERT_FALSE(svr.is_running());
  19742. });
  19743. svr.wait_until_ready();
  19744. Client cli(HOST, port);
  19745. Headers headers;
  19746. headers.emplace("Accept", "text/plain;q=0.5");
  19747. headers.emplace("Accept", "application/json");
  19748. auto res = cli.Get("/", headers);
  19749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19750. EXPECT_EQ(StatusCode::OK_200, res->status);
  19751. // Sorted by q-value, so the second field line's type comes first
  19752. ASSERT_EQ(2U, observed_types.size());
  19753. EXPECT_EQ("application/json", observed_types[0]);
  19754. EXPECT_EQ("text/plain", observed_types[1]);
  19755. }
  19756. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19757. // empty field line must not contribute a bare comma to the combined value.
  19758. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19759. Server svr;
  19760. std::vector<std::string> observed_types;
  19761. svr.Get("/", [&](const Request &req, Response &res) {
  19762. observed_types = req.accept_content_types;
  19763. res.set_content("ok", "text/plain");
  19764. });
  19765. auto port = svr.bind_to_any_port(HOST);
  19766. thread t = thread([&]() { svr.listen_after_bind(); });
  19767. auto se = detail::scope_exit([&] {
  19768. svr.stop();
  19769. t.join();
  19770. ASSERT_FALSE(svr.is_running());
  19771. });
  19772. svr.wait_until_ready();
  19773. // Empty first field line, then a real one
  19774. std::string raw_req = "GET / HTTP/1.1\r\n"
  19775. "Host: localhost\r\n"
  19776. "Accept:\r\n"
  19777. "Accept: application/json\r\n"
  19778. "Connection: close\r\n"
  19779. "\r\n";
  19780. std::string out;
  19781. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19782. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19783. ASSERT_EQ(1U, observed_types.size());
  19784. EXPECT_EQ("application/json", observed_types[0]);
  19785. }
  19786. // The skip in get_combined_header_value() is what keeps an empty field line
  19787. // from contributing a bare comma. Only a trailing empty field line exercises
  19788. // it: a leading one is already covered by the "combined is still empty" check,
  19789. // and parse_accept_header() now ignores the empty element either way, so the
  19790. // request-level test above can no longer tell the two apart.
  19791. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19792. Headers headers;
  19793. headers.emplace("Accept", "text/html");
  19794. headers.emplace("Accept", "");
  19795. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19796. headers.clear();
  19797. headers.emplace("Accept", "");
  19798. headers.emplace("Accept", "application/json");
  19799. EXPECT_EQ("application/json",
  19800. detail::get_combined_header_value(headers, "Accept"));
  19801. }
  19802. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19803. // An encoding offered on a later Accept-Encoding field line is still offered.
  19804. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19805. Server svr;
  19806. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19807. res.set_content(std::string(1024, 'x'), "text/plain");
  19808. });
  19809. auto port = svr.bind_to_any_port(HOST);
  19810. thread t = thread([&]() { svr.listen_after_bind(); });
  19811. auto se = detail::scope_exit([&] {
  19812. svr.stop();
  19813. t.join();
  19814. ASSERT_FALSE(svr.is_running());
  19815. });
  19816. svr.wait_until_ready();
  19817. Client cli(HOST, port);
  19818. cli.set_decompress(false);
  19819. Headers headers;
  19820. headers.emplace("Accept-Encoding", "identity");
  19821. headers.emplace("Accept-Encoding", "gzip");
  19822. auto res = cli.Get("/", headers);
  19823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19824. EXPECT_EQ(StatusCode::OK_200, res->status);
  19825. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19826. }
  19827. #endif
  19828. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19829. // Transfer-Encoding is not its body.
  19830. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19831. Server svr;
  19832. svr.set_payload_max_length(8);
  19833. svr.Post("/test", [](const Request &, Response &res) {
  19834. res.set_content("ok", "text/plain");
  19835. });
  19836. auto port = svr.bind_to_any_port(HOST);
  19837. ASSERT_GT(port, 0);
  19838. thread t = thread([&] { svr.listen_after_bind(); });
  19839. auto se = detail::scope_exit([&] {
  19840. svr.stop();
  19841. t.join();
  19842. ASSERT_FALSE(svr.is_running());
  19843. });
  19844. svr.wait_until_ready();
  19845. std::string resp;
  19846. ASSERT_TRUE(send_request(1,
  19847. "POST /test HTTP/1.1\r\n"
  19848. "Host: localhost\r\n"
  19849. "Connection: close\r\n"
  19850. "\r\n" +
  19851. std::string(16, 'X'),
  19852. &resp, port));
  19853. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19854. }
  19855. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19856. Server svr;
  19857. svr.Post("/post", [&](const Request &req, Response &res) {
  19858. res.set_content(req.body, "text/plain");
  19859. });
  19860. svr.Put("/put", [&](const Request &req, Response &res) {
  19861. res.set_content(req.body, "text/plain");
  19862. });
  19863. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19864. res.set_content(req.body, "text/plain");
  19865. });
  19866. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19867. res.set_content(req.body, "text/plain");
  19868. });
  19869. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19870. auto se = detail::scope_exit([&] {
  19871. svr.stop();
  19872. t.join();
  19873. ASSERT_FALSE(svr.is_running());
  19874. });
  19875. svr.wait_until_ready();
  19876. std::string resp;
  19877. // POST without Content-Length
  19878. ASSERT_TRUE(send_request(5,
  19879. "POST /post HTTP/1.1\r\n"
  19880. "Host: localhost\r\n"
  19881. "Connection: close\r\n"
  19882. "\r\n",
  19883. &resp));
  19884. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19885. // PUT without Content-Length
  19886. resp.clear();
  19887. ASSERT_TRUE(send_request(5,
  19888. "PUT /put HTTP/1.1\r\n"
  19889. "Host: localhost\r\n"
  19890. "Connection: close\r\n"
  19891. "\r\n",
  19892. &resp));
  19893. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19894. // PATCH without Content-Length
  19895. resp.clear();
  19896. ASSERT_TRUE(send_request(5,
  19897. "PATCH /patch HTTP/1.1\r\n"
  19898. "Host: localhost\r\n"
  19899. "Connection: close\r\n"
  19900. "\r\n",
  19901. &resp));
  19902. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19903. // DELETE without Content-Length
  19904. resp.clear();
  19905. ASSERT_TRUE(send_request(5,
  19906. "DELETE /delete HTTP/1.1\r\n"
  19907. "Host: localhost\r\n"
  19908. "Connection: close\r\n"
  19909. "\r\n",
  19910. &resp));
  19911. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19912. }
  19913. //==============================================================================
  19914. // open_stream() Tests
  19915. //==============================================================================
  19916. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19917. std::string result;
  19918. char buf[8192];
  19919. ssize_t n;
  19920. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19921. result.append(buf, static_cast<size_t>(n));
  19922. }
  19923. return result;
  19924. }
  19925. // Mock stream for unit tests
  19926. class MockStream : public Stream {
  19927. public:
  19928. std::string data;
  19929. size_t pos = 0;
  19930. ssize_t error_after = -1; // -1 = no error
  19931. explicit MockStream(const std::string &d, ssize_t err = -1)
  19932. : data(d), error_after(err) {}
  19933. bool is_readable() const override { return true; }
  19934. bool wait_readable() const override { return true; }
  19935. bool wait_writable() const override { return true; }
  19936. ssize_t read(char *ptr, size_t size) override {
  19937. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19938. if (pos >= data.size()) return 0;
  19939. size_t limit =
  19940. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19941. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19942. std::memcpy(ptr, data.data() + pos, to_read);
  19943. pos += to_read;
  19944. return static_cast<ssize_t>(to_read);
  19945. }
  19946. ssize_t write(const char *, size_t) override { return -1; }
  19947. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19948. ip = "127.0.0.1";
  19949. port = 0;
  19950. }
  19951. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19952. ip = "127.0.0.1";
  19953. port = 0;
  19954. }
  19955. socket_t socket() const override { return INVALID_SOCKET; }
  19956. time_t duration() const override { return 0; }
  19957. };
  19958. TEST(StreamHandleTest, Basic) {
  19959. ClientImpl::StreamHandle handle;
  19960. EXPECT_FALSE(handle.is_valid());
  19961. handle.response = detail::make_unique<Response>();
  19962. handle.error = Error::Connection;
  19963. EXPECT_FALSE(handle.is_valid());
  19964. handle.error = Error::Success;
  19965. EXPECT_TRUE(handle.is_valid());
  19966. }
  19967. TEST(BodyReaderTest, Basic) {
  19968. MockStream stream("Hello, World!");
  19969. detail::BodyReader reader;
  19970. reader.stream = &stream;
  19971. reader.content_length = 13;
  19972. char buf[32];
  19973. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19974. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19975. EXPECT_TRUE(reader.eof);
  19976. }
  19977. TEST(BodyReaderTest, NoStream) {
  19978. detail::BodyReader reader;
  19979. char buf[32];
  19980. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19981. EXPECT_EQ(Error::Connection, reader.last_error);
  19982. }
  19983. TEST(BodyReaderTest, Error) {
  19984. MockStream stream("Hello, World!", 5);
  19985. detail::BodyReader reader;
  19986. reader.stream = &stream;
  19987. reader.content_length = 13;
  19988. char buf[32];
  19989. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19990. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19991. EXPECT_EQ(Error::Read, reader.last_error);
  19992. }
  19993. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19994. // Mock-based StreamHandle tests relying on private internals are removed.
  19995. class OpenStreamTest : public ::testing::Test {
  19996. protected:
  19997. void SetUp() override {
  19998. svr_.Get("/hello", [](const Request &, Response &res) {
  19999. res.set_content("Hello World!", "text/plain");
  20000. });
  20001. svr_.Get("/large", [](const Request &, Response &res) {
  20002. res.set_content(std::string(10000, 'X'), "text/plain");
  20003. });
  20004. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20005. res.set_content("Hello World!", "image/jpeg");
  20006. res.set_header("Content-Encoding", "UTF-8");
  20007. });
  20008. svr_.Get("/chunked", [](const Request &, Response &res) {
  20009. res.set_chunked_content_provider("text/plain",
  20010. [](size_t offset, DataSink &sink) {
  20011. if (offset < 15) {
  20012. sink.write("chunk", 5);
  20013. return true;
  20014. }
  20015. sink.done();
  20016. return true;
  20017. });
  20018. });
  20019. svr_.Get("/compressible", [](const Request &, Response &res) {
  20020. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20021. DataSink &sink) {
  20022. if (offset < 100 * 1024) {
  20023. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20024. sink.write(chunk.data(), chunk.size());
  20025. return true;
  20026. }
  20027. sink.done();
  20028. return true;
  20029. });
  20030. });
  20031. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20032. [](const Request & /*req*/, Response &res) {
  20033. auto i = new int(0);
  20034. res.set_header("Trailer", "Content-Length, X-Allowed");
  20035. res.set_chunked_content_provider(
  20036. "text/plain",
  20037. [i](size_t /*offset*/, DataSink &sink) {
  20038. switch (*i) {
  20039. case 0: sink.os << "123"; break;
  20040. case 1: sink.os << "456"; break;
  20041. case 2: sink.os << "789"; break;
  20042. case 3: {
  20043. sink.done_with_trailer(
  20044. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20045. } break;
  20046. }
  20047. (*i)++;
  20048. return true;
  20049. },
  20050. [i](bool success) {
  20051. EXPECT_TRUE(success);
  20052. delete i;
  20053. });
  20054. });
  20055. // Echo headers endpoint for header-related tests
  20056. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20057. std::string body;
  20058. for (const auto &h : req.headers) {
  20059. body.append(h.first);
  20060. body.push_back(':');
  20061. body.append(h.second);
  20062. body.push_back('\n');
  20063. }
  20064. res.set_content(body, "text/plain");
  20065. });
  20066. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20067. std::string body;
  20068. for (const auto &h : req.headers) {
  20069. body.append(h.first);
  20070. body.push_back(':');
  20071. body.append(h.second);
  20072. body.push_back('\n');
  20073. }
  20074. res.set_content(body, "text/plain");
  20075. });
  20076. port_ = svr_.bind_to_any_port("127.0.0.1");
  20077. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20078. svr_.wait_until_ready();
  20079. }
  20080. void TearDown() override {
  20081. svr_.stop();
  20082. if (thread_.joinable()) thread_.join();
  20083. }
  20084. Server svr_;
  20085. std::thread thread_;
  20086. int port_ = 0;
  20087. };
  20088. TEST_F(OpenStreamTest, Basic) {
  20089. Client cli("127.0.0.1", port_);
  20090. auto handle = cli.open_stream("GET", "/hello");
  20091. EXPECT_TRUE(handle.is_valid());
  20092. EXPECT_EQ("Hello World!", read_all(handle));
  20093. }
  20094. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20095. Client cli("127.0.0.1", port_);
  20096. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20097. ASSERT_TRUE(handle.is_valid());
  20098. EXPECT_EQ("Hello World!", read_all(handle));
  20099. }
  20100. TEST_F(OpenStreamTest, SmallBuffer) {
  20101. Client cli("127.0.0.1", port_);
  20102. auto handle = cli.open_stream("GET", "/hello");
  20103. std::string result;
  20104. char buf[4];
  20105. ssize_t n;
  20106. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20107. result.append(buf, static_cast<size_t>(n));
  20108. EXPECT_EQ("Hello World!", result);
  20109. }
  20110. TEST_F(OpenStreamTest, DefaultHeaders) {
  20111. Client cli("127.0.0.1", port_);
  20112. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20113. {
  20114. auto handle = cli.open_stream("GET", "/echo-headers");
  20115. ASSERT_TRUE(handle.is_valid());
  20116. auto body = read_all(handle);
  20117. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20118. std::string::npos);
  20119. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20120. std::string::npos);
  20121. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20122. }
  20123. // open_stream POST with body and no explicit content_type should NOT add
  20124. // text/plain Content-Type (behavior differs from non-streaming path), but
  20125. // should include Content-Length
  20126. {
  20127. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20128. ASSERT_TRUE(handle.is_valid());
  20129. auto body = read_all(handle);
  20130. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20131. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20132. }
  20133. // open_stream POST with explicit Content-Type should preserve it
  20134. {
  20135. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20136. {{"Content-Type", "application/custom"}},
  20137. "{}", "application/custom");
  20138. ASSERT_TRUE(handle.is_valid());
  20139. auto body = read_all(handle);
  20140. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20141. }
  20142. // User-specified User-Agent must not be overwritten for stream API
  20143. {
  20144. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20145. {{"User-Agent", "MyAgent/1.2"}});
  20146. ASSERT_TRUE(handle.is_valid());
  20147. auto body = read_all(handle);
  20148. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20149. }
  20150. }
  20151. TEST_F(OpenStreamTest, Large) {
  20152. Client cli("127.0.0.1", port_);
  20153. auto handle = cli.open_stream("GET", "/large");
  20154. EXPECT_EQ(10000u, read_all(handle).size());
  20155. }
  20156. TEST_F(OpenStreamTest, ConnectionError) {
  20157. Client cli("127.0.0.1", 9999);
  20158. auto handle = cli.open_stream("GET", "/hello");
  20159. EXPECT_FALSE(handle.is_valid());
  20160. }
  20161. TEST_F(OpenStreamTest, Chunked) {
  20162. Client cli("127.0.0.1", port_);
  20163. auto handle = cli.open_stream("GET", "/chunked");
  20164. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20165. "Transfer-Encoding") == "chunked");
  20166. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20167. }
  20168. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20169. Client cli("127.0.0.1", port_);
  20170. auto handle =
  20171. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20172. ASSERT_TRUE(handle.is_valid());
  20173. // Consume body to allow trailers to be received/parsed
  20174. auto body = read_all(handle);
  20175. // Explicitly parse trailers (ensure trailers are available for assertion)
  20176. handle.parse_trailers_if_needed();
  20177. EXPECT_EQ(std::string("123456789"), body);
  20178. // The response should include a Trailer header declaring both names
  20179. ASSERT_TRUE(handle.response);
  20180. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20181. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20182. handle.response->get_header_value("Trailer"));
  20183. // Prohibited trailer must not be present
  20184. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20185. // Allowed trailer should be present
  20186. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20187. EXPECT_EQ(std::string("yes"),
  20188. handle.response->get_trailer_value("X-Allowed"));
  20189. // Verify trailers are NOT present as regular headers
  20190. EXPECT_EQ(std::string(""),
  20191. handle.response->get_header_value("Content-Length"));
  20192. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20193. }
  20194. // Accepts one connection on an OS-assigned port, which it hands over through
  20195. // port_promise, reads the request head and sends back response. after_send,
  20196. // if given, runs on the connection before it is closed.
  20197. static std::thread
  20198. serve_single_response(std::promise<int> &port_promise,
  20199. const std::string &response,
  20200. std::function<void(socket_t)> after_send = nullptr) {
  20201. return std::thread([&port_promise, response, after_send] {
  20202. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20203. default_socket_options(srv);
  20204. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20205. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20206. sockaddr_in addr{};
  20207. addr.sin_family = AF_INET;
  20208. addr.sin_port = htons(0); // Let OS assign a free port
  20209. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20210. int opt = 1;
  20211. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20212. #ifdef _WIN32
  20213. reinterpret_cast<const char *>(&opt),
  20214. #else
  20215. &opt,
  20216. #endif
  20217. sizeof(opt));
  20218. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20219. ::listen(srv, 1) != 0) {
  20220. port_promise.set_value(-1);
  20221. detail::close_socket(srv);
  20222. return;
  20223. }
  20224. socklen_t addr_len = sizeof(addr);
  20225. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20226. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20227. sockaddr_in cli_addr{};
  20228. socklen_t cli_len = sizeof(cli_addr);
  20229. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20230. if (cli != INVALID_SOCKET) {
  20231. // Read the complete HTTP request (until the blank line that terminates
  20232. // headers) before sending the response. If the server closes the socket
  20233. // while the client's request data is still unread in the kernel receive
  20234. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20235. // connection on both sides: it discards the client's receive buffer
  20236. // (which already holds our response) and causes any in-progress write on
  20237. // the client to fail with ECONNRESET. Reading all request data first
  20238. // ensures close() emits a graceful FIN.
  20239. {
  20240. char rbuf[256];
  20241. std::string req;
  20242. while (req.find("\r\n\r\n") == std::string::npos) {
  20243. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20244. if (n <= 0) { break; }
  20245. req.append(rbuf, static_cast<size_t>(n));
  20246. }
  20247. }
  20248. ::send(cli,
  20249. #ifdef _WIN32
  20250. static_cast<const char *>(response.c_str()),
  20251. static_cast<int>(response.size()),
  20252. #else
  20253. response.c_str(), response.size(),
  20254. #endif
  20255. 0);
  20256. if (after_send) { after_send(cli); }
  20257. detail::close_socket(cli);
  20258. }
  20259. detail::close_socket(srv);
  20260. });
  20261. }
  20262. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20263. #ifndef _WIN32
  20264. signal(SIGPIPE, SIG_IGN);
  20265. #endif
  20266. std::promise<int> port_promise;
  20267. auto port_future = port_promise.get_future();
  20268. auto server_thread =
  20269. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20270. "Content-Type: text/plain\r\n"
  20271. "Content-Length: not-a-number\r\n"
  20272. "Connection: close\r\n"
  20273. "\r\n"
  20274. "hello");
  20275. auto port = port_future.get();
  20276. ASSERT_GT(port, 0);
  20277. Client cli("127.0.0.1", port);
  20278. auto handle = cli.open_stream("GET", "/");
  20279. EXPECT_FALSE(handle.is_valid());
  20280. server_thread.join();
  20281. }
  20282. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20283. #ifndef _WIN32
  20284. signal(SIGPIPE, SIG_IGN);
  20285. #endif
  20286. std::promise<int> port_promise;
  20287. auto port_future = port_promise.get_future();
  20288. auto server_thread = serve_single_response(
  20289. port_promise, "HTTP/1.1 200 OK\r\n"
  20290. "Content-Type: text/plain\r\n"
  20291. "Content-Length: 99999999999999999999999999\r\n"
  20292. "Connection: close\r\n"
  20293. "\r\n"
  20294. "hello");
  20295. auto port = port_future.get();
  20296. ASSERT_GT(port, 0);
  20297. // Historically std::stoull would throw std::out_of_range here and crash
  20298. // the process, then parsing silently clamped to a bogus framing length and
  20299. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20300. // so the stream fails to open, matching the not-a-number case above. The
  20301. // process still must NOT terminate.
  20302. Client cli("127.0.0.1", port);
  20303. auto handle = cli.open_stream("GET", "/");
  20304. EXPECT_FALSE(handle.is_valid());
  20305. server_thread.join();
  20306. }
  20307. #ifndef _WIN32
  20308. // As above for the body of a streamed request: a send() cut short by the write
  20309. // timeout must not leave the rest of the body unsent.
  20310. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20311. signal(SIGPIPE, SIG_IGN);
  20312. Server svr;
  20313. svr.set_socket_options([](socket_t sock) {
  20314. int size = 8192;
  20315. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20316. reinterpret_cast<const char *>(&size), sizeof(size));
  20317. });
  20318. svr.Post("/size", [](const Request &, Response &res,
  20319. const ContentReader &content_reader) {
  20320. // Outlast the client's write timeout before reading the body.
  20321. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20322. size_t received = 0;
  20323. content_reader([&](const char *, size_t len) {
  20324. received += len;
  20325. return true;
  20326. });
  20327. res.set_content(std::to_string(received), "text/plain");
  20328. });
  20329. auto port = svr.bind_to_any_port(HOST);
  20330. std::thread t([&]() { svr.listen_after_bind(); });
  20331. auto se = detail::scope_exit([&] {
  20332. svr.stop();
  20333. t.join();
  20334. });
  20335. svr.wait_until_ready();
  20336. Client cli(HOST, port);
  20337. cli.set_write_timeout(0, 500000);
  20338. cli.set_socket_options([](socket_t sock) {
  20339. int size = 8192;
  20340. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20341. reinterpret_cast<const char *>(&size), sizeof(size));
  20342. });
  20343. const std::string body(4 * 1024 * 1024, 'A');
  20344. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20345. "application/octet-stream");
  20346. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20347. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20348. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20349. }
  20350. #endif
  20351. // Serves `response` to the single request `fn` makes with a fresh client.
  20352. template <typename Fn>
  20353. static void with_single_response(const std::string &response, Fn fn) {
  20354. #ifndef _WIN32
  20355. signal(SIGPIPE, SIG_IGN);
  20356. #endif
  20357. std::promise<int> port_promise;
  20358. auto port_future = port_promise.get_future();
  20359. auto server_thread = serve_single_response(port_promise, response);
  20360. auto se = detail::scope_exit([&] { server_thread.join(); });
  20361. auto port = port_future.get();
  20362. ASSERT_GT(port, 0);
  20363. Client cli("127.0.0.1", port);
  20364. fn(cli);
  20365. }
  20366. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20367. // too, also in a build without the decoder for the advertised coding.
  20368. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20369. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20370. const auto response = "HTTP/1.1 200 OK\r\n"
  20371. "Content-Encoding: gzip\r\n"
  20372. "Content-Length: " +
  20373. std::to_string(gzipped.size()) +
  20374. "\r\n"
  20375. "Connection: close\r\n\r\n" +
  20376. gzipped;
  20377. with_single_response(response, [&](Client &cli) {
  20378. cli.set_decompress(false);
  20379. auto handle = cli.open_stream("GET", "/");
  20380. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20381. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20382. EXPECT_EQ(gzipped, read_all(handle));
  20383. EXPECT_FALSE(handle.has_read_error());
  20384. });
  20385. with_single_response(response, [&](Client &cli) {
  20386. cli.set_decompress(false);
  20387. auto res = stream::Get(cli, "/", 7);
  20388. ASSERT_TRUE(res) << to_string(res.error());
  20389. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20390. EXPECT_EQ(gzipped, res.read_all());
  20391. EXPECT_FALSE(res.has_read_error());
  20392. });
  20393. }
  20394. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20395. // Neither Content-Length nor chunked: the body ends at the close
  20396. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20397. "Connection: close\r\n"
  20398. "\r\n"
  20399. "hello";
  20400. with_single_response(close_delimited, [](Client &cli) {
  20401. auto handle = cli.open_stream("GET", "/");
  20402. ASSERT_TRUE(handle.is_valid());
  20403. EXPECT_EQ("hello", read_all(handle));
  20404. EXPECT_FALSE(handle.has_read_error());
  20405. });
  20406. // A close before the end of the Content-Length is still an error
  20407. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20408. "Content-Length: 10\r\n"
  20409. "\r\n"
  20410. "hello";
  20411. with_single_response(short_content_length, [](Client &cli) {
  20412. auto handle = cli.open_stream("GET", "/");
  20413. ASSERT_TRUE(handle.is_valid());
  20414. read_all(handle);
  20415. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20416. });
  20417. // So is a close before the last chunk
  20418. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20419. "Transfer-Encoding: chunked\r\n"
  20420. "\r\n"
  20421. "5\r\nhello\r\n";
  20422. with_single_response(short_chunked, [](Client &cli) {
  20423. auto handle = cli.open_stream("GET", "/");
  20424. ASSERT_TRUE(handle.is_valid());
  20425. read_all(handle);
  20426. EXPECT_TRUE(handle.has_read_error());
  20427. });
  20428. }
  20429. #ifdef CPPHTTPLIB_SSL_ENABLED
  20430. // Serves `response` to one request, then closes with or without a close_notify
  20431. template <typename Fn>
  20432. static void with_single_tls_response(const std::string &response,
  20433. bool close_notify, Fn fn) {
  20434. #ifndef _WIN32
  20435. signal(SIGPIPE, SIG_IGN);
  20436. #endif
  20437. std::promise<int> port_promise;
  20438. auto port_future = port_promise.get_future();
  20439. auto server_thread = std::thread([&port_promise, response, close_notify] {
  20440. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20441. default_socket_options(srv);
  20442. sockaddr_in addr{};
  20443. addr.sin_family = AF_INET;
  20444. addr.sin_port = htons(0);
  20445. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20446. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20447. ::listen(srv, 1) != 0) {
  20448. port_promise.set_value(-1);
  20449. detail::close_socket(srv);
  20450. return;
  20451. }
  20452. socklen_t addr_len = sizeof(addr);
  20453. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20454. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20455. auto cli = ::accept(srv, nullptr, nullptr);
  20456. if (cli != INVALID_SOCKET) {
  20457. auto ctx = tls::create_server_context();
  20458. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20459. nullptr);
  20460. auto session = tls::create_session(ctx, cli);
  20461. tls::TlsError err;
  20462. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  20463. // The request head first, so that closing the socket sends a FIN
  20464. // rather than an RST for the unread bytes.
  20465. std::string req;
  20466. char buf[256];
  20467. while (req.find("\r\n\r\n") == std::string::npos) {
  20468. auto n = tls::read(session, buf, sizeof(buf), err);
  20469. if (n <= 0) { break; }
  20470. req.append(buf, static_cast<size_t>(n));
  20471. }
  20472. size_t sent = 0;
  20473. while (sent < response.size()) {
  20474. auto n = tls::write(session, response.data() + sent,
  20475. response.size() - sent, err);
  20476. if (n <= 0) { break; }
  20477. sent += static_cast<size_t>(n);
  20478. }
  20479. if (close_notify) { tls::shutdown(session, true); }
  20480. }
  20481. tls::free_session(session);
  20482. detail::close_socket(cli);
  20483. tls::free_context(ctx);
  20484. }
  20485. detail::close_socket(srv);
  20486. });
  20487. auto se = detail::scope_exit([&] { server_thread.join(); });
  20488. auto port = port_future.get();
  20489. ASSERT_GT(port, 0);
  20490. SSLClient cli("127.0.0.1", port);
  20491. cli.enable_server_certificate_verification(false);
  20492. fn(cli);
  20493. }
  20494. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  20495. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  20496. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  20497. "Connection: close\r\n"
  20498. "\r\n"
  20499. "hello";
  20500. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  20501. auto res = cli.Get("/");
  20502. ASSERT_TRUE(res) << to_string(res.error());
  20503. EXPECT_EQ("hello", res->body);
  20504. });
  20505. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20506. auto res = cli.Get("/");
  20507. ASSERT_FALSE(res);
  20508. EXPECT_EQ(Error::Read, res.error());
  20509. });
  20510. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  20511. auto handle = cli.open_stream("GET", "/");
  20512. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20513. read_all(handle);
  20514. EXPECT_TRUE(handle.has_read_error());
  20515. });
  20516. // A framed body ends where its framing says, with or without the alert
  20517. const std::string framed = "HTTP/1.1 200 OK\r\n"
  20518. "Content-Length: 5\r\n"
  20519. "Connection: close\r\n"
  20520. "\r\n"
  20521. "hello";
  20522. with_single_tls_response(framed, false, [](SSLClient &cli) {
  20523. auto res = cli.Get("/");
  20524. ASSERT_TRUE(res) << to_string(res.error());
  20525. EXPECT_EQ("hello", res->body);
  20526. });
  20527. }
  20528. #endif
  20529. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20530. const char *responses[] = {
  20531. "HTTP/1.1 103 Early Hints\r\n"
  20532. "Link: </style.css>; rel=preload\r\n"
  20533. "\r\n"
  20534. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20535. "HTTP/1.1 100 Continue\r\n"
  20536. "X-Note: interim\r\n"
  20537. "\r\n"
  20538. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20539. };
  20540. for (auto response : responses) {
  20541. with_single_response(response, [](Client &cli) {
  20542. auto res = cli.Get("/");
  20543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20544. EXPECT_EQ(StatusCode::OK_200, res->status);
  20545. EXPECT_EQ("ok", res->body);
  20546. });
  20547. }
  20548. }
  20549. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20550. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20551. const std::string final_response =
  20552. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20553. std::string interims;
  20554. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20555. interims += interim;
  20556. }
  20557. with_single_response(interims + final_response, [](Client &cli) {
  20558. auto res = cli.Get("/");
  20559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20560. EXPECT_EQ("ok", res->body);
  20561. });
  20562. with_single_response(interims + interim + final_response, [](Client &cli) {
  20563. auto res = cli.Get("/");
  20564. ASSERT_FALSE(res);
  20565. EXPECT_EQ(Error::Read, res.error());
  20566. });
  20567. }
  20568. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20569. #ifndef _WIN32
  20570. signal(SIGPIPE, SIG_IGN);
  20571. #endif
  20572. // The server answers the head without asking for the body. Bytes it then
  20573. // reads on the connection would be taken for the body the request declared.
  20574. auto closed_by_client = false;
  20575. std::promise<int> port_promise;
  20576. auto server_thread = serve_single_response(
  20577. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20578. [&](socket_t sock) {
  20579. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20580. char buf[256];
  20581. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20582. });
  20583. Client cli("127.0.0.1", port_promise.get_future().get());
  20584. cli.set_keep_alive(true);
  20585. cli.set_read_timeout(1, 0);
  20586. // Long enough for the client to send Expect: 100-continue.
  20587. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20589. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20590. cli.Get("/second");
  20591. server_thread.join();
  20592. EXPECT_TRUE(closed_by_client);
  20593. }
  20594. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20595. // Long enough for the client to send Expect: 100-continue
  20596. with_single_response(
  20597. "HTTP/1.1 103 Early Hints\r\n"
  20598. "Link: </style.css>; rel=preload\r\n"
  20599. "\r\n"
  20600. "HTTP/1.1 401 Unauthorized\r\n"
  20601. "Content-Length: 0\r\n\r\n",
  20602. [](Client &cli) {
  20603. cli.set_read_timeout(2, 0);
  20604. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20606. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20607. });
  20608. }
  20609. #ifdef CPPHTTPLIB_SSL_ENABLED
  20610. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20611. #ifndef _WIN32
  20612. signal(SIGPIPE, SIG_IGN);
  20613. #endif
  20614. auto reused = false;
  20615. std::promise<int> port_promise;
  20616. auto server_thread = serve_single_response(
  20617. port_promise,
  20618. "HTTP/1.1 401 Unauthorized\r\n"
  20619. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20620. "Content-Length: 0\r\n\r\n",
  20621. [&](socket_t sock) {
  20622. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20623. char buf[256];
  20624. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20625. });
  20626. Client cli("127.0.0.1", port_promise.get_future().get());
  20627. cli.set_keep_alive(true);
  20628. cli.set_digest_auth("user", "pass");
  20629. cli.set_read_timeout(1, 0);
  20630. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20631. server_thread.join();
  20632. EXPECT_FALSE(reused);
  20633. }
  20634. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20635. // Any other answer to CONNECT would read as the origin's response.
  20636. struct {
  20637. const char *response;
  20638. bool passed_on;
  20639. } cases[] = {
  20640. {"HTTP/1.1 201 Created\r\n"
  20641. "Set-Cookie: session=from-proxy\r\n"
  20642. "Content-Length: 0\r\n\r\n",
  20643. false},
  20644. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20645. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20646. "Content-Length: 0\r\n\r\n",
  20647. true},
  20648. };
  20649. for (const auto &c : cases) {
  20650. std::promise<int> port_promise;
  20651. auto server_thread = serve_single_response(port_promise, c.response);
  20652. SSLClient cli("example.com", 443);
  20653. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20654. auto res = cli.Get("/");
  20655. server_thread.join();
  20656. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20657. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20658. if (res) {
  20659. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20660. }
  20661. }
  20662. }
  20663. #endif
  20664. // Records the client's error logger calls as "error METHOD path", or
  20665. // "error null" for a call without a request
  20666. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20667. return [&log](const Error &err, const Request *req) {
  20668. log.push_back(to_string(err) + " " +
  20669. (req ? req->method + " " + req->path : "null"));
  20670. };
  20671. }
  20672. // A failed request is reported once, with the request the caller made
  20673. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20674. Server svr;
  20675. svr.Get("/big", [](const Request &, Response &res) {
  20676. res.set_content(std::string(100000, 'b'), "text/plain");
  20677. });
  20678. auto port = svr.bind_to_any_port(HOST);
  20679. std::thread t([&]() { svr.listen_after_bind(); });
  20680. auto se = detail::scope_exit([&] {
  20681. svr.stop();
  20682. t.join();
  20683. });
  20684. svr.wait_until_ready();
  20685. Client cli(HOST, port);
  20686. std::vector<std::string> log;
  20687. cli.set_error_logger(record_errors(log));
  20688. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20689. cli.Get("/big", [](const char *, size_t) { return false; });
  20690. EXPECT_EQ(expected, log);
  20691. log.clear();
  20692. cli.Get("/big", [](size_t, size_t) { return false; });
  20693. EXPECT_EQ(expected, log);
  20694. }
  20695. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20696. // Fails while the body is read
  20697. auto broken = [](const Request &, Response &res) {
  20698. res.set_content_provider(10, "text/plain",
  20699. [](size_t, size_t, DataSink &) { return false; });
  20700. };
  20701. Server other;
  20702. other.Get("/broken", broken);
  20703. auto other_port = other.bind_to_any_port(HOST);
  20704. std::thread other_t([&]() { other.listen_after_bind(); });
  20705. auto other_se = detail::scope_exit([&] {
  20706. other.stop();
  20707. other_t.join();
  20708. });
  20709. other.wait_until_ready();
  20710. Server svr;
  20711. svr.Get("/broken", broken);
  20712. svr.Get("/same-origin",
  20713. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20714. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20715. res.set_redirect("http://" + std::string(HOST) + ":" +
  20716. std::to_string(other_port) + "/broken");
  20717. });
  20718. auto port = svr.bind_to_any_port(HOST);
  20719. std::thread t([&]() { svr.listen_after_bind(); });
  20720. auto se = detail::scope_exit([&] {
  20721. svr.stop();
  20722. t.join();
  20723. });
  20724. svr.wait_until_ready();
  20725. Client cli(HOST, port);
  20726. cli.set_follow_location(true);
  20727. std::vector<std::string> log;
  20728. cli.set_error_logger(record_errors(log));
  20729. for (auto path : {"/same-origin", "/cross-origin"}) {
  20730. log.clear();
  20731. auto res = cli.Get(path);
  20732. ASSERT_FALSE(res);
  20733. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20734. log);
  20735. }
  20736. }
  20737. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20738. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20739. std::vector<std::string> log;
  20740. cli.set_error_logger(record_errors(log));
  20741. auto handle = cli.open_stream("GET", "/x");
  20742. EXPECT_FALSE(handle.is_valid());
  20743. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20744. log);
  20745. });
  20746. }
  20747. #ifdef CPPHTTPLIB_SSL_ENABLED
  20748. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20749. // Not a TLS server, so the handshake fails. It waits for a request line in
  20750. // the handshake bytes, so a short read timeout lets it close quickly.
  20751. Server svr;
  20752. svr.set_read_timeout(0, 100000);
  20753. svr.Get("/x", [](const Request &, Response &res) {
  20754. res.set_content("x", "text/plain");
  20755. });
  20756. auto port = svr.bind_to_any_port(HOST);
  20757. std::thread t([&]() { svr.listen_after_bind(); });
  20758. auto se = detail::scope_exit([&] {
  20759. svr.stop();
  20760. t.join();
  20761. });
  20762. svr.wait_until_ready();
  20763. std::vector<std::string> log;
  20764. SSLClient cli(HOST, port);
  20765. cli.enable_server_certificate_verification(false);
  20766. cli.set_error_logger(record_errors(log));
  20767. auto res = cli.Get("/x");
  20768. ASSERT_FALSE(res);
  20769. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20770. log.clear();
  20771. auto handle = cli.open_stream("GET", "/x");
  20772. EXPECT_FALSE(handle.is_valid());
  20773. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20774. log.clear();
  20775. SSLClient no_ca(HOST, port);
  20776. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20777. no_ca.set_error_logger(record_errors(log));
  20778. res = no_ca.Get("/x");
  20779. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20780. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20781. }
  20782. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20783. #ifndef _WIN32
  20784. signal(SIGPIPE, SIG_IGN);
  20785. #endif
  20786. // Refused, answered with a challenge, or closed without an answer
  20787. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20788. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20789. "Content-Length: 0\r\n\r\n",
  20790. ""}) {
  20791. std::promise<int> port_promise;
  20792. auto server_thread = serve_single_response(port_promise, response);
  20793. SSLClient cli("example.com", 443);
  20794. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20795. std::vector<std::string> log;
  20796. cli.set_error_logger(record_errors(log));
  20797. auto res = cli.Get("/");
  20798. server_thread.join();
  20799. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20800. << response;
  20801. }
  20802. }
  20803. #endif
  20804. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20805. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20806. // the chunked coding and drop Content-Length, so a front-end that trusts
  20807. // Content-Length would disagree about where the body ends (response
  20808. // smuggling). The client must reject such a response.
  20809. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20810. for (const char *te : {"chunked", "gzip, chunked"}) {
  20811. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20812. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20813. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20814. "5\r\nhello\r\n0\r\n\r\n";
  20815. with_single_response(response, [&](Client &cli) {
  20816. auto res = cli.Get("/");
  20817. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20818. EXPECT_EQ(Error::Read, res.error()) << te;
  20819. });
  20820. with_single_response(response, [&](Client &cli) {
  20821. auto handle = cli.open_stream("GET", "/");
  20822. EXPECT_FALSE(handle.is_valid()) << te;
  20823. EXPECT_EQ(Error::Read, handle.error) << te;
  20824. });
  20825. }
  20826. }
  20827. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20828. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20829. // closing the connection (unlike a request, which must be rejected).
  20830. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20831. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20832. "Transfer-Encoding: chunked\r\n"
  20833. "Connection: close\r\n"
  20834. "\r\n"
  20835. "5\r\nhello\r\n0\r\n\r\n",
  20836. "HTTP/1.1 200 OK\r\n"
  20837. "Transfer-Encoding: gzip\r\n"
  20838. "Connection: close\r\n"
  20839. "\r\n"
  20840. "hello"}) {
  20841. with_single_response(response, [&](Client &cli) {
  20842. auto res = cli.Get("/");
  20843. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20844. EXPECT_EQ("hello", res->body);
  20845. });
  20846. with_single_response(response, [&](Client &cli) {
  20847. auto handle = cli.open_stream("GET", "/");
  20848. ASSERT_TRUE(handle.is_valid()) << response;
  20849. EXPECT_EQ("hello", read_all(handle));
  20850. });
  20851. }
  20852. }
  20853. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20854. // framing headers describe nothing to read and must not be rejected.
  20855. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20856. const std::string framing = "Content-Length: 5\r\n"
  20857. "Transfer-Encoding: chunked\r\n"
  20858. "Connection: close\r\n"
  20859. "\r\n";
  20860. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20861. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20862. });
  20863. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20864. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20865. });
  20866. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20867. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20868. with_single_response(response, [&](Client &cli) {
  20869. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20870. });
  20871. with_single_response(response, [&](Client &cli) {
  20872. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20873. });
  20874. }
  20875. }
  20876. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20877. // header section, so a stream opened on one has nothing to read, whatever
  20878. // framing or coding headers it carries.
  20879. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20880. struct Case {
  20881. const char *method;
  20882. const char *status;
  20883. };
  20884. // A reader of the declared body reports an early close when nothing
  20885. // follows, and hands back what does.
  20886. struct Framing {
  20887. const char *headers;
  20888. const char *after;
  20889. };
  20890. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20891. Case{"GET", "304 Not Modified"}}) {
  20892. for (const auto &f :
  20893. {Framing{"Content-Length: 5\r\n", ""},
  20894. Framing{"Content-Length: 5\r\n", "hello"},
  20895. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20896. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20897. // Not decoded, so a build without Brotli opens it too
  20898. Framing{"Content-Encoding: br\r\n", ""}}) {
  20899. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20900. "Connection: close\r\n"
  20901. "\r\n" +
  20902. f.after;
  20903. with_single_response(response, [&](Client &cli) {
  20904. auto handle = cli.open_stream(c.method, "/");
  20905. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20906. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20907. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20908. });
  20909. }
  20910. }
  20911. }
  20912. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20913. // response, is faulty framing, so the connection is not reused after it.
  20914. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20915. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20916. "Content-Length: 0\r\n"
  20917. "Transfer-Encoding: chunked\r\n"
  20918. "\r\n"
  20919. "5\r\nhello\r\n0\r\n\r\n",
  20920. "HTTP/1.0 200 Connection established\r\n"
  20921. "Connection: keep-alive\r\n"
  20922. "Transfer-Encoding: chunked\r\n"
  20923. "\r\n"
  20924. "5\r\nhello\r\n0\r\n\r\n"}) {
  20925. with_single_response(response, [&](Client &cli) {
  20926. cli.set_keep_alive(true);
  20927. auto res = cli.Get("/");
  20928. ASSERT_TRUE(res) << response;
  20929. EXPECT_EQ("hello", res->body);
  20930. EXPECT_FALSE(cli.is_socket_open()) << response;
  20931. });
  20932. }
  20933. }
  20934. // A payload max length of 0 means no limit, however the body is framed.
  20935. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20936. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20937. "Transfer-Encoding: chunked\r\n"
  20938. "\r\n"
  20939. "5\r\nhello\r\n0\r\n\r\n",
  20940. "HTTP/1.1 200 OK\r\n"
  20941. "Connection: close\r\n"
  20942. "\r\n"
  20943. "hello"}) {
  20944. with_single_response(response, [&](Client &cli) {
  20945. cli.set_payload_max_length(0);
  20946. auto res = cli.Get("/");
  20947. ASSERT_TRUE(res) << response;
  20948. EXPECT_EQ("hello", res->body) << response;
  20949. });
  20950. }
  20951. }
  20952. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20953. Server svr;
  20954. svr.set_payload_max_length(0);
  20955. svr.Post("/echo", [](const Request &req, Response &res) {
  20956. res.set_content(req.body, "text/plain");
  20957. });
  20958. auto port = svr.bind_to_any_port(HOST);
  20959. thread t = thread([&] { svr.listen_after_bind(); });
  20960. auto se = detail::scope_exit([&] {
  20961. svr.stop();
  20962. t.join();
  20963. ASSERT_FALSE(svr.is_running());
  20964. });
  20965. svr.wait_until_ready();
  20966. Client cli(HOST, port);
  20967. auto res = cli.Post(
  20968. "/echo",
  20969. [](size_t /*offset*/, DataSink &sink) {
  20970. sink.write("hello", 5);
  20971. sink.done();
  20972. return true;
  20973. },
  20974. "text/plain");
  20975. ASSERT_TRUE(res);
  20976. EXPECT_EQ(StatusCode::OK_200, res->status);
  20977. EXPECT_EQ("hello", res->body);
  20978. }
  20979. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20980. TEST_F(OpenStreamTest, Gzip) {
  20981. Client cli("127.0.0.1", port_);
  20982. auto handle = cli.open_stream("GET", "/compressible", {},
  20983. {{"Accept-Encoding", "gzip"}});
  20984. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20985. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20986. }
  20987. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20988. Client cli("127.0.0.1", port_);
  20989. auto handle =
  20990. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20991. {{"Accept-Encoding", "gzip"}});
  20992. ASSERT_TRUE(handle.is_valid());
  20993. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20994. EXPECT_EQ("123456789", read_all(handle));
  20995. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20996. }
  20997. #endif
  20998. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20999. TEST_F(OpenStreamTest, Brotli) {
  21000. Client cli("127.0.0.1", port_);
  21001. auto handle =
  21002. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21003. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21004. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21005. }
  21006. #endif
  21007. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21008. TEST_F(OpenStreamTest, Zstd) {
  21009. Client cli("127.0.0.1", port_);
  21010. auto handle = cli.open_stream("GET", "/compressible", {},
  21011. {{"Accept-Encoding", "zstd"}});
  21012. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21013. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21014. }
  21015. #endif
  21016. #ifdef CPPHTTPLIB_SSL_ENABLED
  21017. class SSLOpenStreamTest : public ::testing::Test {
  21018. protected:
  21019. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21020. void SetUp() override {
  21021. svr_.Get("/hello", [](const Request &, Response &res) {
  21022. res.set_content("Hello SSL World!", "text/plain");
  21023. });
  21024. svr_.Get("/chunked", [](const Request &, Response &res) {
  21025. res.set_chunked_content_provider("text/plain",
  21026. [](size_t offset, DataSink &sink) {
  21027. if (offset < 15) {
  21028. sink.write("chunk", 5);
  21029. return true;
  21030. }
  21031. sink.done();
  21032. return true;
  21033. });
  21034. });
  21035. svr_.Post("/echo", [](const Request &req, Response &res) {
  21036. res.set_content(req.body, req.get_header_value("Content-Type"));
  21037. });
  21038. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21039. std::string body = req.body;
  21040. res.set_chunked_content_provider(
  21041. "text/plain", [body](size_t offset, DataSink &sink) {
  21042. if (offset < body.size()) {
  21043. sink.write(body.data() + offset, body.size() - offset);
  21044. }
  21045. sink.done();
  21046. return true;
  21047. });
  21048. });
  21049. port_ = svr_.bind_to_any_port("127.0.0.1");
  21050. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21051. svr_.wait_until_ready();
  21052. }
  21053. void TearDown() override {
  21054. svr_.stop();
  21055. if (thread_.joinable()) thread_.join();
  21056. }
  21057. SSLServer svr_;
  21058. std::thread thread_;
  21059. int port_ = 0;
  21060. };
  21061. TEST_F(SSLOpenStreamTest, Basic) {
  21062. SSLClient cli("127.0.0.1", port_);
  21063. cli.enable_server_certificate_verification(false);
  21064. auto handle = cli.open_stream("GET", "/hello");
  21065. ASSERT_TRUE(handle.is_valid());
  21066. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21067. }
  21068. TEST_F(SSLOpenStreamTest, Chunked) {
  21069. SSLClient cli("127.0.0.1", port_);
  21070. cli.enable_server_certificate_verification(false);
  21071. auto handle = cli.open_stream("GET", "/chunked");
  21072. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21073. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21074. "Transfer-Encoding") == "chunked");
  21075. auto body = read_all(handle);
  21076. EXPECT_EQ("chunkchunkchunk", body);
  21077. }
  21078. TEST_F(SSLOpenStreamTest, Post) {
  21079. SSLClient cli("127.0.0.1", port_);
  21080. cli.enable_server_certificate_verification(false);
  21081. auto handle =
  21082. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21083. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21084. EXPECT_EQ(200, handle.response->status);
  21085. auto body = read_all(handle);
  21086. EXPECT_EQ("Hello SSL POST", body);
  21087. }
  21088. TEST_F(SSLOpenStreamTest, PostChunked) {
  21089. SSLClient cli("127.0.0.1", port_);
  21090. cli.enable_server_certificate_verification(false);
  21091. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21092. "Chunked SSL Data", "text/plain");
  21093. ASSERT_TRUE(handle.is_valid());
  21094. EXPECT_EQ(200, handle.response->status);
  21095. auto body = read_all(handle);
  21096. EXPECT_EQ("Chunked SSL Data", body);
  21097. }
  21098. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21099. // Content-Length is terminated by the server closing the connection. When the
  21100. // SSL peer sends a close_notify after the body, the client must treat it as a
  21101. // clean EOF and return a successful response rather than an error.
  21102. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21103. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21104. ASSERT_TRUE(svr.is_valid());
  21105. svr.set_keep_alive_max_count(1);
  21106. const std::string expected_body = "Hello from connection-close response!";
  21107. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21108. res.set_content_provider("text/plain",
  21109. [&](size_t offset, DataSink &sink) -> bool {
  21110. if (offset < expected_body.size()) {
  21111. sink.write(expected_body.data() + offset,
  21112. expected_body.size() - offset);
  21113. }
  21114. sink.done();
  21115. return true;
  21116. });
  21117. });
  21118. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21119. auto se = detail::scope_exit([&] {
  21120. svr.stop();
  21121. listen_thread.join();
  21122. ASSERT_FALSE(svr.is_running());
  21123. });
  21124. svr.wait_until_ready();
  21125. SSLClient cli(HOST, PORT);
  21126. cli.enable_server_certificate_verification(false);
  21127. auto res = cli.Get("/no-content-length");
  21128. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21129. EXPECT_EQ(StatusCode::OK_200, res->status);
  21130. EXPECT_EQ(expected_body, res->body);
  21131. }
  21132. #endif // CPPHTTPLIB_SSL_ENABLED
  21133. //==============================================================================
  21134. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21135. // results for various scenarios.
  21136. //==============================================================================
  21137. TEST(ParityTest, GetVsOpenStream) {
  21138. Server svr;
  21139. const std::string path = "/parity";
  21140. const std::string content = "Parity test content: hello world";
  21141. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21142. res.set_content(content, "text/plain");
  21143. });
  21144. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21145. auto se = detail::scope_exit([&] {
  21146. svr.stop();
  21147. t.join();
  21148. ASSERT_FALSE(svr.is_running());
  21149. });
  21150. svr.wait_until_ready();
  21151. Client cli(HOST, PORT);
  21152. // Non-stream path
  21153. auto r1 = cli.Get(path);
  21154. ASSERT_TRUE(r1);
  21155. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21156. // Stream path
  21157. auto h = cli.open_stream("GET", path);
  21158. ASSERT_TRUE(h.is_valid());
  21159. EXPECT_EQ(r1->body, read_all(h));
  21160. }
  21161. // Helper to compress data with provided compressor type T
  21162. template <typename Compressor>
  21163. static std::string compress_payload_for_parity(const std::string &in) {
  21164. std::string out;
  21165. Compressor compressor;
  21166. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21167. [&](const char *data, size_t n) {
  21168. out.append(data, n);
  21169. return true;
  21170. });
  21171. EXPECT_TRUE(ok);
  21172. return out;
  21173. }
  21174. // Helper function for compression parity tests
  21175. template <typename Compressor>
  21176. static void test_compression_parity(const std::string &original,
  21177. const std::string &path,
  21178. const std::string &encoding) {
  21179. const std::string compressed =
  21180. compress_payload_for_parity<Compressor>(original);
  21181. Server svr;
  21182. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21183. res.set_content(compressed, "application/octet-stream");
  21184. res.set_header("Content-Encoding", encoding);
  21185. });
  21186. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21187. auto se = detail::scope_exit([&] {
  21188. svr.stop();
  21189. t.join();
  21190. ASSERT_FALSE(svr.is_running());
  21191. });
  21192. svr.wait_until_ready();
  21193. Client cli(HOST, PORT);
  21194. // Non-streaming
  21195. {
  21196. auto res = cli.Get(path);
  21197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21198. EXPECT_EQ(StatusCode::OK_200, res->status);
  21199. EXPECT_EQ(original, res->body);
  21200. }
  21201. // Streaming
  21202. {
  21203. auto h = cli.open_stream("GET", path);
  21204. ASSERT_TRUE(h.is_valid());
  21205. EXPECT_EQ(original, read_all(h));
  21206. }
  21207. }
  21208. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21209. TEST(ParityTest, Gzip) {
  21210. test_compression_parity<detail::gzip_compressor>(
  21211. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21212. }
  21213. #endif
  21214. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21215. TEST(ParityTest, Brotli) {
  21216. test_compression_parity<detail::brotli_compressor>(
  21217. "Hello, brotli parity test payload", "/parity-br", "br");
  21218. }
  21219. #endif
  21220. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21221. TEST(ParityTest, Zstd) {
  21222. test_compression_parity<detail::zstd_compressor>(
  21223. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21224. }
  21225. #endif
  21226. //==============================================================================
  21227. // New Stream API Tests
  21228. //==============================================================================
  21229. inline std::string read_body(httplib::stream::Result &result) {
  21230. std::string body;
  21231. while (result.next()) {
  21232. body.append(result.data(), result.size());
  21233. }
  21234. return body;
  21235. }
  21236. TEST(ClientConnectionTest, Basic) {
  21237. httplib::ClientConnection conn;
  21238. EXPECT_FALSE(conn.is_open());
  21239. conn.sock = 1;
  21240. EXPECT_TRUE(conn.is_open());
  21241. httplib::ClientConnection conn2(std::move(conn));
  21242. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21243. conn2.sock = INVALID_SOCKET;
  21244. }
  21245. // Unified test server for all stream::* tests
  21246. class StreamApiTest : public ::testing::Test {
  21247. protected:
  21248. void SetUp() override {
  21249. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21250. res.set_content("Hello World!", "text/plain");
  21251. });
  21252. svr_.Get("/echo-params",
  21253. [](const httplib::Request &req, httplib::Response &res) {
  21254. std::string r;
  21255. for (const auto &p : req.params) {
  21256. if (!r.empty()) r += "&";
  21257. r += p.first + "=" + p.second;
  21258. }
  21259. res.set_content(r, "text/plain");
  21260. });
  21261. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21262. res.set_content(req.body, req.get_header_value("Content-Type"));
  21263. });
  21264. svr_.Post("/echo-headers",
  21265. [](const httplib::Request &req, httplib::Response &res) {
  21266. std::string r;
  21267. for (const auto &h : req.headers)
  21268. r += h.first + ": " + h.second + "\n";
  21269. res.set_content(r, "text/plain");
  21270. });
  21271. svr_.Post("/echo-params",
  21272. [](const httplib::Request &req, httplib::Response &res) {
  21273. std::string r = "params:";
  21274. for (const auto &p : req.params)
  21275. r += p.first + "=" + p.second + ";";
  21276. res.set_content(r + " body:" + req.body, "text/plain");
  21277. });
  21278. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21279. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21280. });
  21281. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21282. res.set_content("PUT:" + req.body, "text/plain");
  21283. });
  21284. svr_.Patch("/echo",
  21285. [](const httplib::Request &req, httplib::Response &res) {
  21286. res.set_content("PATCH:" + req.body, "text/plain");
  21287. });
  21288. svr_.Delete(
  21289. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21290. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21291. "text/plain");
  21292. });
  21293. svr_.Get("/head-test",
  21294. [](const httplib::Request &, httplib::Response &res) {
  21295. res.set_content("body for HEAD", "text/plain");
  21296. });
  21297. svr_.Options("/options",
  21298. [](const httplib::Request &, httplib::Response &res) {
  21299. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21300. });
  21301. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21302. svr_.wait_until_ready();
  21303. }
  21304. void TearDown() override {
  21305. svr_.stop();
  21306. if (thread_.joinable()) thread_.join();
  21307. }
  21308. httplib::Server svr_;
  21309. std::thread thread_;
  21310. };
  21311. // stream::Get tests
  21312. TEST_F(StreamApiTest, GetBasic) {
  21313. httplib::Client cli(HOST, PORT);
  21314. auto result = httplib::stream::Get(cli, "/hello");
  21315. ASSERT_TRUE(result.is_valid());
  21316. EXPECT_EQ(200, result.status());
  21317. EXPECT_EQ("Hello World!", read_body(result));
  21318. }
  21319. TEST_F(StreamApiTest, GetWithParams) {
  21320. httplib::Client cli(HOST, PORT);
  21321. httplib::Params params{{"foo", "bar"}};
  21322. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21323. ASSERT_TRUE(result.is_valid());
  21324. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21325. }
  21326. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21327. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21328. httplib::Client cli(HOST, PORT);
  21329. cli.set_payload_max_length(0);
  21330. auto result = httplib::stream::Get(cli, "/hello");
  21331. ASSERT_TRUE(result.is_valid());
  21332. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21333. EXPECT_EQ("Hello World!", read_body(result));
  21334. }
  21335. #endif
  21336. TEST_F(StreamApiTest, GetConnectionError) {
  21337. httplib::Client cli(HOST, 9999);
  21338. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21339. }
  21340. TEST_F(StreamApiTest, Get404) {
  21341. httplib::Client cli(HOST, PORT);
  21342. auto result = httplib::stream::Get(cli, "/nonexistent");
  21343. EXPECT_TRUE(result.is_valid());
  21344. EXPECT_EQ(404, result.status());
  21345. }
  21346. // stream::Post tests
  21347. TEST_F(StreamApiTest, PostBasic) {
  21348. httplib::Client cli(HOST, PORT);
  21349. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21350. "application/json");
  21351. ASSERT_TRUE(result.is_valid());
  21352. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21353. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21354. }
  21355. TEST_F(StreamApiTest, PostWithHeaders) {
  21356. httplib::Client cli(HOST, PORT);
  21357. httplib::Headers headers{{"X-Custom", "value"}};
  21358. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21359. "text/plain");
  21360. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21361. }
  21362. TEST_F(StreamApiTest, PostWithParams) {
  21363. httplib::Client cli(HOST, PORT);
  21364. httplib::Params params{{"k", "v"}};
  21365. auto result =
  21366. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21367. auto body = read_body(result);
  21368. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21369. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21370. }
  21371. TEST_F(StreamApiTest, PostLarge) {
  21372. httplib::Client cli(HOST, PORT);
  21373. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21374. size_t total = 0;
  21375. while (result.next()) {
  21376. total += result.size();
  21377. }
  21378. EXPECT_EQ(100u * 1024u, total);
  21379. }
  21380. // stream::Put/Patch tests
  21381. TEST_F(StreamApiTest, PutAndPatch) {
  21382. httplib::Client cli(HOST, PORT);
  21383. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21384. EXPECT_EQ("PUT:test", read_body(put));
  21385. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21386. EXPECT_EQ("PATCH:test", read_body(patch));
  21387. }
  21388. // stream::Delete tests
  21389. TEST_F(StreamApiTest, Delete) {
  21390. httplib::Client cli(HOST, PORT);
  21391. auto del1 = httplib::stream::Delete(cli, "/resource");
  21392. EXPECT_EQ("Deleted", read_body(del1));
  21393. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21394. EXPECT_EQ("Deleted:data", read_body(del2));
  21395. }
  21396. // stream::Head/Options tests
  21397. TEST_F(StreamApiTest, HeadAndOptions) {
  21398. httplib::Client cli(HOST, PORT);
  21399. auto head = httplib::stream::Head(cli, "/head-test");
  21400. EXPECT_TRUE(head.is_valid());
  21401. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21402. auto opts = httplib::stream::Options(cli, "/options");
  21403. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21404. }
  21405. // SSL stream::* tests
  21406. #ifdef CPPHTTPLIB_SSL_ENABLED
  21407. class SSLStreamApiTest : public ::testing::Test {
  21408. protected:
  21409. void SetUp() override {
  21410. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21411. res.set_content("Hello SSL!", "text/plain");
  21412. });
  21413. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21414. res.set_content(req.body, "text/plain");
  21415. });
  21416. port_ = svr_.bind_to_any_port("127.0.0.1");
  21417. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21418. svr_.wait_until_ready();
  21419. }
  21420. void TearDown() override {
  21421. svr_.stop();
  21422. if (thread_.joinable()) thread_.join();
  21423. }
  21424. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21425. std::thread thread_;
  21426. int port_ = 0;
  21427. };
  21428. TEST_F(SSLStreamApiTest, GetAndPost) {
  21429. httplib::SSLClient cli("127.0.0.1", port_);
  21430. cli.enable_server_certificate_verification(false);
  21431. auto get = httplib::stream::Get(cli, "/hello");
  21432. EXPECT_EQ("Hello SSL!", read_body(get));
  21433. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21434. EXPECT_EQ("test", read_body(post));
  21435. }
  21436. #endif
  21437. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21438. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21439. // BodyReader
  21440. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21441. // Test that read timeout during streaming is detected
  21442. // Use a large content-length response where server delays mid-stream
  21443. Server svr;
  21444. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21445. // Send a large response with delay in the middle
  21446. res.set_content_provider(
  21447. 1000, // content_length
  21448. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21449. if (offset < 100) {
  21450. // Send first 100 bytes immediately
  21451. std::string data(100, 'A');
  21452. sink.write(data.c_str(), data.size());
  21453. return true;
  21454. }
  21455. // Then delay longer than client timeout
  21456. std::this_thread::sleep_for(std::chrono::seconds(3));
  21457. std::string data(900, 'B');
  21458. sink.write(data.c_str(), data.size());
  21459. return true;
  21460. });
  21461. });
  21462. auto port = 8091;
  21463. std::thread t([&]() { svr.listen("localhost", port); });
  21464. svr.wait_until_ready();
  21465. Client cli("localhost", port);
  21466. cli.set_read_timeout(1, 0); // 1 second timeout
  21467. auto handle = cli.open_stream("GET", "/slow-stream");
  21468. ASSERT_TRUE(handle.is_valid());
  21469. char buf[256];
  21470. ssize_t total = 0;
  21471. ssize_t n;
  21472. bool got_error = false;
  21473. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21474. total += n;
  21475. }
  21476. if (n < 0) {
  21477. got_error = true;
  21478. // Should be timeout or read error
  21479. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21480. handle.get_read_error() == Error::Read)
  21481. << "Actual error: " << to_string(handle.get_read_error());
  21482. }
  21483. // Either we got an error, or we got less data than expected
  21484. EXPECT_TRUE(got_error || total < 1000)
  21485. << "Expected timeout but got all " << total << " bytes";
  21486. svr.stop();
  21487. t.join();
  21488. }
  21489. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21490. // Test connection closed detection via BodyReader
  21491. Server svr;
  21492. std::atomic<bool> close_now{false};
  21493. svr.Get("/will-close", [&](const Request &, Response &res) {
  21494. res.set_content_provider(
  21495. 10000, // Large content_length that we won't fully send
  21496. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21497. if (offset < 100) {
  21498. std::string data(100, 'X');
  21499. sink.write(data.c_str(), data.size());
  21500. return true;
  21501. }
  21502. // Wait for signal then abort
  21503. while (!close_now) {
  21504. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21505. }
  21506. return false; // Abort - server will close connection
  21507. });
  21508. });
  21509. auto port = 8092;
  21510. std::thread t([&]() { svr.listen("localhost", port); });
  21511. svr.wait_until_ready();
  21512. Client cli("localhost", port);
  21513. auto handle = cli.open_stream("GET", "/will-close");
  21514. ASSERT_TRUE(handle.is_valid());
  21515. char buf[256];
  21516. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21517. EXPECT_GT(n, 0) << "First read should succeed";
  21518. // Signal server to close
  21519. close_now = true;
  21520. // Keep reading until error or EOF
  21521. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21522. // Keep reading
  21523. }
  21524. // Should get an error since content_length wasn't satisfied
  21525. if (n < 0) {
  21526. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21527. handle.get_read_error() == Error::Read)
  21528. << "Actual error: " << to_string(handle.get_read_error());
  21529. }
  21530. svr.stop();
  21531. t.join();
  21532. }
  21533. #ifdef CPPHTTPLIB_SSL_ENABLED
  21534. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21535. // Test that read timeout during SSL streaming is detected
  21536. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21537. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21538. res.set_content_provider(
  21539. 1000, "text/plain",
  21540. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21541. if (offset < 100) {
  21542. std::string data(100, 'A');
  21543. sink.write(data.c_str(), data.size());
  21544. return true;
  21545. }
  21546. std::this_thread::sleep_for(std::chrono::seconds(3));
  21547. std::string data(900, 'B');
  21548. sink.write(data.c_str(), data.size());
  21549. return true;
  21550. });
  21551. });
  21552. auto port = 8093;
  21553. std::thread t([&]() { svr.listen("localhost", port); });
  21554. svr.wait_until_ready();
  21555. SSLClient cli("localhost", port);
  21556. cli.enable_server_certificate_verification(false);
  21557. cli.set_read_timeout(1, 0); // 1 second timeout
  21558. auto handle = cli.open_stream("GET", "/slow-stream");
  21559. ASSERT_TRUE(handle.is_valid());
  21560. char buf[256];
  21561. ssize_t total = 0;
  21562. ssize_t n;
  21563. bool got_error = false;
  21564. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21565. total += n;
  21566. }
  21567. if (n < 0) {
  21568. got_error = true;
  21569. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21570. handle.get_read_error() == Error::Read)
  21571. << "Actual error: " << to_string(handle.get_read_error());
  21572. }
  21573. EXPECT_TRUE(got_error || total < 1000)
  21574. << "Expected timeout but got all " << total << " bytes";
  21575. svr.stop();
  21576. t.join();
  21577. }
  21578. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21579. // Test SSL connection closed detection
  21580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21581. std::atomic<bool> close_now{false};
  21582. svr.Get("/will-close", [&](const Request &, Response &res) {
  21583. res.set_content_provider(
  21584. 10000, "text/plain",
  21585. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21586. if (offset < 100) {
  21587. std::string data(100, 'X');
  21588. sink.write(data.c_str(), data.size());
  21589. return true;
  21590. }
  21591. while (!close_now) {
  21592. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21593. }
  21594. return false;
  21595. });
  21596. });
  21597. auto port = 8094;
  21598. std::thread t([&]() { svr.listen("localhost", port); });
  21599. svr.wait_until_ready();
  21600. SSLClient cli("localhost", port);
  21601. cli.enable_server_certificate_verification(false);
  21602. auto handle = cli.open_stream("GET", "/will-close");
  21603. ASSERT_TRUE(handle.is_valid());
  21604. char buf[256];
  21605. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21606. EXPECT_GT(n, 0);
  21607. // Signal server to close
  21608. close_now = true;
  21609. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21610. // Keep reading
  21611. }
  21612. if (n < 0) {
  21613. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21614. handle.get_read_error() == Error::Read)
  21615. << "Actual error: " << to_string(handle.get_read_error());
  21616. }
  21617. svr.stop();
  21618. t.join();
  21619. }
  21620. #endif
  21621. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21622. using namespace httplib;
  21623. // Create a test file
  21624. const char *fname = "etag_testfile.txt";
  21625. const char *content = "etag-content";
  21626. {
  21627. std::ofstream ofs(fname);
  21628. ofs << content;
  21629. ASSERT_TRUE(ofs.good());
  21630. }
  21631. Server svr;
  21632. svr.set_mount_point("/static", ".");
  21633. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21634. svr.wait_until_ready();
  21635. Client cli(HOST, PORT);
  21636. // First request: should get 200 with ETag header
  21637. auto res1 = cli.Get("/static/etag_testfile.txt");
  21638. ASSERT_TRUE(res1);
  21639. ASSERT_EQ(200, res1->status);
  21640. ASSERT_TRUE(res1->has_header("ETag"));
  21641. std::string etag = res1->get_header_value("ETag");
  21642. EXPECT_FALSE(etag.empty());
  21643. // Verify ETag format: W/"hex-hex"
  21644. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21645. EXPECT_EQ('W', etag[0]);
  21646. EXPECT_EQ('/', etag[1]);
  21647. EXPECT_EQ('"', etag[2]);
  21648. EXPECT_EQ('"', etag.back());
  21649. // Exact match: expect 304 Not Modified
  21650. Headers h2 = {{"If-None-Match", etag}};
  21651. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21652. ASSERT_TRUE(res2);
  21653. EXPECT_EQ(304, res2->status);
  21654. // Wildcard match: expect 304 Not Modified
  21655. Headers h3 = {{"If-None-Match", "*"}};
  21656. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21657. ASSERT_TRUE(res3);
  21658. EXPECT_EQ(304, res3->status);
  21659. // Non-matching ETag: expect 200
  21660. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21661. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21662. ASSERT_TRUE(res4);
  21663. EXPECT_EQ(200, res4->status);
  21664. // Multiple ETags with one matching: expect 304
  21665. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21666. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21667. ASSERT_TRUE(res5);
  21668. EXPECT_EQ(304, res5->status);
  21669. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21670. // that equivalent to the single comma-separated list above, so the match on
  21671. // the second line must still be found.
  21672. Headers h6;
  21673. h6.emplace("If-None-Match", "W/\"other\"");
  21674. h6.emplace("If-None-Match", etag);
  21675. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21676. ASSERT_TRUE(res6);
  21677. EXPECT_EQ(304, res6->status);
  21678. svr.stop();
  21679. t.join();
  21680. std::remove(fname);
  21681. }
  21682. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21683. using namespace httplib;
  21684. Server svr;
  21685. svr.set_mount_point("/static", ".");
  21686. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21687. svr.wait_until_ready();
  21688. Client cli(HOST, PORT);
  21689. // Send If-None-Match: * to a non-existent file
  21690. Headers h = {{"If-None-Match", "*"}};
  21691. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21693. EXPECT_EQ(404, res->status);
  21694. svr.stop();
  21695. t.join();
  21696. }
  21697. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21698. using namespace httplib;
  21699. // Create a test file
  21700. const char *fname = "etag_boundary_testfile.txt";
  21701. const char *content = "boundary-test";
  21702. {
  21703. std::ofstream ofs(fname);
  21704. ofs << content;
  21705. ASSERT_TRUE(ofs.good());
  21706. }
  21707. Server svr;
  21708. svr.set_mount_point("/static", ".");
  21709. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21710. svr.wait_until_ready();
  21711. Client cli(HOST, PORT);
  21712. // Get the actual ETag
  21713. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21714. ASSERT_TRUE(res1);
  21715. ASSERT_EQ(200, res1->status);
  21716. ASSERT_TRUE(res1->has_header("ETag"));
  21717. std::string etag = res1->get_header_value("ETag");
  21718. // Test 1: Very long ETag value (longer than actual ETag)
  21719. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21720. Headers h1 = {{"If-None-Match", "W/"
  21721. "\"very-long-etag-value-that-is-much-longer-"
  21722. "than-the-actual-etag-value\""}};
  21723. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21724. ASSERT_TRUE(res2);
  21725. EXPECT_EQ(200, res2->status); // Should not match
  21726. // Test 2: Long string followed by wildcard
  21727. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21728. // string)
  21729. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21730. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21731. ASSERT_TRUE(res3);
  21732. EXPECT_EQ(304, res3->status); // Should match on "*"
  21733. // Test 3: Wildcard followed by long string
  21734. // Should match on "*" immediately and return 304
  21735. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21736. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21737. ASSERT_TRUE(res4);
  21738. EXPECT_EQ(304, res4->status); // Should match on "*"
  21739. // Test 4: Multiple long non-matching values
  21740. // Should NOT match and return 200 (test that all comparisons are safe)
  21741. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21742. "W/\"second-long-non-matching-value\", "
  21743. "W/\"third-long-non-matching-value\""}};
  21744. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21745. ASSERT_TRUE(res5);
  21746. EXPECT_EQ(200, res5->status); // Should not match
  21747. // Test 5: Single character that is not "*" (edge case)
  21748. Headers h5 = {{"If-None-Match", "X"}};
  21749. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21750. ASSERT_TRUE(res6);
  21751. EXPECT_EQ(200, res6->status); // Should not match
  21752. svr.stop();
  21753. t.join();
  21754. std::remove(fname);
  21755. }
  21756. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21757. using namespace httplib;
  21758. // Create a test file
  21759. const char *fname = "ims_testfile.txt";
  21760. const char *content = "if-modified-since-test";
  21761. {
  21762. std::ofstream ofs(fname);
  21763. ofs << content;
  21764. ASSERT_TRUE(ofs.good());
  21765. }
  21766. Server svr;
  21767. svr.set_mount_point("/static", ".");
  21768. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21769. svr.wait_until_ready();
  21770. Client cli(HOST, PORT);
  21771. // First request: should get 200 with Last-Modified header
  21772. auto res1 = cli.Get("/static/ims_testfile.txt");
  21773. ASSERT_TRUE(res1);
  21774. ASSERT_EQ(200, res1->status);
  21775. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21776. std::string last_modified = res1->get_header_value("Last-Modified");
  21777. EXPECT_FALSE(last_modified.empty());
  21778. // If-Modified-Since with same time: expect 304
  21779. Headers h2 = {{"If-Modified-Since", last_modified}};
  21780. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21781. ASSERT_TRUE(res2);
  21782. EXPECT_EQ(304, res2->status);
  21783. // If-Modified-Since with future time: expect 304
  21784. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21785. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21786. ASSERT_TRUE(res3);
  21787. EXPECT_EQ(304, res3->status);
  21788. // If-Modified-Since with past time: expect 200
  21789. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21790. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21791. ASSERT_TRUE(res4);
  21792. EXPECT_EQ(200, res4->status);
  21793. // If-None-Match takes precedence over If-Modified-Since
  21794. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21795. ASSERT_TRUE(res1->has_header("ETag"));
  21796. std::string etag = res1->get_header_value("ETag");
  21797. Headers h5 = {{"If-None-Match", etag},
  21798. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21799. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21800. ASSERT_TRUE(res5);
  21801. EXPECT_EQ(304, res5->status);
  21802. svr.stop();
  21803. t.join();
  21804. std::remove(fname);
  21805. }
  21806. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21807. using namespace httplib;
  21808. Server svr;
  21809. // Endpoint that returns compressible content
  21810. svr.Get("/compressible", [](const Request &, Response &res) {
  21811. // Return a large enough body to trigger compression
  21812. std::string body(1000, 'a');
  21813. res.set_content(body, "text/plain");
  21814. });
  21815. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21816. svr.wait_until_ready();
  21817. Client cli(HOST, PORT);
  21818. // Request with gzip support: should get Vary header when compressed
  21819. cli.set_compress(true);
  21820. auto res1 = cli.Get("/compressible");
  21821. ASSERT_TRUE(res1);
  21822. EXPECT_EQ(200, res1->status);
  21823. // If Content-Encoding is set, Vary should also be set
  21824. if (res1->has_header("Content-Encoding")) {
  21825. EXPECT_TRUE(res1->has_header("Vary"));
  21826. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21827. }
  21828. // Request without Accept-Encoding header: should not have compression
  21829. Headers h_no_compress;
  21830. auto res2 = cli.Get("/compressible", h_no_compress);
  21831. ASSERT_TRUE(res2);
  21832. EXPECT_EQ(200, res2->status);
  21833. // Verify Vary header is present when compression is applied
  21834. // (the exact behavior depends on server configuration)
  21835. svr.stop();
  21836. t.join();
  21837. }
  21838. TEST(ETagTest, IfRangeWithETag) {
  21839. using namespace httplib;
  21840. // Create a test file with known content
  21841. const char *fname = "if_range_testfile.txt";
  21842. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21843. {
  21844. std::ofstream ofs(fname);
  21845. ofs << content;
  21846. ASSERT_TRUE(ofs.good());
  21847. }
  21848. Server svr;
  21849. svr.set_mount_point("/static", ".");
  21850. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21851. svr.wait_until_ready();
  21852. Client cli(HOST, PORT);
  21853. // First request: get ETag
  21854. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21855. ASSERT_TRUE(res1);
  21856. ASSERT_EQ(200, res1->status);
  21857. ASSERT_TRUE(res1->has_header("ETag"));
  21858. std::string etag = res1->get_header_value("ETag");
  21859. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21860. // Since our server generates weak ETags (W/"..."), If-Range with our
  21861. // ETag should NOT result in partial content - it should return full content.
  21862. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21863. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21864. ASSERT_TRUE(res2);
  21865. // Weak ETag in If-Range -> full content (200), not partial (206)
  21866. EXPECT_EQ(200, res2->status);
  21867. EXPECT_EQ(content, res2->body);
  21868. EXPECT_FALSE(res2->has_header("Content-Range"));
  21869. // Range request with non-matching If-Range (ETag): should get 200 (full
  21870. // content)
  21871. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21872. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21873. ASSERT_TRUE(res3);
  21874. EXPECT_EQ(200, res3->status);
  21875. EXPECT_EQ(content, res3->body);
  21876. EXPECT_FALSE(res3->has_header("Content-Range"));
  21877. // Range request with strong ETag (hypothetical - our server doesn't generate
  21878. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21879. // should return full content)
  21880. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21881. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21882. ASSERT_TRUE(res4);
  21883. EXPECT_EQ(200, res4->status);
  21884. EXPECT_EQ(content, res4->body);
  21885. EXPECT_FALSE(res4->has_header("Content-Range"));
  21886. svr.stop();
  21887. t.join();
  21888. std::remove(fname);
  21889. }
  21890. TEST(ETagTest, IfRangeWithDate) {
  21891. using namespace httplib;
  21892. // Create a test file
  21893. const char *fname = "if_range_date_testfile.txt";
  21894. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21895. {
  21896. std::ofstream ofs(fname);
  21897. ofs << content;
  21898. ASSERT_TRUE(ofs.good());
  21899. }
  21900. Server svr;
  21901. svr.set_mount_point("/static", ".");
  21902. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21903. svr.wait_until_ready();
  21904. Client cli(HOST, PORT);
  21905. // First request: get Last-Modified
  21906. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21907. ASSERT_TRUE(res1);
  21908. ASSERT_EQ(200, res1->status);
  21909. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21910. std::string last_modified = res1->get_header_value("Last-Modified");
  21911. // Range request with matching If-Range (date): should get 206
  21912. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21913. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21914. ASSERT_TRUE(res2);
  21915. EXPECT_EQ(206, res2->status);
  21916. EXPECT_EQ("FGHIJ", res2->body);
  21917. // Range request with old If-Range date: should get 200 (full content)
  21918. Headers h3 = {{"Range", "bytes=5-9"},
  21919. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21920. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21921. ASSERT_TRUE(res3);
  21922. EXPECT_EQ(200, res3->status);
  21923. EXPECT_EQ(content, res3->body);
  21924. // Range request with future If-Range date: should get 206
  21925. Headers h4 = {{"Range", "bytes=0-4"},
  21926. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21927. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21928. ASSERT_TRUE(res4);
  21929. EXPECT_EQ(206, res4->status);
  21930. EXPECT_EQ("ABCDE", res4->body);
  21931. svr.stop();
  21932. t.join();
  21933. std::remove(fname);
  21934. }
  21935. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21936. using namespace httplib;
  21937. const char *fname = "etag_malformed.txt";
  21938. const char *content = "malformed-etag";
  21939. {
  21940. std::ofstream ofs(fname);
  21941. ofs << content;
  21942. ASSERT_TRUE(ofs.good());
  21943. }
  21944. Server svr;
  21945. svr.set_mount_point("/static", ".");
  21946. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21947. svr.wait_until_ready();
  21948. Client cli(HOST, PORT);
  21949. // baseline: should get 200 and an ETag
  21950. auto res1 = cli.Get("/static/etag_malformed.txt");
  21951. ASSERT_TRUE(res1);
  21952. ASSERT_EQ(200, res1->status);
  21953. ASSERT_TRUE(res1->has_header("ETag"));
  21954. // Malformed ETag value (missing quotes) should be treated as non-matching
  21955. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21956. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21957. ASSERT_TRUE(res_bad);
  21958. EXPECT_EQ(200, res_bad->status);
  21959. // Whitespace-only header value should be considered invalid / non-matching
  21960. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21961. "Host: localhost\r\n"
  21962. "If-None-Match: \r\n"
  21963. "Connection: close\r\n"
  21964. "\r\n";
  21965. std::string out;
  21966. ASSERT_TRUE(send_request(5, raw_req, &out));
  21967. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21968. svr.stop();
  21969. t.join();
  21970. std::remove(fname);
  21971. }
  21972. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21973. using namespace httplib;
  21974. const char *fname = "ims_invalid_format.txt";
  21975. const char *content = "ims-bad-format";
  21976. {
  21977. std::ofstream ofs(fname);
  21978. ofs << content;
  21979. ASSERT_TRUE(ofs.good());
  21980. }
  21981. Server svr;
  21982. svr.set_mount_point("/static", ".");
  21983. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21984. svr.wait_until_ready();
  21985. Client cli(HOST, PORT);
  21986. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21987. ASSERT_TRUE(res1);
  21988. ASSERT_EQ(200, res1->status);
  21989. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21990. // If-Modified-Since with invalid format should not result in 304
  21991. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21992. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21993. ASSERT_TRUE(res_bad);
  21994. EXPECT_EQ(200, res_bad->status);
  21995. // If-Range with invalid date format should be treated as mismatch -> full
  21996. // content (200)
  21997. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21998. {"If-Range", "invalid-date"}};
  21999. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22000. ASSERT_TRUE(res_ifrange);
  22001. EXPECT_EQ(200, res_ifrange->status);
  22002. svr.stop();
  22003. t.join();
  22004. std::remove(fname);
  22005. }
  22006. TEST(ETagTest, IfRangeWithMalformedETag) {
  22007. using namespace httplib;
  22008. const char *fname = "ifrange_malformed.txt";
  22009. const std::string content = "0123456789";
  22010. {
  22011. std::ofstream ofs(fname);
  22012. ofs << content;
  22013. ASSERT_TRUE(ofs.good());
  22014. }
  22015. Server svr;
  22016. svr.set_mount_point("/static", ".");
  22017. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22018. svr.wait_until_ready();
  22019. Client cli(HOST, PORT);
  22020. // First request: get ETag
  22021. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22022. ASSERT_TRUE(res1);
  22023. ASSERT_EQ(200, res1->status);
  22024. ASSERT_TRUE(res1->has_header("ETag"));
  22025. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22026. // full content (200)
  22027. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22028. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22029. ASSERT_TRUE(res2);
  22030. EXPECT_EQ(200, res2->status);
  22031. EXPECT_EQ(content, res2->body);
  22032. svr.stop();
  22033. t.join();
  22034. std::remove(fname);
  22035. }
  22036. TEST(ETagTest, ExtremeLargeDateValues) {
  22037. using namespace httplib;
  22038. const char *fname = "ims_extreme_date.txt";
  22039. const char *content = "ims-extreme-date";
  22040. {
  22041. std::ofstream ofs(fname);
  22042. ofs << content;
  22043. ASSERT_TRUE(ofs.good());
  22044. }
  22045. Server svr;
  22046. svr.set_mount_point("/static", ".");
  22047. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22048. svr.wait_until_ready();
  22049. Client cli(HOST, PORT);
  22050. auto res1 = cli.Get(std::string("/static/") + fname);
  22051. ASSERT_TRUE(res1);
  22052. ASSERT_EQ(200, res1->status);
  22053. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22054. // Extremely large year that may overflow date parsing routines.
  22055. Headers h_large_date = {
  22056. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22057. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22058. ASSERT_TRUE(res_bad);
  22059. // Expect server to treat this as invalid/mismatch and return full content
  22060. EXPECT_EQ(200, res_bad->status);
  22061. // If-Range with extremely large date should be treated as mismatch -> full
  22062. // content (200)
  22063. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22064. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22065. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22066. ASSERT_TRUE(res_ifrange);
  22067. EXPECT_EQ(200, res_ifrange->status);
  22068. svr.stop();
  22069. t.join();
  22070. std::remove(fname);
  22071. }
  22072. TEST(ETagTest, NegativeFileModificationTime) {
  22073. using namespace httplib;
  22074. const char *fname = "ims_negative_mtime.txt";
  22075. const std::string content = "negative-mtime";
  22076. {
  22077. std::ofstream ofs(fname);
  22078. ofs << content;
  22079. ASSERT_TRUE(ofs.good());
  22080. }
  22081. // Try to set file mtime to a negative value. This may fail on some
  22082. // platforms/filesystems; if it fails, the test will still verify server
  22083. // behaves safely by performing a regular conditional request.
  22084. #if defined(__APPLE__) || defined(__linux__)
  22085. bool set_negative = false;
  22086. do {
  22087. struct timeval times[2];
  22088. // access time: now
  22089. times[0].tv_sec = time(nullptr);
  22090. times[0].tv_usec = 0;
  22091. // modification time: negative (e.g., -1)
  22092. times[1].tv_sec = -1;
  22093. times[1].tv_usec = 0;
  22094. if (utimes(fname, times) == 0) { set_negative = true; }
  22095. } while (0);
  22096. #else
  22097. bool set_negative = false;
  22098. #endif
  22099. Server svr;
  22100. svr.set_mount_point("/static", ".");
  22101. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22102. svr.wait_until_ready();
  22103. Client cli(HOST, PORT);
  22104. auto res1 = cli.Get(std::string("/static/") + fname);
  22105. ASSERT_TRUE(res1);
  22106. ASSERT_EQ(200, res1->status);
  22107. bool has_last_modified = res1->has_header("Last-Modified");
  22108. std::string last_modified;
  22109. if (has_last_modified) {
  22110. last_modified = res1->get_header_value("Last-Modified");
  22111. }
  22112. if (set_negative) {
  22113. // If we successfully set a negative mtime, ensure server returns a
  22114. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22115. // with an old date and ensure server handles it without crash.
  22116. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22117. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22118. ASSERT_TRUE(res2);
  22119. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22120. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22121. } else {
  22122. // Could not set negative mtime on this platform; fall back to verifying
  22123. // that normal invalid/malformed dates are treated safely (non-304).
  22124. Headers h_bad_date = {
  22125. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22126. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22127. ASSERT_TRUE(res_bad);
  22128. EXPECT_EQ(200, res_bad->status);
  22129. }
  22130. svr.stop();
  22131. t.join();
  22132. std::remove(fname);
  22133. }
  22134. //==============================================================================
  22135. // Integration Tests with Server
  22136. //==============================================================================
  22137. class SSEIntegrationTest : public ::testing::Test {
  22138. protected:
  22139. void SetUp() override {
  22140. stop_server_.store(false);
  22141. events_.clear();
  22142. server_ = httplib::detail::make_unique<Server>();
  22143. setup_server();
  22144. start_server();
  22145. }
  22146. void TearDown() override {
  22147. stop_server_.store(true);
  22148. event_cv_.notify_all();
  22149. server_->stop();
  22150. if (server_thread_.joinable()) { server_thread_.join(); }
  22151. }
  22152. void setup_server() {
  22153. // Simple SSE endpoint
  22154. server_->Get("/events", [this](const Request &req, Response &res) {
  22155. auto last_id = req.get_header_value("Last-Event-ID");
  22156. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22157. res.set_chunked_content_provider(
  22158. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22159. std::unique_lock<std::mutex> lock(event_mutex_);
  22160. if (event_cv_.wait_for(
  22161. lock, std::chrono::milliseconds(200), [this] {
  22162. return !events_.empty() || stop_server_.load();
  22163. })) {
  22164. if (stop_server_.load()) { return false; }
  22165. if (!events_.empty()) {
  22166. std::string event = events_.front();
  22167. events_.erase(events_.begin());
  22168. sink.write(event.data(), event.size());
  22169. return true;
  22170. }
  22171. }
  22172. return !stop_server_.load();
  22173. });
  22174. });
  22175. // Endpoint that returns error
  22176. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22177. res.status = 500;
  22178. res.set_content("Internal Server Error", "text/plain");
  22179. });
  22180. // Endpoint for custom event types
  22181. server_->Get("/custom-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 event = "event: update\ndata: updated\n\n"
  22186. "event: delete\ndata: deleted\n\n";
  22187. sink.write(event.data(), event.size());
  22188. }
  22189. return false; // End stream after sending
  22190. });
  22191. });
  22192. }
  22193. void start_server() {
  22194. port_ = server_->bind_to_any_port(HOST);
  22195. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22196. // Wait for server to start
  22197. while (!server_->is_running()) {
  22198. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22199. }
  22200. }
  22201. int get_port() const { return port_; }
  22202. void send_event(const std::string &event) {
  22203. std::lock_guard<std::mutex> lock(event_mutex_);
  22204. events_.push_back(event);
  22205. event_cv_.notify_all();
  22206. }
  22207. std::unique_ptr<Server> server_;
  22208. std::thread server_thread_;
  22209. std::mutex event_mutex_;
  22210. std::condition_variable event_cv_;
  22211. std::vector<std::string> events_;
  22212. std::atomic<bool> stop_server_{false};
  22213. std::string last_received_event_id_;
  22214. int port_ = 0;
  22215. };
  22216. //==============================================================================
  22217. // SSE Parsing Tests
  22218. //==============================================================================
  22219. class SSEParsingTest : public SSEIntegrationTest {
  22220. protected:
  22221. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  22222. // A trailing sentinel event tells when the whole stream has been parsed.
  22223. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  22224. auto body = stream + "event: end\ndata: end\n\n";
  22225. server_->Get("/parse", [body](const Request &, Response &res) {
  22226. res.set_content(body, "text/event-stream");
  22227. });
  22228. return collect("/parse");
  22229. }
  22230. // Runs SSEClient against path until an "end" event arrives and returns the
  22231. // messages dispatched before it
  22232. std::vector<sse::SSEMessage> collect(const std::string &path) {
  22233. Client client(HOST, get_port());
  22234. sse::SSEClient sse(client, path);
  22235. std::mutex mutex;
  22236. std::condition_variable cv;
  22237. std::vector<sse::SSEMessage> messages;
  22238. auto done = false;
  22239. sse.on_message([&](const sse::SSEMessage &msg) {
  22240. std::lock_guard<std::mutex> lock(mutex);
  22241. // Ignore a replay from a reconnect that races with stop()
  22242. if (!done) { messages.push_back(msg); }
  22243. });
  22244. sse.on_event("end", [&](const sse::SSEMessage &) {
  22245. std::lock_guard<std::mutex> lock(mutex);
  22246. done = true;
  22247. cv.notify_all();
  22248. });
  22249. sse.set_reconnect_interval(100);
  22250. sse.start_async();
  22251. {
  22252. std::unique_lock<std::mutex> lock(mutex);
  22253. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  22254. }
  22255. sse.stop();
  22256. EXPECT_TRUE(done);
  22257. return messages;
  22258. }
  22259. };
  22260. TEST_F(SSEParsingTest, SingleLineData) {
  22261. auto msgs = parse("data: hello\n\n");
  22262. ASSERT_EQ(msgs.size(), 1u);
  22263. EXPECT_EQ(msgs[0].data, "hello");
  22264. EXPECT_EQ(msgs[0].event, "message");
  22265. }
  22266. TEST_F(SSEParsingTest, MultiLineData) {
  22267. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  22268. ASSERT_EQ(msgs.size(), 1u);
  22269. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  22270. }
  22271. TEST_F(SSEParsingTest, CustomEventType) {
  22272. auto msgs = parse("event: update\ndata: payload\n\n");
  22273. ASSERT_EQ(msgs.size(), 1u);
  22274. EXPECT_EQ(msgs[0].event, "update");
  22275. EXPECT_EQ(msgs[0].data, "payload");
  22276. }
  22277. TEST_F(SSEParsingTest, EventIdHandling) {
  22278. auto msgs = parse("id: 12345\ndata: test\n\n");
  22279. ASSERT_EQ(msgs.size(), 1u);
  22280. EXPECT_EQ(msgs[0].id, "12345");
  22281. }
  22282. TEST_F(SSEParsingTest, EmptyEventId) {
  22283. auto msgs = parse("id:\ndata: test\n\n");
  22284. ASSERT_EQ(msgs.size(), 1u);
  22285. EXPECT_EQ(msgs[0].id, "");
  22286. }
  22287. TEST_F(SSEParsingTest, CommentsIgnored) {
  22288. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22289. ASSERT_EQ(msgs.size(), 1u);
  22290. EXPECT_EQ(msgs[0].data, "hello");
  22291. EXPECT_EQ(msgs[0].event, "message");
  22292. }
  22293. TEST_F(SSEParsingTest, ColonInValue) {
  22294. auto msgs = parse("data: hello:world:test\n\n");
  22295. ASSERT_EQ(msgs.size(), 1u);
  22296. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22297. }
  22298. TEST_F(SSEParsingTest, FieldNameOnly) {
  22299. // A line without a colon is a field name with an empty value
  22300. auto msgs = parse("data\n\n");
  22301. ASSERT_EQ(msgs.size(), 1u);
  22302. EXPECT_EQ(msgs[0].data, "");
  22303. }
  22304. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22305. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22306. ASSERT_EQ(msgs.size(), 1u);
  22307. EXPECT_EQ(msgs[0].event, "update");
  22308. EXPECT_EQ(msgs[0].data, "hello");
  22309. }
  22310. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22311. auto msgs = parse("data\r\n\r\n");
  22312. ASSERT_EQ(msgs.size(), 1u);
  22313. EXPECT_EQ(msgs[0].data, "");
  22314. }
  22315. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22316. auto msgs = parse("event: update\rdata: hello\r\r");
  22317. ASSERT_EQ(msgs.size(), 1u);
  22318. EXPECT_EQ(msgs[0].event, "update");
  22319. EXPECT_EQ(msgs[0].data, "hello");
  22320. }
  22321. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22322. // Chunk boundaries fall inside every \r\n and right before the first one
  22323. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22324. "\n\r", "\nevent: end\ndata: end\n\n"};
  22325. server_->Get("/split", [chunks](const Request &, Response &res) {
  22326. auto i = std::make_shared<size_t>(0);
  22327. res.set_chunked_content_provider(
  22328. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22329. if (*i == chunks.size()) {
  22330. sink.done();
  22331. } else {
  22332. sink.write(chunks[*i].data(), chunks[*i].size());
  22333. (*i)++;
  22334. }
  22335. return true;
  22336. });
  22337. });
  22338. auto msgs = collect("/split");
  22339. ASSERT_EQ(msgs.size(), 1u);
  22340. EXPECT_EQ(msgs[0].event, "update");
  22341. EXPECT_EQ(msgs[0].data, "hello");
  22342. }
  22343. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22344. // Only a BOM at the start of the stream is ignored
  22345. auto msgs = parse("\xEF\xBB\xBF"
  22346. "data: first\n\n"
  22347. "\xEF\xBB\xBF"
  22348. "data: second\n\n");
  22349. ASSERT_EQ(msgs.size(), 1u);
  22350. EXPECT_EQ(msgs[0].data, "first");
  22351. }
  22352. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22353. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22354. ASSERT_EQ(msgs.size(), 1u);
  22355. EXPECT_EQ(msgs[0].data, "hello");
  22356. EXPECT_EQ(msgs[0].event, "message");
  22357. }
  22358. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22359. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22360. ASSERT_EQ(msgs.size(), 2u);
  22361. EXPECT_EQ(msgs[0].data, "hello");
  22362. EXPECT_EQ(msgs[1].data, "hello");
  22363. }
  22364. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22365. // An event without data is not dispatched, and its type must not leak
  22366. // into the next event
  22367. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22368. ASSERT_EQ(msgs.size(), 1u);
  22369. EXPECT_EQ(msgs[0].event, "message");
  22370. EXPECT_EQ(msgs[0].data, "hello");
  22371. }
  22372. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22373. // Also when the empty field replaces an earlier type
  22374. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22375. ASSERT_EQ(msgs.size(), 2u);
  22376. EXPECT_EQ(msgs[0].event, "message");
  22377. EXPECT_EQ(msgs[1].event, "message");
  22378. }
  22379. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22380. // The first connection sends only an id; the second echoes back the
  22381. // Last-Event-ID it was reconnected with
  22382. std::atomic<int> connection_count{0};
  22383. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22384. if (connection_count++ == 0) {
  22385. res.set_content("id: 42\n\n", "text/event-stream");
  22386. } else {
  22387. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22388. "\n\nevent: end\ndata: end\n\n",
  22389. "text/event-stream");
  22390. }
  22391. });
  22392. auto msgs = collect("/id-only");
  22393. ASSERT_EQ(msgs.size(), 1u);
  22394. EXPECT_EQ(msgs[0].data, "42");
  22395. }
  22396. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22397. // The first connection sets an id and then clears it with an empty one; the
  22398. // second reports whether it was reconnected with a Last-Event-ID
  22399. std::atomic<int> connection_count{0};
  22400. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22401. if (connection_count++ == 0) {
  22402. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22403. "text/event-stream");
  22404. } else {
  22405. res.set_content(
  22406. std::string("data: ") +
  22407. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22408. "\n\nevent: end\ndata: end\n\n",
  22409. "text/event-stream");
  22410. }
  22411. });
  22412. auto msgs = collect("/id-clear");
  22413. ASSERT_EQ(msgs.size(), 3u);
  22414. EXPECT_EQ(msgs[0].id, "1");
  22415. EXPECT_EQ(msgs[1].id, "");
  22416. EXPECT_EQ(msgs[2].data, "not sent");
  22417. }
  22418. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22419. // The first connection sets an id and then sends ids that cannot be carried
  22420. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22421. // with
  22422. std::atomic<int> connection_count{0};
  22423. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22424. if (connection_count++ == 0) {
  22425. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22426. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22427. "text/event-stream");
  22428. } else {
  22429. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22430. "\n\nevent: end\ndata: end\n\n",
  22431. "text/event-stream");
  22432. }
  22433. });
  22434. auto msgs = collect("/id-unsendable");
  22435. ASSERT_EQ(msgs.size(), 1u);
  22436. EXPECT_EQ(msgs[0].data, "42");
  22437. }
  22438. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22439. auto msgs = parse("event: notification\nid: evt-42\n"
  22440. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22441. ASSERT_EQ(msgs.size(), 1u);
  22442. EXPECT_EQ(msgs[0].event, "notification");
  22443. EXPECT_EQ(msgs[0].id, "evt-42");
  22444. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22445. }
  22446. TEST(SSEMessageTest, Clear) {
  22447. sse::SSEMessage msg;
  22448. msg.event = "custom";
  22449. msg.data = "some data";
  22450. msg.id = "123";
  22451. msg.clear();
  22452. EXPECT_EQ(msg.event, "message");
  22453. EXPECT_EQ(msg.data, "");
  22454. EXPECT_EQ(msg.id, "");
  22455. }
  22456. //==============================================================================
  22457. // SSE Integration Tests
  22458. //==============================================================================
  22459. // Test: Successful connection and on_open callback
  22460. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22461. // Add a simple endpoint that sends one event and closes
  22462. server_->Get("/simple-event", [](const Request &, Response &res) {
  22463. res.set_chunked_content_provider(
  22464. "text/event-stream", [](size_t offset, DataSink &sink) {
  22465. if (offset == 0) {
  22466. std::string event = "data: hello\n\n";
  22467. sink.write(event.data(), event.size());
  22468. }
  22469. return false; // Close stream after sending
  22470. });
  22471. });
  22472. Client client("localhost", get_port());
  22473. sse::SSEClient sse(client, "/simple-event");
  22474. std::atomic<bool> open_called{false};
  22475. std::atomic<bool> message_received{false};
  22476. sse.on_open([&open_called]() { open_called.store(true); });
  22477. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22478. if (msg.data == "hello") { message_received.store(true); }
  22479. });
  22480. sse.set_reconnect_interval(100);
  22481. sse.set_max_reconnect_attempts(1);
  22482. // Start async
  22483. sse.start_async();
  22484. // Wait for message to be processed
  22485. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22486. sse.stop();
  22487. EXPECT_TRUE(open_called.load());
  22488. EXPECT_TRUE(message_received.load());
  22489. }
  22490. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22491. // A data line that never ends.
  22492. server_->Get("/endless-line", [](const Request &, Response &res) {
  22493. res.set_chunked_content_provider(
  22494. "text/event-stream", [](size_t offset, DataSink &sink) {
  22495. if (offset == 0) { sink.write("data: ", 6); }
  22496. std::string chunk(64 * 1024, 'A');
  22497. return sink.write(chunk.data(), chunk.size());
  22498. });
  22499. });
  22500. Client client("localhost", get_port());
  22501. sse::SSEClient sse(client, "/endless-line");
  22502. std::atomic<bool> too_long{false};
  22503. sse.on_error([&](Error err) {
  22504. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22505. });
  22506. sse.set_max_reconnect_attempts(1);
  22507. sse.start_async();
  22508. for (int i = 0; i < 500 && !too_long; i++) {
  22509. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22510. }
  22511. sse.stop();
  22512. EXPECT_TRUE(too_long);
  22513. }
  22514. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22515. // Far more in all than the client's payload limit below.
  22516. server_->Get("/many-events", [](const Request &, Response &res) {
  22517. res.set_chunked_content_provider(
  22518. "text/event-stream", [](size_t offset, DataSink &sink) {
  22519. if (offset == 0) {
  22520. std::string events;
  22521. for (int i = 0; i < 1000; i++) {
  22522. events += "data: message\n\n";
  22523. }
  22524. sink.write(events.data(), events.size());
  22525. }
  22526. return false;
  22527. });
  22528. });
  22529. Client client("localhost", get_port());
  22530. client.set_payload_max_length(1024);
  22531. sse::SSEClient sse(client, "/many-events");
  22532. std::atomic<int> messages{0};
  22533. std::atomic<bool> too_large{false};
  22534. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22535. sse.on_error([&](Error err) {
  22536. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22537. });
  22538. sse.set_max_reconnect_attempts(1);
  22539. sse.start_async();
  22540. for (int i = 0; i < 500 && messages < 1000; i++) {
  22541. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22542. }
  22543. sse.stop();
  22544. EXPECT_GE(messages.load(), 1000);
  22545. EXPECT_FALSE(too_large);
  22546. }
  22547. // Test: on_message callback
  22548. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22549. // Endpoint that sends multiple events then closes
  22550. server_->Get("/multi-event", [](const Request &, Response &res) {
  22551. res.set_chunked_content_provider(
  22552. "text/event-stream", [](size_t offset, DataSink &sink) {
  22553. if (offset == 0) {
  22554. std::string events = "data: message1\n\ndata: message2\n\n";
  22555. sink.write(events.data(), events.size());
  22556. }
  22557. return false;
  22558. });
  22559. });
  22560. Client client("localhost", get_port());
  22561. sse::SSEClient sse(client, "/multi-event");
  22562. std::vector<std::string> received_messages;
  22563. std::mutex messages_mutex;
  22564. sse.on_message([&](const sse::SSEMessage &msg) {
  22565. std::lock_guard<std::mutex> lock(messages_mutex);
  22566. received_messages.push_back(msg.data);
  22567. });
  22568. sse.set_reconnect_interval(100);
  22569. sse.set_max_reconnect_attempts(1);
  22570. sse.start_async();
  22571. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22572. sse.stop();
  22573. std::lock_guard<std::mutex> lock(messages_mutex);
  22574. EXPECT_GE(received_messages.size(), 2u);
  22575. if (received_messages.size() >= 2) {
  22576. EXPECT_EQ(received_messages[0], "message1");
  22577. EXPECT_EQ(received_messages[1], "message2");
  22578. }
  22579. }
  22580. // Test: on_event for specific types
  22581. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22582. Client client("localhost", get_port());
  22583. sse::SSEClient sse(client, "/custom-events");
  22584. std::atomic<bool> update_received{false};
  22585. std::atomic<bool> delete_received{false};
  22586. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22587. if (msg.data == "updated") { update_received.store(true); }
  22588. });
  22589. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22590. if (msg.data == "deleted") { delete_received.store(true); }
  22591. });
  22592. sse.set_max_reconnect_attempts(1);
  22593. sse.start_async();
  22594. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22595. sse.stop();
  22596. EXPECT_TRUE(update_received.load());
  22597. EXPECT_TRUE(delete_received.load());
  22598. }
  22599. // Test: on_error callback on connection failure
  22600. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22601. // Connect to a non-existent port
  22602. Client client("localhost", 59999);
  22603. sse::SSEClient sse(client, "/events");
  22604. std::atomic<bool> error_called{false};
  22605. Error received_error = Error::Success;
  22606. sse.on_error([&](Error err) {
  22607. error_called.store(true);
  22608. received_error = err;
  22609. });
  22610. sse.set_reconnect_interval(50);
  22611. sse.set_max_reconnect_attempts(1);
  22612. sse.start_async();
  22613. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22614. sse.stop();
  22615. EXPECT_TRUE(error_called.load());
  22616. EXPECT_NE(received_error, Error::Success);
  22617. }
  22618. // Test: Last-Event-ID header sent on reconnect
  22619. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22620. // Endpoint that sends event with ID
  22621. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22622. res.set_chunked_content_provider(
  22623. "text/event-stream", [](size_t offset, DataSink &sink) {
  22624. if (offset == 0) {
  22625. std::string event = "id: evt-123\ndata: test\n\n";
  22626. sink.write(event.data(), event.size());
  22627. }
  22628. return false;
  22629. });
  22630. });
  22631. Client client("localhost", get_port());
  22632. sse::SSEClient sse(client, "/event-with-id");
  22633. std::atomic<bool> id_received{false};
  22634. sse.on_message([&](const sse::SSEMessage &msg) {
  22635. if (!msg.id.empty()) { id_received.store(true); }
  22636. });
  22637. sse.set_reconnect_interval(100);
  22638. sse.set_max_reconnect_attempts(1);
  22639. sse.start_async();
  22640. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22641. sse.stop();
  22642. EXPECT_TRUE(id_received.load());
  22643. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22644. }
  22645. // Test: last_event_id() read from another thread while start_async() runs
  22646. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22647. // Ids of every length up to 200, so the stored id keeps changing size
  22648. server_->Get("/many-ids", [](const Request &, Response &res) {
  22649. res.set_chunked_content_provider(
  22650. "text/event-stream", [](size_t offset, DataSink &sink) {
  22651. if (offset == 0) {
  22652. std::string events;
  22653. for (size_t i = 0; i < 2000; i++) {
  22654. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22655. events += "data: x\n\n";
  22656. }
  22657. events += "id: end\ndata: x\n\n";
  22658. sink.write(events.data(), events.size());
  22659. }
  22660. return false;
  22661. });
  22662. });
  22663. Client client("localhost", get_port());
  22664. sse::SSEClient sse(client, "/many-ids");
  22665. // Wait out the rest of the test rather than replay the stream
  22666. sse.set_reconnect_interval(10000);
  22667. sse.set_max_reconnect_attempts(1);
  22668. sse.start_async();
  22669. auto well_formed = true;
  22670. std::string id;
  22671. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22672. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22673. id = sse.last_event_id();
  22674. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22675. well_formed = false;
  22676. }
  22677. }
  22678. sse.stop();
  22679. EXPECT_TRUE(well_formed);
  22680. EXPECT_EQ(sse.last_event_id(), "end");
  22681. }
  22682. // Test: Manual stop
  22683. TEST_F(SSEIntegrationTest, ManualStop) {
  22684. // Endpoint that sends one event and stays open briefly. The server outlives
  22685. // this test body, so the provider uses the fixture's flag, not a local.
  22686. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22687. res.set_chunked_content_provider(
  22688. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22689. if (offset == 0) {
  22690. std::string event = "data: connected\n\n";
  22691. sink.write(event.data(), event.size());
  22692. }
  22693. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22694. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22695. }
  22696. return false;
  22697. });
  22698. });
  22699. Client client("localhost", get_port());
  22700. sse::SSEClient sse(client, "/stay-open");
  22701. std::atomic<bool> connected{false};
  22702. sse.on_open([&connected]() { connected.store(true); });
  22703. sse.set_reconnect_interval(100);
  22704. sse.set_max_reconnect_attempts(1);
  22705. sse.start_async();
  22706. // Wait for connection to establish
  22707. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22708. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22709. }
  22710. EXPECT_TRUE(connected.load());
  22711. EXPECT_TRUE(sse.is_connected());
  22712. // Signal handler to stop
  22713. stop_server_.store(true);
  22714. // Stop SSE client
  22715. sse.stop();
  22716. EXPECT_FALSE(sse.is_connected());
  22717. }
  22718. // Sends one event, then nothing until stop is set
  22719. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22720. return [&stop](const Request &, Response &res) {
  22721. res.set_chunked_content_provider(
  22722. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22723. if (offset == 0) {
  22724. std::string event = "data: hello\n\n";
  22725. sink.write(event.data(), event.size());
  22726. }
  22727. while (!stop.load()) {
  22728. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22729. }
  22730. return false;
  22731. });
  22732. };
  22733. }
  22734. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22735. static void check_stop_interrupts_blocked_read(Client &client) {
  22736. client.set_read_timeout(30, 0);
  22737. for (auto by_destructor : {false, true}) {
  22738. std::atomic<bool> received{false};
  22739. std::chrono::steady_clock::time_point start;
  22740. {
  22741. sse::SSEClient sse(client, "/idle-stream");
  22742. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22743. sse.start_async();
  22744. for (int i = 0; i < 500 && !received.load(); ++i) {
  22745. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22746. }
  22747. ASSERT_TRUE(received.load());
  22748. // Let the client block in the next read
  22749. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22750. start = std::chrono::steady_clock::now();
  22751. if (!by_destructor) { sse.stop(); }
  22752. }
  22753. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22754. std::chrono::seconds(2));
  22755. }
  22756. }
  22757. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22758. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22759. Client client("localhost", get_port());
  22760. check_stop_interrupts_blocked_read(client);
  22761. }
  22762. #ifdef CPPHTTPLIB_SSL_ENABLED
  22763. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22764. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22765. std::atomic<bool> done{false};
  22766. svr.Get("/idle-stream", idle_event_stream(done));
  22767. auto port = svr.bind_to_any_port(HOST);
  22768. std::thread t([&] { svr.listen_after_bind(); });
  22769. auto se = detail::scope_exit([&] {
  22770. done.store(true);
  22771. svr.stop();
  22772. t.join();
  22773. });
  22774. svr.wait_until_ready();
  22775. Client client("https://localhost:" + std::to_string(port));
  22776. client.enable_server_certificate_verification(false);
  22777. check_stop_interrupts_blocked_read(client);
  22778. }
  22779. #endif
  22780. // Test: SSEClient with custom headers
  22781. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22782. // Setup a server endpoint that checks for custom header
  22783. std::atomic<bool> header_received{false};
  22784. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22785. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22786. header_received.store(true);
  22787. }
  22788. res.set_chunked_content_provider("text/event-stream",
  22789. [](size_t, DataSink &) { return false; });
  22790. });
  22791. Client client("localhost", get_port());
  22792. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22793. sse::SSEClient sse(client, "/header-check", headers);
  22794. sse.set_max_reconnect_attempts(1);
  22795. sse.start_async();
  22796. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22797. sse.stop();
  22798. EXPECT_TRUE(header_received.load());
  22799. }
  22800. // Test: Reconnect interval configuration
  22801. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22802. Client client("localhost", get_port());
  22803. sse::SSEClient sse(client, "/events");
  22804. auto &result = sse.set_reconnect_interval(500);
  22805. // Builder pattern should return reference to self
  22806. EXPECT_EQ(&result, &sse);
  22807. }
  22808. // Test: Max reconnect attempts
  22809. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22810. // Connect to non-existent port to force reconnects
  22811. Client client("localhost", 59998);
  22812. sse::SSEClient sse(client, "/events");
  22813. std::atomic<int> error_count{0};
  22814. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22815. sse.set_reconnect_interval(50);
  22816. sse.set_max_reconnect_attempts(2);
  22817. auto start = std::chrono::steady_clock::now();
  22818. sse.start(); // Blocking call
  22819. auto end = std::chrono::steady_clock::now();
  22820. // Should have stopped after 2 failed attempts
  22821. EXPECT_GE(error_count.load(), 2);
  22822. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22823. auto duration =
  22824. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22825. #ifdef _WIN32
  22826. // Windows is much slower for socket connection failures
  22827. EXPECT_LT(duration.count(), 7000);
  22828. #else
  22829. EXPECT_LT(duration.count(), 1000);
  22830. #endif
  22831. }
  22832. // Test: Multi-line data in integration
  22833. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22834. // Endpoint with multi-line data
  22835. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22836. res.set_chunked_content_provider(
  22837. "text/event-stream", [](size_t offset, DataSink &sink) {
  22838. if (offset == 0) {
  22839. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22840. sink.write(event.data(), event.size());
  22841. }
  22842. return false;
  22843. });
  22844. });
  22845. Client client("localhost", get_port());
  22846. sse::SSEClient sse(client, "/multiline-data");
  22847. std::string received_data;
  22848. std::mutex data_mutex;
  22849. sse.on_message([&](const sse::SSEMessage &msg) {
  22850. std::lock_guard<std::mutex> lock(data_mutex);
  22851. received_data = msg.data;
  22852. });
  22853. sse.set_reconnect_interval(100);
  22854. sse.set_max_reconnect_attempts(1);
  22855. sse.start_async();
  22856. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22857. sse.stop();
  22858. std::lock_guard<std::mutex> lock(data_mutex);
  22859. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22860. }
  22861. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22862. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22863. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22864. DataSink &sink) {
  22865. if (offset == 0) {
  22866. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22867. sink.write(events.data(), events.size());
  22868. }
  22869. return false;
  22870. });
  22871. });
  22872. Client client("localhost", get_port());
  22873. sse::SSEClient sse(client, "/empty-data-lines");
  22874. std::mutex mutex;
  22875. std::condition_variable cv;
  22876. std::vector<std::string> received;
  22877. sse.on_message([&](const sse::SSEMessage &msg) {
  22878. std::lock_guard<std::mutex> lock(mutex);
  22879. received.push_back(msg.data);
  22880. cv.notify_all();
  22881. });
  22882. sse.set_max_reconnect_attempts(1);
  22883. sse.start_async();
  22884. {
  22885. std::unique_lock<std::mutex> lock(mutex);
  22886. cv.wait_for(lock, std::chrono::seconds(2),
  22887. [&] { return received.size() >= 3; });
  22888. }
  22889. sse.stop();
  22890. ASSERT_GE(received.size(), 3u);
  22891. EXPECT_EQ(received[0], "");
  22892. EXPECT_EQ(received[1], "\nhello");
  22893. EXPECT_EQ(received[2], "");
  22894. }
  22895. // Test: Auto-reconnect after server disconnection
  22896. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22897. std::atomic<int> connection_count{0};
  22898. std::atomic<int> message_count{0};
  22899. // Endpoint that sends one event and closes, forcing reconnect
  22900. server_->Get("/reconnect-test",
  22901. [&connection_count](const Request &, Response &res) {
  22902. connection_count.fetch_add(1);
  22903. res.set_chunked_content_provider(
  22904. "text/event-stream", [](size_t offset, DataSink &sink) {
  22905. if (offset == 0) {
  22906. std::string event = "data: hello\n\n";
  22907. sink.write(event.data(), event.size());
  22908. }
  22909. return false; // Close connection after sending
  22910. });
  22911. });
  22912. Client client("localhost", get_port());
  22913. sse::SSEClient sse(client, "/reconnect-test");
  22914. sse.on_message([&message_count](const sse::SSEMessage &) {
  22915. message_count.fetch_add(1);
  22916. });
  22917. sse.set_reconnect_interval(100);
  22918. sse.set_max_reconnect_attempts(3);
  22919. sse.start_async();
  22920. // Wait long enough for multiple reconnects
  22921. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22922. sse.stop();
  22923. // Should have connected multiple times (initial + reconnects)
  22924. EXPECT_GE(connection_count.load(), 2);
  22925. // Should have received messages from multiple connections
  22926. EXPECT_GE(message_count.load(), 2);
  22927. }
  22928. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22929. std::atomic<int> connection_count{0};
  22930. // Neither Content-Length nor chunked: the close ends the stream
  22931. server_->Get("/close-delimited",
  22932. [&connection_count](const Request &, Response &res) {
  22933. connection_count.fetch_add(1);
  22934. res.set_content_provider(
  22935. "text/event-stream", [](size_t offset, DataSink &sink) {
  22936. if (offset == 0) {
  22937. std::string event = "data: hello\n\n";
  22938. sink.write(event.data(), event.size());
  22939. } else {
  22940. sink.done();
  22941. }
  22942. return true;
  22943. });
  22944. });
  22945. Client client("localhost", get_port());
  22946. sse::SSEClient sse(client, "/close-delimited");
  22947. std::atomic<int> error_count{0};
  22948. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22949. sse.set_reconnect_interval(100);
  22950. sse.start_async();
  22951. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22952. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22953. }
  22954. sse.stop();
  22955. // Reconnects as after any end of the stream, but reports no error
  22956. EXPECT_GE(connection_count.load(), 2);
  22957. EXPECT_EQ(0, error_count.load());
  22958. }
  22959. // Test: A retry field that is not all ASCII digits is ignored
  22960. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22961. std::atomic<int> connection_count{0};
  22962. server_->Get("/bad-retry",
  22963. [&connection_count](const Request &, Response &res) {
  22964. connection_count.fetch_add(1);
  22965. res.set_chunked_content_provider(
  22966. "text/event-stream", [](size_t offset, DataSink &sink) {
  22967. if (offset == 0) {
  22968. std::string event = "retry: -1\ndata: hello\n\n";
  22969. sink.write(event.data(), event.size());
  22970. }
  22971. return false;
  22972. });
  22973. });
  22974. Client client("localhost", get_port());
  22975. sse::SSEClient sse(client, "/bad-retry");
  22976. sse.set_reconnect_interval(10000);
  22977. sse.start_async();
  22978. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22979. sse.stop();
  22980. EXPECT_EQ(connection_count.load(), 1);
  22981. }
  22982. // Test: A retry field of all ASCII digits sets the reconnection time
  22983. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22984. std::mutex mutex;
  22985. std::condition_variable cv;
  22986. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22987. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22988. {
  22989. std::lock_guard<std::mutex> lock(mutex);
  22990. connected_at.push_back(std::chrono::steady_clock::now());
  22991. cv.notify_all();
  22992. }
  22993. res.set_chunked_content_provider(
  22994. "text/event-stream", [](size_t offset, DataSink &sink) {
  22995. if (offset == 0) {
  22996. std::string event = "retry: 0\ndata: hello\n\n";
  22997. sink.write(event.data(), event.size());
  22998. }
  22999. return false;
  23000. });
  23001. });
  23002. Client client("localhost", get_port());
  23003. sse::SSEClient sse(client, "/zero-retry");
  23004. sse.set_reconnect_interval(10000);
  23005. sse.start_async();
  23006. {
  23007. std::unique_lock<std::mutex> lock(mutex);
  23008. cv.wait_for(lock, std::chrono::seconds(5),
  23009. [&] { return connected_at.size() >= 2; });
  23010. }
  23011. sse.stop();
  23012. // The server-supplied interval is applied, but never below 100ms, so
  23013. // "retry: 0" does not cause a busy reconnect loop
  23014. std::lock_guard<std::mutex> lock(mutex);
  23015. ASSERT_GE(connected_at.size(), 2u);
  23016. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23017. connected_at[1] - connected_at[0])
  23018. .count();
  23019. EXPECT_GE(interval_ms, 100);
  23020. }
  23021. // Test: Last-Event-ID sent on reconnect
  23022. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23023. std::atomic<int> connection_count{0};
  23024. std::vector<std::string> received_last_event_ids;
  23025. std::mutex id_mutex;
  23026. // Endpoint that checks Last-Event-ID header and sends event with ID
  23027. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23028. int conn = connection_count.fetch_add(1);
  23029. // Capture the Last-Event-ID header from each connection
  23030. {
  23031. std::lock_guard<std::mutex> lock(id_mutex);
  23032. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23033. }
  23034. res.set_chunked_content_provider(
  23035. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23036. if (offset == 0) {
  23037. std::string event =
  23038. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23039. sink.write(event.data(), event.size());
  23040. }
  23041. return false;
  23042. });
  23043. });
  23044. Client client("localhost", get_port());
  23045. sse::SSEClient sse(client, "/reconnect-with-id");
  23046. sse.set_reconnect_interval(100);
  23047. sse.set_max_reconnect_attempts(3);
  23048. sse.start_async();
  23049. // Wait for at least 2 connections
  23050. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23051. sse.stop();
  23052. // Verify behavior
  23053. std::lock_guard<std::mutex> lock(id_mutex);
  23054. EXPECT_GE(received_last_event_ids.size(), 2u);
  23055. // First connection should have no Last-Event-ID
  23056. if (!received_last_event_ids.empty()) {
  23057. EXPECT_EQ(received_last_event_ids[0], "");
  23058. }
  23059. // Second connection should have Last-Event-ID from first connection
  23060. if (received_last_event_ids.size() >= 2) {
  23061. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23062. }
  23063. }
  23064. // Test: set_headers updates headers used on reconnect
  23065. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23066. std::vector<std::string> received_tokens;
  23067. std::mutex token_mutex;
  23068. // Endpoint that captures Authorization header
  23069. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23070. {
  23071. std::lock_guard<std::mutex> lock(token_mutex);
  23072. received_tokens.push_back(req.get_header_value("Authorization"));
  23073. }
  23074. res.set_chunked_content_provider(
  23075. "text/event-stream", [](size_t offset, DataSink &sink) {
  23076. if (offset == 0) {
  23077. std::string event = "data: hello\n\n";
  23078. sink.write(event.data(), event.size());
  23079. }
  23080. return false; // Close connection to trigger reconnect
  23081. });
  23082. });
  23083. Client client("localhost", get_port());
  23084. Headers headers = {{"Authorization", "Bearer old-token"}};
  23085. sse::SSEClient sse(client, "/auth-check", headers);
  23086. // Update headers on each successful connection
  23087. sse.on_open(
  23088. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23089. sse.set_reconnect_interval(100);
  23090. sse.set_max_reconnect_attempts(3);
  23091. sse.start_async();
  23092. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23093. sse.stop();
  23094. std::lock_guard<std::mutex> lock(token_mutex);
  23095. ASSERT_GE(received_tokens.size(), 2u);
  23096. // First connection uses original header
  23097. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23098. // Second connection uses updated header from set_headers
  23099. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23100. }
  23101. // Test: 401 allows reconnection (so on_error can refresh headers)
  23102. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23103. std::atomic<int> connection_count{0};
  23104. // Endpoint: returns 401 on first attempt, 200 on second
  23105. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23106. int conn = connection_count.fetch_add(1);
  23107. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23108. res.status = StatusCode::Unauthorized_401;
  23109. res.set_content("Unauthorized", "text/plain");
  23110. return;
  23111. }
  23112. res.set_chunked_content_provider(
  23113. "text/event-stream", [](size_t offset, DataSink &sink) {
  23114. if (offset == 0) {
  23115. std::string event = "data: authenticated\n\n";
  23116. sink.write(event.data(), event.size());
  23117. }
  23118. return false;
  23119. });
  23120. });
  23121. Client client("localhost", get_port());
  23122. Headers headers = {{"Authorization", "Bearer expired"}};
  23123. sse::SSEClient sse(client, "/auth-retry", headers);
  23124. std::atomic<bool> message_received{false};
  23125. // Refresh token on error
  23126. sse.on_error(
  23127. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23128. sse.on_message([&](const sse::SSEMessage &msg) {
  23129. if (msg.data == "authenticated") { message_received.store(true); }
  23130. });
  23131. sse.set_reconnect_interval(100);
  23132. sse.set_max_reconnect_attempts(3);
  23133. sse.start_async();
  23134. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23135. sse.stop();
  23136. // Should have reconnected after 401 and succeeded with new token
  23137. EXPECT_GE(connection_count.load(), 2);
  23138. EXPECT_TRUE(message_received.load());
  23139. }
  23140. TEST(Issue2318Test, EmptyHostString) {
  23141. {
  23142. httplib::Client cli_empty("", PORT);
  23143. auto res = cli_empty.Get("/");
  23144. ASSERT_FALSE(res);
  23145. EXPECT_EQ(httplib::Error::Connection, res.error());
  23146. }
  23147. {
  23148. httplib::Client cli(" ", PORT);
  23149. auto res = cli.Get("/");
  23150. ASSERT_FALSE(res);
  23151. EXPECT_EQ(httplib::Error::Connection, res.error());
  23152. }
  23153. }
  23154. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23155. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23156. Server svr;
  23157. // Set a small payload limit (1KB)
  23158. svr.set_payload_max_length(1024);
  23159. svr.Post("/test", [&](const Request &req, Response &res) {
  23160. res.set_content("Body size: " + std::to_string(req.body.size()),
  23161. "text/plain");
  23162. });
  23163. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23164. auto se = detail::scope_exit([&] {
  23165. svr.stop();
  23166. listen_thread.join();
  23167. });
  23168. svr.wait_until_ready();
  23169. // Create data that compresses well but exceeds limit when decompressed
  23170. // 8KB of repeated null bytes compresses to a very small size
  23171. std::string original_data(8 * 1024, '\0');
  23172. // Compress the data using gzip
  23173. std::string compressed_data;
  23174. detail::gzip_compressor compressor;
  23175. compressor.compress(original_data.data(), original_data.size(), true,
  23176. [&](const char *data, size_t size) {
  23177. compressed_data.append(data, size);
  23178. return true;
  23179. });
  23180. // Verify compression worked (compressed should be much smaller)
  23181. ASSERT_LT(compressed_data.size(), original_data.size());
  23182. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23183. // Send compressed data with Content-Encoding: gzip
  23184. Client cli(HOST, PORT);
  23185. Headers headers = {{"Content-Encoding", "gzip"}};
  23186. auto res =
  23187. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23188. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23190. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23191. }
  23192. #endif
  23193. // ============================================================================
  23194. // OpenSSL-Specific Tests
  23195. // ============================================================================
  23196. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23197. X509 *readCertificate(const std::string &strFileName) {
  23198. std::ifstream inStream(strFileName);
  23199. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23200. std::istreambuf_iterator<char>());
  23201. if (strCertPEM.empty()) return (nullptr);
  23202. BIO *pbCert = BIO_new(BIO_s_mem());
  23203. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23204. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23205. BIO_free(pbCert);
  23206. return (pCert);
  23207. }
  23208. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23209. std::ifstream inStream(strFileName);
  23210. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23211. std::istreambuf_iterator<char>());
  23212. if (strPrivateKeyPEM.empty()) return (nullptr);
  23213. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23214. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23215. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23216. BIO_free(pbPrivKey);
  23217. return (pPrivateKey);
  23218. }
  23219. TEST(BindServerTest, UpdateCerts) {
  23220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23221. int port = svr.bind_to_any_port("0.0.0.0");
  23222. ASSERT_TRUE(svr.is_valid());
  23223. ASSERT_TRUE(port > 0);
  23224. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23225. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23226. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23227. ASSERT_TRUE(cert != nullptr);
  23228. ASSERT_TRUE(ca_cert != nullptr);
  23229. ASSERT_TRUE(key != nullptr);
  23230. X509_STORE *cert_store = X509_STORE_new();
  23231. X509_STORE_add_cert(cert_store, ca_cert);
  23232. // svr.update_certs(cert, key, cert_store); // deprecated
  23233. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23234. CLIENT_CA_CERT_FILE);
  23235. ASSERT_TRUE(svr.is_valid());
  23236. svr.stop();
  23237. X509_STORE_free(cert_store);
  23238. X509_free(cert);
  23239. X509_free(ca_cert);
  23240. EVP_PKEY_free(key);
  23241. }
  23242. // Test that update_certs() updates client CA list correctly
  23243. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23244. // Start with file-based constructor
  23245. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23246. ASSERT_TRUE(svr.is_valid());
  23247. // Initially no client CA list should be set
  23248. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23249. ASSERT_TRUE(ssl_ctx != nullptr);
  23250. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23251. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23252. // Now update with client CA (PEM string)
  23253. std::string cert_pem, key_pem, ca_pem;
  23254. read_file(SERVER_CERT_FILE, cert_pem);
  23255. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23256. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23257. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23258. ASSERT_TRUE(svr.is_valid());
  23259. // Now client CA list should be set
  23260. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23261. ASSERT_TRUE(ca_list_after != nullptr);
  23262. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23263. }
  23264. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23265. // Test that the file-path SSLServer constructor properly sets the client CA
  23266. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23267. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23268. ASSERT_TRUE(svr.is_valid());
  23269. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23270. ASSERT_TRUE(ssl_ctx != nullptr);
  23271. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23272. ASSERT_TRUE(ca_list != nullptr);
  23273. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23274. }
  23275. #endif
  23276. // ============================================================================
  23277. // MbedTLS-Specific Tests
  23278. // ============================================================================
  23279. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23280. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23281. using namespace httplib::tls;
  23282. // Track if callback was invoked
  23283. bool callback_invoked = false;
  23284. // The callback receives void* ctx which is actually MbedTlsContext*
  23285. // We can access the mbedtls_ssl_config via the context
  23286. auto setup_callback = [&callback_invoked](void *ctx) {
  23287. callback_invoked = true;
  23288. // Cast to MbedTlsContext* to access the ssl config
  23289. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23290. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23291. // Use static variables to hold certificate data (simplified for test)
  23292. static mbedtls_x509_crt own_cert;
  23293. static mbedtls_pk_context own_key;
  23294. static mbedtls_x509_crt ca_chain;
  23295. static bool initialized = false;
  23296. if (!initialized) {
  23297. mbedtls_x509_crt_init(&own_cert);
  23298. mbedtls_pk_init(&own_key);
  23299. mbedtls_x509_crt_init(&ca_chain);
  23300. // Load server certificate
  23301. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23302. return false;
  23303. }
  23304. // Load server private key.
  23305. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23306. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23307. #if MBEDTLS_VERSION_MAJOR == 3
  23308. ,
  23309. mbedtls_ctr_drbg_random, nullptr
  23310. #endif
  23311. ) != 0) {
  23312. return false;
  23313. }
  23314. // Load CA chain for client verification
  23315. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23316. return false;
  23317. }
  23318. initialized = true;
  23319. }
  23320. // Configure the SSL config
  23321. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23322. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23323. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23324. // Set minimum TLS version using mbedTLS native API
  23325. #if MBEDTLS_VERSION_MAJOR >= 3
  23326. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23327. #else
  23328. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23329. MBEDTLS_SSL_MINOR_VERSION_3);
  23330. #endif
  23331. return true;
  23332. };
  23333. SSLServer svr(setup_callback);
  23334. ASSERT_TRUE(svr.is_valid());
  23335. ASSERT_TRUE(callback_invoked);
  23336. svr.Get("/test", [&](const Request &req, Response &res) {
  23337. res.set_content("test", "text/plain");
  23338. auto cert = req.peer_cert();
  23339. ASSERT_TRUE(static_cast<bool>(cert));
  23340. auto common_name = cert.subject_cn();
  23341. EXPECT_EQ("Common Name", common_name);
  23342. });
  23343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23344. auto se = detail::scope_exit([&] {
  23345. svr.stop();
  23346. t.join();
  23347. ASSERT_FALSE(svr.is_running());
  23348. });
  23349. svr.wait_until_ready();
  23350. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23351. cli.enable_server_certificate_verification(false);
  23352. cli.set_connection_timeout(30);
  23353. auto res = cli.Get("/test");
  23354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23355. ASSERT_EQ(StatusCode::OK_200, res->status);
  23356. }
  23357. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23358. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23359. // keep-alive SSL session, which reads through that config in
  23360. // mbedtls_ssl_close_notify.
  23361. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23362. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23363. ASSERT_TRUE(svr.is_valid());
  23364. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23365. res.set_content("test", "text/plain");
  23366. });
  23367. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23368. auto se = detail::scope_exit([&] {
  23369. svr.stop();
  23370. t.join();
  23371. ASSERT_FALSE(svr.is_running());
  23372. });
  23373. svr.wait_until_ready();
  23374. {
  23375. SSLClient cli(HOST, PORT);
  23376. cli.enable_server_certificate_verification(false);
  23377. cli.set_keep_alive(true);
  23378. auto res = cli.Get("/test");
  23379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23380. ASSERT_EQ(StatusCode::OK_200, res->status);
  23381. // cli is destructed here with the keep-alive SSL session still open.
  23382. }
  23383. }
  23384. #endif
  23385. // WebSocket Tests
  23386. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23387. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23388. // defining the meaning of these bits has been negotiated.
  23389. auto make_frame = [](uint8_t first_byte) {
  23390. std::string frame;
  23391. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23392. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23393. frame += "Hello";
  23394. return frame;
  23395. };
  23396. // RSV1 set (0x40)
  23397. {
  23398. detail::BufferStream strm;
  23399. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23400. ws::Opcode opcode;
  23401. std::string payload;
  23402. bool fin;
  23403. EXPECT_EQ(
  23404. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23405. ws::impl::FrameRead::Fail);
  23406. }
  23407. // RSV2 set (0x20)
  23408. {
  23409. detail::BufferStream strm;
  23410. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23411. ws::Opcode opcode;
  23412. std::string payload;
  23413. bool fin;
  23414. EXPECT_EQ(
  23415. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23416. ws::impl::FrameRead::Fail);
  23417. }
  23418. // RSV3 set (0x10)
  23419. {
  23420. detail::BufferStream strm;
  23421. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23422. ws::Opcode opcode;
  23423. std::string payload;
  23424. bool fin;
  23425. EXPECT_EQ(
  23426. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23427. ws::impl::FrameRead::Fail);
  23428. }
  23429. // No RSV bits set - should succeed
  23430. {
  23431. detail::BufferStream strm;
  23432. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23433. ws::Opcode opcode;
  23434. std::string payload;
  23435. bool fin;
  23436. EXPECT_EQ(
  23437. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23438. ws::impl::FrameRead::Ok);
  23439. EXPECT_EQ(ws::Opcode::Text, opcode);
  23440. EXPECT_EQ("Hello", payload);
  23441. EXPECT_TRUE(fin);
  23442. }
  23443. }
  23444. TEST(WebSocketTest, ControlFrameValidation) {
  23445. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23446. // payload length <= 125.
  23447. // Ping with FIN=0 - must be rejected
  23448. {
  23449. detail::BufferStream strm;
  23450. std::string frame;
  23451. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23452. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23453. strm.write(frame.data(), frame.size());
  23454. ws::Opcode opcode;
  23455. std::string payload;
  23456. bool fin;
  23457. EXPECT_EQ(
  23458. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23459. ws::impl::FrameRead::Fail);
  23460. }
  23461. // Close with FIN=0 - must be rejected
  23462. {
  23463. detail::BufferStream strm;
  23464. std::string frame;
  23465. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23466. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23467. strm.write(frame.data(), frame.size());
  23468. ws::Opcode opcode;
  23469. std::string payload;
  23470. bool fin;
  23471. EXPECT_EQ(
  23472. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23473. ws::impl::FrameRead::Fail);
  23474. }
  23475. // Ping with payload_len=126 (extended length) - must be rejected
  23476. {
  23477. detail::BufferStream strm;
  23478. std::string frame;
  23479. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23480. frame += static_cast<char>(126); // payload_len=126 (>125)
  23481. frame += static_cast<char>(0x00); // extended length high byte
  23482. frame += static_cast<char>(126); // extended length low byte
  23483. frame += std::string(126, 'x');
  23484. strm.write(frame.data(), frame.size());
  23485. ws::Opcode opcode;
  23486. std::string payload;
  23487. bool fin;
  23488. EXPECT_EQ(
  23489. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23490. ws::impl::FrameRead::Fail);
  23491. }
  23492. // Ping with FIN=1 and payload_len=125 - should succeed
  23493. {
  23494. detail::BufferStream strm;
  23495. std::string frame;
  23496. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23497. frame += static_cast<char>(125); // payload_len=125
  23498. frame += std::string(125, 'x');
  23499. strm.write(frame.data(), frame.size());
  23500. ws::Opcode opcode;
  23501. std::string payload;
  23502. bool fin;
  23503. EXPECT_EQ(
  23504. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23505. ws::impl::FrameRead::Ok);
  23506. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23507. EXPECT_EQ(125u, payload.size());
  23508. EXPECT_TRUE(fin);
  23509. }
  23510. }
  23511. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23512. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23513. // length MUST be 0.
  23514. // MSB set - must be rejected
  23515. {
  23516. detail::BufferStream strm;
  23517. std::string frame;
  23518. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23519. frame += static_cast<char>(127); // 64-bit extended length
  23520. frame += static_cast<char>(0x80); // MSB set (invalid)
  23521. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23522. strm.write(frame.data(), frame.size());
  23523. ws::Opcode opcode;
  23524. std::string payload;
  23525. bool fin;
  23526. EXPECT_EQ(
  23527. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23528. ws::impl::FrameRead::Fail);
  23529. }
  23530. // MSB clear - should pass length parsing (will be rejected by max_len,
  23531. // but that's a different check; use a small length to verify)
  23532. {
  23533. detail::BufferStream strm;
  23534. std::string frame;
  23535. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23536. frame += static_cast<char>(127); // 64-bit extended length
  23537. frame += std::string(7, '\0'); // high bytes = 0
  23538. frame += static_cast<char>(0x03); // length = 3
  23539. frame += "abc";
  23540. strm.write(frame.data(), frame.size());
  23541. ws::Opcode opcode;
  23542. std::string payload;
  23543. bool fin;
  23544. EXPECT_EQ(
  23545. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23546. ws::impl::FrameRead::Ok);
  23547. EXPECT_EQ(ws::Opcode::Text, opcode);
  23548. EXPECT_EQ("abc", payload);
  23549. }
  23550. }
  23551. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23552. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23553. // Valid UTF-8
  23554. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23555. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23556. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23557. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23558. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23559. // Invalid UTF-8
  23560. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23561. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23562. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23563. EXPECT_FALSE(
  23564. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23565. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23566. }
  23567. TEST(WebSocketTest, ConnectAndDisconnect) {
  23568. Server svr;
  23569. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23570. std::string msg;
  23571. while (ws.read(msg)) {}
  23572. });
  23573. auto port = svr.bind_to_any_port(HOST);
  23574. std::thread t([&]() { svr.listen_after_bind(); });
  23575. svr.wait_until_ready();
  23576. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23577. auto res = client.connect();
  23578. ASSERT_TRUE(res);
  23579. EXPECT_EQ(Error::Success, res.error());
  23580. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23581. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23582. EXPECT_TRUE(client.is_open());
  23583. client.close();
  23584. EXPECT_FALSE(client.is_open());
  23585. svr.stop();
  23586. t.join();
  23587. }
  23588. TEST(WebSocketTest, ValidURL) {
  23589. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23590. EXPECT_TRUE(ws1.is_valid());
  23591. ws::WebSocketClient ws2("ws://example.com/path");
  23592. EXPECT_TRUE(ws2.is_valid());
  23593. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23594. EXPECT_TRUE(ws3.is_valid());
  23595. #ifdef CPPHTTPLIB_SSL_ENABLED
  23596. ws::WebSocketClient wss1("wss://example.com/path");
  23597. EXPECT_TRUE(wss1.is_valid());
  23598. ws::WebSocketClient wss2("wss://example.com:443/path");
  23599. EXPECT_TRUE(wss2.is_valid());
  23600. #endif
  23601. }
  23602. TEST(WebSocketTest, InvalidURL) {
  23603. // No scheme
  23604. ws::WebSocketClient ws1("localhost:8080/path");
  23605. EXPECT_FALSE(ws1.is_valid());
  23606. // No path
  23607. ws::WebSocketClient ws2("ws://localhost:8080");
  23608. EXPECT_FALSE(ws2.is_valid());
  23609. // Empty string
  23610. ws::WebSocketClient ws3("");
  23611. EXPECT_FALSE(ws3.is_valid());
  23612. // Missing host
  23613. ws::WebSocketClient ws4("ws://:8080/path");
  23614. EXPECT_FALSE(ws4.is_valid());
  23615. // Port number overflow — should not crash
  23616. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23617. EXPECT_FALSE(ws5.is_valid());
  23618. // Port out of range
  23619. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23620. EXPECT_FALSE(ws6.is_valid());
  23621. }
  23622. TEST(WebSocketTest, UnsupportedScheme) {
  23623. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23624. ws::WebSocketClient ws1("http://localhost:8080/path");
  23625. EXPECT_FALSE(ws1.is_valid());
  23626. ws::WebSocketClient ws2("https://localhost:8080/path");
  23627. EXPECT_FALSE(ws2.is_valid());
  23628. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23629. EXPECT_FALSE(ws3.is_valid());
  23630. #else
  23631. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23632. std::invalid_argument);
  23633. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23634. std::invalid_argument);
  23635. #endif
  23636. }
  23637. TEST(WebSocketTest, ConnectWhenInvalid) {
  23638. ws::WebSocketClient ws("not a valid url");
  23639. EXPECT_FALSE(ws.is_valid());
  23640. auto res = ws.connect();
  23641. EXPECT_FALSE(res);
  23642. EXPECT_EQ(Error::Connection, res.error());
  23643. EXPECT_EQ(-1, res.status());
  23644. }
  23645. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23646. // Grab a port that is free, then close it again so nothing listens there
  23647. Server svr;
  23648. auto port = svr.bind_to_any_port(HOST);
  23649. svr.stop();
  23650. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23651. auto res = client.connect();
  23652. ASSERT_FALSE(res);
  23653. EXPECT_EQ(Error::Connection, res.error());
  23654. EXPECT_EQ(-1, res.status());
  23655. }
  23656. TEST(WebSocketTest, DefaultPort) {
  23657. ws::WebSocketClient ws1("ws://example.com/path");
  23658. EXPECT_TRUE(ws1.is_valid());
  23659. // ws:// defaults to port 80 (verified by successful parse)
  23660. #ifdef CPPHTTPLIB_SSL_ENABLED
  23661. ws::WebSocketClient ws2("wss://example.com/path");
  23662. EXPECT_TRUE(ws2.is_valid());
  23663. // wss:// defaults to port 443 (verified by successful parse)
  23664. #endif
  23665. }
  23666. TEST(WebSocketTest, IPv6LiteralAddress) {
  23667. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23668. EXPECT_TRUE(ws1.is_valid());
  23669. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23670. EXPECT_TRUE(ws2.is_valid());
  23671. }
  23672. TEST(WebSocketTest, ComplexPath) {
  23673. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23674. EXPECT_TRUE(ws1.is_valid());
  23675. ws::WebSocketClient ws2("ws://localhost:8080/");
  23676. EXPECT_TRUE(ws2.is_valid());
  23677. }
  23678. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23679. Server svr;
  23680. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23681. std::string msg;
  23682. while (ws.read(msg)) {}
  23683. });
  23684. auto port = svr.bind_to_any_port(HOST);
  23685. std::thread t([&]() { svr.listen_after_bind(); });
  23686. svr.wait_until_ready();
  23687. auto another_host = "example.com";
  23688. auto wrong_ip = "192.0.2.1";
  23689. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23690. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  23691. ASSERT_TRUE(client.connect());
  23692. EXPECT_TRUE(client.is_open());
  23693. client.close();
  23694. svr.stop();
  23695. t.join();
  23696. }
  23697. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23698. Server svr;
  23699. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23700. std::string msg;
  23701. while (ws.read(msg)) {}
  23702. });
  23703. auto port = svr.bind_to_any_port(HOST);
  23704. std::thread t([&]() { svr.listen_after_bind(); });
  23705. svr.wait_until_ready();
  23706. auto wrong_ip = "192.0.2.1";
  23707. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23708. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  23709. client.set_connection_timeout(1);
  23710. client.set_read_timeout(1);
  23711. client.set_write_timeout(1);
  23712. EXPECT_FALSE(client.connect());
  23713. EXPECT_FALSE(client.is_open());
  23714. svr.stop();
  23715. t.join();
  23716. }
  23717. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23718. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23719. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23720. // (RFC 6761) is only a map key and the Host header value.
  23721. auto host = "target.invalid";
  23722. Server svr;
  23723. std::string received_host;
  23724. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23725. received_host = req.get_header_value("Host");
  23726. std::string msg;
  23727. while (ws.read(msg)) {}
  23728. });
  23729. auto port = svr.bind_to_any_port(HOST);
  23730. std::thread t([&]() { svr.listen_after_bind(); });
  23731. // ASSERT_* below returns from the test body, which would leave t joinable
  23732. // and make ~thread call std::terminate.
  23733. auto se = detail::scope_exit([&] {
  23734. svr.stop();
  23735. if (t.joinable()) { t.join(); }
  23736. });
  23737. svr.wait_until_ready();
  23738. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23739. std::to_string(port) + "/ws");
  23740. client.set_direct_hostname_addr_map({{host, HOST}});
  23741. ASSERT_TRUE(client.connect());
  23742. EXPECT_TRUE(client.is_open());
  23743. client.close();
  23744. svr.stop();
  23745. t.join();
  23746. // The mapping only redirects the connection; the identity stays host_.
  23747. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23748. }
  23749. class WebSocketIntegrationTest : public ::testing::Test {
  23750. protected:
  23751. void SetUp() override {
  23752. server_ = httplib::detail::make_unique<Server>();
  23753. setup_server();
  23754. start_server();
  23755. }
  23756. void TearDown() override {
  23757. server_->stop();
  23758. if (server_thread_.joinable()) { server_thread_.join(); }
  23759. }
  23760. void setup_server() {
  23761. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23762. std::string msg;
  23763. ws::ReadResult ret;
  23764. while ((ret = ws.read(msg))) {
  23765. if (ret == ws::Binary) {
  23766. ws.send(msg.data(), msg.size());
  23767. } else {
  23768. ws.send(msg);
  23769. }
  23770. }
  23771. });
  23772. server_->WebSocket("/ws-echo-string",
  23773. [](const Request &, ws::WebSocket &ws) {
  23774. std::string msg;
  23775. while (ws.read(msg)) {
  23776. ws.send("echo: " + msg);
  23777. }
  23778. });
  23779. server_->WebSocket(
  23780. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23781. // Echo back request metadata
  23782. ws.send("path:" + req.path);
  23783. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23784. std::string msg;
  23785. while (ws.read(msg)) {}
  23786. });
  23787. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23788. std::string msg;
  23789. ws.read(msg); // wait for a message
  23790. ws.close();
  23791. });
  23792. server_->WebSocket("/ws-close-status",
  23793. [](const Request &, ws::WebSocket &ws) {
  23794. std::string msg;
  23795. ws.read(msg); // wait for a message
  23796. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23797. });
  23798. server_->WebSocket(
  23799. "/ws-subprotocol",
  23800. [](const Request &, ws::WebSocket &ws) {
  23801. std::string msg;
  23802. while (ws.read(msg)) {
  23803. ws.send(msg);
  23804. }
  23805. },
  23806. [](const std::vector<std::string> &protocols) -> std::string {
  23807. for (const auto &p : protocols) {
  23808. if (p == "graphql-ws") { return p; }
  23809. }
  23810. return "";
  23811. });
  23812. server_->WebSocket(
  23813. "/ws-subprotocol-unoffered",
  23814. [](const Request &, ws::WebSocket &ws) {
  23815. std::string msg;
  23816. while (ws.read(msg)) {
  23817. ws.send(msg);
  23818. }
  23819. },
  23820. [](const std::vector<std::string> &) -> std::string {
  23821. return "admin";
  23822. });
  23823. }
  23824. void start_server() {
  23825. port_ = server_->bind_to_any_port(HOST);
  23826. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23827. server_->wait_until_ready();
  23828. }
  23829. std::unique_ptr<Server> server_;
  23830. std::thread server_thread_;
  23831. int port_ = 0;
  23832. };
  23833. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23834. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23835. "/ws-echo");
  23836. ASSERT_TRUE(client.connect());
  23837. ASSERT_TRUE(client.is_open());
  23838. ASSERT_TRUE(client.send("Hello WebSocket"));
  23839. std::string msg;
  23840. EXPECT_EQ(ws::Text, client.read(msg));
  23841. EXPECT_EQ("Hello WebSocket", msg);
  23842. client.close();
  23843. }
  23844. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23845. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23846. "/ws-echo");
  23847. ASSERT_TRUE(client.connect());
  23848. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23849. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23850. std::string msg;
  23851. EXPECT_EQ(ws::Binary, client.read(msg));
  23852. EXPECT_EQ(binary_data, msg);
  23853. client.close();
  23854. }
  23855. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23857. "/ws-echo");
  23858. ASSERT_TRUE(client.connect());
  23859. for (int i = 0; i < 10; i++) {
  23860. auto text = "message " + std::to_string(i);
  23861. ASSERT_TRUE(client.send(text));
  23862. std::string msg;
  23863. ASSERT_TRUE(client.read(msg));
  23864. EXPECT_EQ(text, msg);
  23865. }
  23866. client.close();
  23867. }
  23868. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23869. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23870. "/ws-close");
  23871. ASSERT_TRUE(client.connect());
  23872. // Send a message to trigger the server to close
  23873. ASSERT_TRUE(client.send("trigger close"));
  23874. // The server will close, so read should return false
  23875. std::string msg;
  23876. EXPECT_FALSE(client.read(msg));
  23877. EXPECT_FALSE(client.is_open());
  23878. }
  23879. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23880. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23881. "/ws-echo");
  23882. ASSERT_TRUE(client.connect());
  23883. // 128KB message
  23884. std::string large_data(128 * 1024, 'X');
  23885. ASSERT_TRUE(client.send(large_data));
  23886. std::string msg;
  23887. ASSERT_TRUE(client.read(msg));
  23888. EXPECT_EQ(large_data, msg);
  23889. client.close();
  23890. }
  23891. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23892. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23893. "/ws-echo");
  23894. ASSERT_TRUE(client.connect());
  23895. const int num_threads = 4;
  23896. std::vector<std::thread> threads;
  23897. std::atomic<int> send_count{0};
  23898. for (int t = 0; t < num_threads; t++) {
  23899. threads.emplace_back([&client, &send_count, t]() {
  23900. for (int i = 0; i < 5; i++) {
  23901. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23902. if (client.send(text)) { send_count++; }
  23903. }
  23904. });
  23905. }
  23906. for (auto &th : threads) {
  23907. th.join();
  23908. }
  23909. int received = 0;
  23910. std::string msg;
  23911. while (received < send_count.load()) {
  23912. if (!client.read(msg)) { break; }
  23913. received++;
  23914. }
  23915. EXPECT_EQ(send_count.load(), received);
  23916. client.close();
  23917. }
  23918. TEST_F(WebSocketIntegrationTest, ReadString) {
  23919. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23920. "/ws-echo-string");
  23921. ASSERT_TRUE(client.connect());
  23922. ASSERT_TRUE(client.send("hello"));
  23923. std::string msg;
  23924. ASSERT_TRUE(client.read(msg));
  23925. EXPECT_EQ("echo: hello", msg);
  23926. ASSERT_TRUE(client.send("world"));
  23927. ASSERT_TRUE(client.read(msg));
  23928. EXPECT_EQ("echo: world", msg);
  23929. client.close();
  23930. }
  23931. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23932. Headers headers = {{"X-Test-Header", "test-value"}};
  23933. ws::WebSocketClient client(
  23934. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23935. ASSERT_TRUE(client.connect());
  23936. std::string msg;
  23937. ASSERT_TRUE(client.read(msg));
  23938. EXPECT_EQ("path:/ws-request-info", msg);
  23939. ASSERT_TRUE(client.read(msg));
  23940. EXPECT_EQ("header:test-value", msg);
  23941. client.close();
  23942. }
  23943. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23945. "/ws-echo");
  23946. client.set_read_timeout(1, 0); // 1 second
  23947. ASSERT_TRUE(client.connect());
  23948. // Don't send anything — server echo handler waits for a message, so read()
  23949. // should time out. The connection survives it: nothing was consumed.
  23950. std::string msg;
  23951. EXPECT_EQ(client.read(msg), ws::Timeout);
  23952. EXPECT_TRUE(client.is_open());
  23953. // And it is still usable afterwards.
  23954. EXPECT_TRUE(client.send("after timeout"));
  23955. EXPECT_EQ(client.read(msg), ws::Text);
  23956. EXPECT_EQ(msg, "after timeout");
  23957. }
  23958. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23959. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23960. "/ws-echo");
  23961. client.set_read_timeout(1, 0);
  23962. ASSERT_TRUE(client.connect());
  23963. ASSERT_TRUE(client.send("first"));
  23964. std::string msg;
  23965. ASSERT_EQ(client.read(msg), ws::Text);
  23966. ASSERT_EQ(msg, "first");
  23967. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23968. // not be used with a read timeout: it would reprocess the previous message.
  23969. EXPECT_EQ(client.read(msg), ws::Timeout);
  23970. EXPECT_EQ(msg, "first");
  23971. }
  23972. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23973. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23974. "/ws-echo");
  23975. ASSERT_TRUE(client.connect());
  23976. // Setting it once the connection is open reaches the live stream, not just
  23977. // the seed for the next connect().
  23978. client.set_read_timeout(1, 0);
  23979. std::string msg;
  23980. EXPECT_EQ(client.read(msg), ws::Timeout);
  23981. EXPECT_TRUE(client.is_open());
  23982. }
  23983. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23984. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23985. "/ws-echo");
  23986. client.set_read_timeout(5, 0);
  23987. ASSERT_TRUE(client.connect());
  23988. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23989. // The server should reject it and close the connection.
  23990. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23991. client.send(oversized);
  23992. // The server's read() should have failed due to payload limit,
  23993. // so our read() should return false (connection closed).
  23994. std::string msg;
  23995. EXPECT_FALSE(client.read(msg));
  23996. }
  23997. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23998. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23999. "/ws-echo");
  24000. client.set_read_timeout(10, 0);
  24001. ASSERT_TRUE(client.connect());
  24002. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24003. // This should succeed.
  24004. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24005. ASSERT_TRUE(client.send(at_limit));
  24006. std::string msg;
  24007. ASSERT_TRUE(client.read(msg));
  24008. EXPECT_EQ(at_limit.size(), msg.size());
  24009. client.close();
  24010. }
  24011. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24012. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24013. "/nonexistent");
  24014. auto res = client.connect();
  24015. EXPECT_FALSE(res);
  24016. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24017. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24018. EXPECT_FALSE(client.is_open());
  24019. }
  24020. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24021. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24022. "/ws-echo");
  24023. ASSERT_TRUE(client.connect());
  24024. ASSERT_TRUE(client.send(""));
  24025. std::string msg;
  24026. EXPECT_EQ(ws::Text, client.read(msg));
  24027. EXPECT_EQ("", msg);
  24028. client.close();
  24029. }
  24030. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24031. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24032. "/ws-echo");
  24033. // First connection
  24034. ASSERT_TRUE(client.connect());
  24035. ASSERT_TRUE(client.send("first"));
  24036. std::string msg;
  24037. ASSERT_TRUE(client.read(msg));
  24038. EXPECT_EQ("first", msg);
  24039. client.close();
  24040. EXPECT_FALSE(client.is_open());
  24041. // Reconnect using the same client object
  24042. ASSERT_TRUE(client.connect());
  24043. ASSERT_TRUE(client.is_open());
  24044. ASSERT_TRUE(client.send("second"));
  24045. ASSERT_TRUE(client.read(msg));
  24046. EXPECT_EQ("second", msg);
  24047. client.close();
  24048. }
  24049. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24050. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24051. "/ws-close-status");
  24052. ASSERT_TRUE(client.connect());
  24053. // Trigger the server to close with GoingAway status
  24054. ASSERT_TRUE(client.send("trigger"));
  24055. // read() should return false after receiving the close frame
  24056. std::string msg;
  24057. EXPECT_FALSE(client.read(msg));
  24058. EXPECT_FALSE(client.is_open());
  24059. }
  24060. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24062. "/ws-echo");
  24063. ASSERT_TRUE(client.connect());
  24064. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24065. EXPECT_FALSE(client.is_open());
  24066. }
  24067. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24068. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24069. ws::WebSocketClient client(
  24070. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24071. ASSERT_TRUE(client.connect());
  24072. // Server should have selected graphql-ws
  24073. EXPECT_EQ("graphql-ws", client.subprotocol());
  24074. client.close();
  24075. }
  24076. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24077. Headers headers;
  24078. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24079. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24080. ws::WebSocketClient client(
  24081. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24082. ASSERT_TRUE(client.connect());
  24083. // The offer on the second field line counts too, so graphql-ws is selected
  24084. EXPECT_EQ("graphql-ws", client.subprotocol());
  24085. client.close();
  24086. }
  24087. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24088. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24089. ws::WebSocketClient client(
  24090. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24091. ASSERT_TRUE(client.connect());
  24092. // Server should not have selected any subprotocol
  24093. EXPECT_TRUE(client.subprotocol().empty());
  24094. client.close();
  24095. }
  24096. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24097. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24098. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24099. "/ws-subprotocol-unoffered",
  24100. headers);
  24101. ASSERT_TRUE(client.connect());
  24102. EXPECT_TRUE(client.subprotocol().empty());
  24103. client.close();
  24104. }
  24105. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24106. // Connect without requesting any subprotocol
  24107. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24108. "/ws-subprotocol");
  24109. ASSERT_TRUE(client.connect());
  24110. EXPECT_TRUE(client.subprotocol().empty());
  24111. client.close();
  24112. }
  24113. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24114. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24115. "/ws-echo");
  24116. client.set_tcp_nodelay(true);
  24117. client.set_connection_timeout(3, 0);
  24118. bool socket_options_called = false;
  24119. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24120. ASSERT_TRUE(client.connect());
  24121. ASSERT_TRUE(client.is_open());
  24122. EXPECT_TRUE(socket_options_called);
  24123. ASSERT_TRUE(client.send("hello"));
  24124. std::string msg;
  24125. auto result = client.read(msg);
  24126. EXPECT_EQ(result, ws::ReadResult::Text);
  24127. EXPECT_EQ(msg, "hello");
  24128. client.close();
  24129. }
  24130. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24131. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24132. "/ws-echo");
  24133. client.set_connection_timeout(std::chrono::seconds(3));
  24134. client.set_write_timeout(std::chrono::seconds(3));
  24135. // A sub-second remainder exercises the seconds/microseconds split.
  24136. client.set_read_timeout(std::chrono::milliseconds(1500));
  24137. ASSERT_TRUE(client.connect());
  24138. auto start = std::chrono::steady_clock::now();
  24139. std::string msg;
  24140. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24141. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24142. std::chrono::steady_clock::now() - start)
  24143. .count();
  24144. // Above 1s so that dropping the microseconds half of the split fails here.
  24145. // Ignoring the setter altogether would not reach this line at all: a client
  24146. // waits forever by default.
  24147. EXPECT_GE(elapsed, 1400);
  24148. EXPECT_LT(elapsed, 30000);
  24149. }
  24150. #ifndef _WIN32
  24151. // A send() that times out after part of the data went out returns the count
  24152. // written so far. Every byte of the frame must still be sent, or the peer reads
  24153. // the next frame's header and payload as the rest of this one.
  24154. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24155. signal(SIGPIPE, SIG_IGN);
  24156. const std::string large(4 * 1024 * 1024, 'A');
  24157. std::atomic<bool> large_sent{false};
  24158. std::atomic<bool> small_sent{false};
  24159. Server svr;
  24160. svr.set_write_timeout(0, 500000);
  24161. svr.set_socket_options([](socket_t sock) {
  24162. int size = 8192;
  24163. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24164. reinterpret_cast<const char *>(&size), sizeof(size));
  24165. });
  24166. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24167. large_sent = ws.send(large.data(), large.size());
  24168. small_sent = ws.send("after");
  24169. std::string msg;
  24170. while (ws.read(msg)) {}
  24171. });
  24172. auto port = svr.bind_to_any_port(HOST);
  24173. std::thread t([&]() { svr.listen_after_bind(); });
  24174. auto se = detail::scope_exit([&] {
  24175. svr.stop();
  24176. t.join();
  24177. });
  24178. svr.wait_until_ready();
  24179. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24180. std::to_string(port) + "/ws");
  24181. client.set_read_timeout(5);
  24182. client.set_socket_options([](socket_t sock) {
  24183. int size = 8192;
  24184. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24185. reinterpret_cast<const char *>(&size), sizeof(size));
  24186. });
  24187. ASSERT_TRUE(client.connect());
  24188. // Outlast the server's write timeout, then drain.
  24189. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24190. std::string msg;
  24191. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24192. EXPECT_TRUE(msg == large);
  24193. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24194. EXPECT_EQ("after", msg);
  24195. EXPECT_TRUE(large_sent);
  24196. EXPECT_TRUE(small_sent);
  24197. client.close();
  24198. }
  24199. #endif
  24200. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24201. Server svr;
  24202. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24203. if (!req.has_header("Authorization")) {
  24204. res.status = StatusCode::Unauthorized_401;
  24205. res.set_content("Unauthorized", "text/plain");
  24206. return Server::HandlerResponse::Handled;
  24207. }
  24208. return Server::HandlerResponse::Unhandled;
  24209. });
  24210. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24211. std::string msg;
  24212. while (ws.read(msg)) {
  24213. ws.send(msg);
  24214. }
  24215. });
  24216. auto port = svr.bind_to_any_port("localhost");
  24217. std::thread t([&]() { svr.listen_after_bind(); });
  24218. svr.wait_until_ready();
  24219. // Without Authorization header - should be rejected before upgrade
  24220. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24221. EXPECT_FALSE(client1.connect());
  24222. // The rejection is framed like any other HTTP response
  24223. {
  24224. Client cli("localhost", port);
  24225. Headers headers = {{"Upgrade", "websocket"},
  24226. {"Connection", "Upgrade"},
  24227. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24228. {"Sec-WebSocket-Version", "13"}};
  24229. auto res = cli.Get("/ws", headers);
  24230. ASSERT_TRUE(res);
  24231. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24232. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24233. EXPECT_EQ("Unauthorized", res->body);
  24234. }
  24235. // With Authorization header - should succeed
  24236. Headers headers = {{"Authorization", "Bearer token123"}};
  24237. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24238. headers);
  24239. ASSERT_TRUE(client2.connect());
  24240. ASSERT_TRUE(client2.send("hello"));
  24241. std::string msg;
  24242. ASSERT_TRUE(client2.read(msg));
  24243. EXPECT_EQ("hello", msg);
  24244. client2.close();
  24245. svr.stop();
  24246. t.join();
  24247. }
  24248. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24249. Server svr;
  24250. std::atomic<int> pre_routing_calls{0};
  24251. std::atomic<int> pre_request_calls{0};
  24252. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24253. pre_routing_calls++;
  24254. if (req.path == "/handled") {
  24255. res.set_content("handled", "text/plain");
  24256. return Server::HandlerResponse::Handled;
  24257. }
  24258. return Server::HandlerResponse::Unhandled;
  24259. });
  24260. svr.set_pre_request_handler([&](const Request &, Response &) {
  24261. pre_request_calls++;
  24262. return Server::HandlerResponse::Unhandled;
  24263. });
  24264. svr.Get("/http", [](const Request &, Response &res) {
  24265. res.set_content("http", "text/plain");
  24266. });
  24267. svr.WebSocket("/ws",
  24268. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24269. auto port = svr.bind_to_any_port("localhost");
  24270. std::thread t([&]() { svr.listen_after_bind(); });
  24271. auto se = detail::scope_exit([&] {
  24272. svr.stop();
  24273. t.join();
  24274. });
  24275. svr.wait_until_ready();
  24276. Headers upgrade = {{"Upgrade", "websocket"},
  24277. {"Connection", "Upgrade"},
  24278. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24279. {"Sec-WebSocket-Version", "13"}};
  24280. auto get = [&](const char *path) {
  24281. pre_routing_calls = 0;
  24282. return Client("localhost", port).Get(path, upgrade);
  24283. };
  24284. // No WebSocket route, but an HTTP one
  24285. auto res = get("/http");
  24286. ASSERT_TRUE(res);
  24287. EXPECT_EQ(StatusCode::OK_200, res->status);
  24288. EXPECT_EQ("http", res->body);
  24289. EXPECT_EQ(1, pre_routing_calls);
  24290. EXPECT_EQ(1, pre_request_calls);
  24291. // No route at all
  24292. res = get("/none");
  24293. ASSERT_TRUE(res);
  24294. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24295. EXPECT_EQ(1, pre_routing_calls);
  24296. // Answered by the pre-routing handler
  24297. res = get("/handled");
  24298. ASSERT_TRUE(res);
  24299. EXPECT_EQ(StatusCode::OK_200, res->status);
  24300. EXPECT_EQ("handled", res->body);
  24301. EXPECT_EQ(1, pre_routing_calls);
  24302. // A WebSocket route
  24303. pre_routing_calls = 0;
  24304. pre_request_calls = 0;
  24305. {
  24306. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24307. "/ws");
  24308. ASSERT_TRUE(client.connect());
  24309. std::string msg;
  24310. ASSERT_TRUE(client.read(msg));
  24311. EXPECT_EQ("ws", msg);
  24312. client.close();
  24313. }
  24314. EXPECT_EQ(1, pre_routing_calls);
  24315. EXPECT_EQ(1, pre_request_calls);
  24316. }
  24317. // An upgrade request answered by a hook leaves its body unread, so that body
  24318. // must not be served as the next request on the connection.
  24319. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24320. Server svr;
  24321. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24322. if (req.path == "/pre-routing") {
  24323. res.set_content("pre-routing", "text/plain");
  24324. return Server::HandlerResponse::Handled;
  24325. }
  24326. return Server::HandlerResponse::Unhandled;
  24327. });
  24328. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24329. if (req.matched_route == "/pre-request") {
  24330. res.set_content("pre-request", "text/plain");
  24331. return Server::HandlerResponse::Handled;
  24332. }
  24333. return Server::HandlerResponse::Unhandled;
  24334. });
  24335. svr.Get("/smuggled", [](const Request &, Response &res) {
  24336. res.set_content("smuggled", "text/plain");
  24337. });
  24338. svr.WebSocket("/pre-request",
  24339. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24340. auto port = svr.bind_to_any_port(HOST);
  24341. std::thread t([&]() { svr.listen_after_bind(); });
  24342. auto se = detail::scope_exit([&] {
  24343. svr.stop();
  24344. t.join();
  24345. });
  24346. svr.wait_until_ready();
  24347. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24348. for (auto path : {"/pre-routing", "/pre-request"}) {
  24349. std::string req = std::string("GET ") + path +
  24350. " HTTP/1.1\r\n"
  24351. "Host: localhost\r\n"
  24352. "Upgrade: websocket\r\n"
  24353. "Connection: Upgrade\r\n"
  24354. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24355. "Sec-WebSocket-Version: 13\r\n"
  24356. "Content-Length: " +
  24357. std::to_string(body.size()) + "\r\n\r\n" + body;
  24358. std::string res;
  24359. ASSERT_TRUE(send_request(5, req, &res, port));
  24360. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24361. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24362. // Only one response, and the body was not served as a request
  24363. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24364. }
  24365. }
  24366. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24367. Server svr;
  24368. std::atomic<int> pre_request_calls{0};
  24369. std::atomic<bool> route_matched{false};
  24370. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24371. pre_request_calls++;
  24372. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24373. if (req.get_header_value("Authorization") != "Bearer token123") {
  24374. res.status = StatusCode::Unauthorized_401;
  24375. res.set_content("Unauthorized", "text/plain");
  24376. return Server::HandlerResponse::Handled;
  24377. }
  24378. return Server::HandlerResponse::Unhandled;
  24379. });
  24380. std::atomic<bool> handler_called{false};
  24381. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24382. handler_called = true;
  24383. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24384. });
  24385. auto port = svr.bind_to_any_port("localhost");
  24386. std::thread t([&]() { svr.listen_after_bind(); });
  24387. svr.wait_until_ready();
  24388. // Without Authorization header - should be rejected before upgrade
  24389. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24390. "/ws/1");
  24391. EXPECT_FALSE(client1.connect());
  24392. EXPECT_FALSE(handler_called);
  24393. EXPECT_EQ(1, pre_request_calls);
  24394. EXPECT_TRUE(route_matched);
  24395. // The rejection is an ordinary HTTP response, not a protocol switch
  24396. {
  24397. Client cli("localhost", port);
  24398. Headers headers = {{"Upgrade", "websocket"},
  24399. {"Connection", "Upgrade"},
  24400. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24401. {"Sec-WebSocket-Version", "13"}};
  24402. auto res = cli.Get("/ws/1", headers);
  24403. ASSERT_TRUE(res);
  24404. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24405. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24406. EXPECT_EQ("Unauthorized", res->body);
  24407. }
  24408. EXPECT_FALSE(handler_called);
  24409. // With Authorization header - should succeed
  24410. Headers headers = {{"Authorization", "Bearer token123"}};
  24411. ws::WebSocketClient client2(
  24412. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24413. ASSERT_TRUE(client2.connect());
  24414. std::string msg;
  24415. ASSERT_TRUE(client2.read(msg));
  24416. EXPECT_EQ("/ws/:id 2", msg);
  24417. EXPECT_TRUE(handler_called);
  24418. client2.close();
  24419. svr.stop();
  24420. t.join();
  24421. }
  24422. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24423. static Headers websocket_upgrade_headers() {
  24424. return {{"Upgrade", "websocket"},
  24425. {"Connection", "Upgrade"},
  24426. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24427. {"Sec-WebSocket-Version", "13"},
  24428. {"Sec-WebSocket-Protocol", "chat"}};
  24429. }
  24430. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24431. Server svr;
  24432. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24433. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24434. return Server::HandlerResponse::Unhandled;
  24435. });
  24436. svr.set_pre_request_handler([](const Request &req, Response &) {
  24437. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24438. return Server::HandlerResponse::Unhandled;
  24439. });
  24440. svr.set_exception_handler(
  24441. [](const Request &, Response &res, std::exception_ptr ep) {
  24442. try {
  24443. std::rethrow_exception(ep);
  24444. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24445. });
  24446. auto handler = [](const Request &, ws::WebSocket &) {};
  24447. svr.WebSocket("/pre-routing", handler);
  24448. svr.WebSocket("/pre-request", handler);
  24449. svr.WebSocket("/sub-protocol", handler,
  24450. [](const std::vector<std::string> &) -> std::string {
  24451. throw std::runtime_error("/sub-protocol");
  24452. });
  24453. auto port = svr.bind_to_any_port(HOST);
  24454. ASSERT_GT(port, 0);
  24455. thread t = thread([&] { svr.listen_after_bind(); });
  24456. auto se = detail::scope_exit([&] {
  24457. svr.stop();
  24458. t.join();
  24459. ASSERT_FALSE(svr.is_running());
  24460. });
  24461. svr.wait_until_ready();
  24462. Client cli(HOST, port);
  24463. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24464. auto res = cli.Get(path, websocket_upgrade_headers());
  24465. if (!res) {
  24466. ADD_FAILURE() << path << ": " << to_string(res.error());
  24467. continue;
  24468. }
  24469. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24470. EXPECT_EQ(path, res->body);
  24471. }
  24472. }
  24473. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24474. Server svr;
  24475. svr.set_pre_routing_handler(
  24476. [](const Request &, Response &) -> Server::HandlerResponse {
  24477. throw std::runtime_error("pre-routing");
  24478. });
  24479. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24480. auto port = svr.bind_to_any_port(HOST);
  24481. ASSERT_GT(port, 0);
  24482. thread t = thread([&] { svr.listen_after_bind(); });
  24483. auto se = detail::scope_exit([&] {
  24484. svr.stop();
  24485. t.join();
  24486. ASSERT_FALSE(svr.is_running());
  24487. });
  24488. svr.wait_until_ready();
  24489. Client cli(HOST, port);
  24490. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24491. ASSERT_TRUE(res) << to_string(res.error());
  24492. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24493. }
  24494. #endif
  24495. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24496. Server svr;
  24497. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24498. // A read timeout is how a handler gets control back. Without it, a handler
  24499. // parked in read() can never write on the connection it is reading.
  24500. ws.set_read_timeout(std::chrono::milliseconds(100));
  24501. std::string msg;
  24502. while (ws.is_open()) {
  24503. auto r = ws.read(msg);
  24504. if (r == httplib::ws::Timeout) {
  24505. ws.send("tick");
  24506. continue;
  24507. }
  24508. if (r == httplib::ws::Fail) { break; }
  24509. ws.send(msg);
  24510. }
  24511. });
  24512. auto port = svr.bind_to_any_port("localhost");
  24513. std::thread t([&]() { svr.listen_after_bind(); });
  24514. svr.wait_until_ready();
  24515. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24516. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24517. ASSERT_TRUE(client.connect());
  24518. // The client sends nothing, so anything it receives came out of the
  24519. // handler's timeout path.
  24520. std::string msg;
  24521. ASSERT_EQ(client.read(msg), ws::Text);
  24522. EXPECT_EQ("tick", msg);
  24523. client.close();
  24524. svr.stop();
  24525. t.join();
  24526. }
  24527. // Stream::read may return fewer bytes than asked for. This is that contract at
  24528. // its worst -- one byte per call -- which is what a frame header straddling a
  24529. // read buffer's boundary looks like to the frame parser.
  24530. class WsByteAtATimeStream : public Stream {
  24531. public:
  24532. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24533. bool is_readable() const override { return true; }
  24534. bool wait_readable() const override { return true; }
  24535. bool wait_writable() const override { return true; }
  24536. ssize_t read(char *ptr, size_t size) override {
  24537. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24538. *ptr = data_[pos_++];
  24539. return 1;
  24540. }
  24541. ssize_t write(const char *, size_t size) override {
  24542. return static_cast<ssize_t>(size);
  24543. }
  24544. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24545. ip = "127.0.0.1";
  24546. port = 0;
  24547. }
  24548. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24549. ip = "127.0.0.1";
  24550. port = 0;
  24551. }
  24552. socket_t socket() const override { return INVALID_SOCKET; }
  24553. time_t duration() const override { return 0; }
  24554. private:
  24555. std::string data_;
  24556. size_t pos_ = 0;
  24557. };
  24558. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24559. // The payload uses the 16-bit extended length, so the header, the length
  24560. // and the mask key are all multi-byte fields here. Each used to be read
  24561. // with a single read() call, which fails as soon as one is split. The
  24562. // payload is also a little over one read chunk, so it is read in two.
  24563. std::string body;
  24564. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24565. body += static_cast<char>(i % 251);
  24566. }
  24567. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24568. std::string frame;
  24569. frame += static_cast<char>(0x81); // FIN + Text
  24570. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24571. frame += static_cast<char>(body.size() >> 8);
  24572. frame += static_cast<char>(body.size() & 0xff);
  24573. for (size_t i = 0; i < 4; i++) {
  24574. frame += static_cast<char>(mask[i]);
  24575. }
  24576. for (size_t i = 0; i < body.size(); i++) {
  24577. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24578. }
  24579. WsByteAtATimeStream strm(frame);
  24580. ws::Opcode opcode;
  24581. std::string payload;
  24582. bool fin = false;
  24583. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24584. /*expect_masked=*/true, body.size()),
  24585. ws::impl::FrameRead::Ok);
  24586. EXPECT_TRUE(fin);
  24587. EXPECT_EQ(opcode, ws::Opcode::Text);
  24588. EXPECT_EQ(payload, body);
  24589. }
  24590. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24591. std::string body(2000, 'x');
  24592. std::string frame;
  24593. frame += static_cast<char>(0x82); // FIN + Binary
  24594. frame += static_cast<char>(126); // 16-bit length follows
  24595. frame += static_cast<char>(body.size() >> 8);
  24596. frame += static_cast<char>(body.size() & 0xff);
  24597. frame += body;
  24598. detail::BufferStream strm;
  24599. strm.write(frame.data(), frame.size());
  24600. ws::Opcode opcode;
  24601. std::string payload;
  24602. bool fin;
  24603. EXPECT_EQ(
  24604. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24605. ws::impl::FrameRead::Ok);
  24606. EXPECT_EQ(body, payload);
  24607. }
  24608. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24609. // The header announces the largest payload allowed, and only 3 bytes of it
  24610. // ever arrive.
  24611. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24612. std::string frame;
  24613. frame += static_cast<char>(0x82); // FIN + Binary
  24614. frame += static_cast<char>(127); // 64-bit length follows
  24615. for (int shift = 56; shift >= 0; shift -= 8) {
  24616. frame += static_cast<char>((len >> shift) & 0xff);
  24617. }
  24618. frame += "abc";
  24619. detail::BufferStream strm;
  24620. strm.write(frame.data(), frame.size());
  24621. ws::Opcode opcode;
  24622. std::string payload;
  24623. bool fin;
  24624. EXPECT_EQ(
  24625. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24626. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24627. ws::impl::FrameRead::Fail);
  24628. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24629. }
  24630. TEST(WebSocketTest, QueryStringInHandshake) {
  24631. Server svr;
  24632. std::mutex mtx;
  24633. std::string received_target;
  24634. std::string received_token;
  24635. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24636. {
  24637. std::lock_guard<std::mutex> lock(mtx);
  24638. received_target = req.target;
  24639. if (req.has_param("token")) {
  24640. received_token = req.get_param_value("token");
  24641. }
  24642. }
  24643. std::string msg;
  24644. while (ws.read(msg)) {
  24645. ws.send(msg);
  24646. }
  24647. });
  24648. auto port = svr.bind_to_any_port("localhost");
  24649. std::thread t([&]() { svr.listen_after_bind(); });
  24650. svr.wait_until_ready();
  24651. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24652. "/ws?token=ABC&session=123");
  24653. ASSERT_TRUE(client.connect());
  24654. // Round-trip ensures the handler has run and captured the request.
  24655. ASSERT_TRUE(client.send("hello"));
  24656. std::string msg;
  24657. ASSERT_TRUE(client.read(msg));
  24658. EXPECT_EQ("hello", msg);
  24659. client.close();
  24660. {
  24661. std::lock_guard<std::mutex> lock(mtx);
  24662. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24663. EXPECT_EQ("ABC", received_token);
  24664. }
  24665. svr.stop();
  24666. t.join();
  24667. }
  24668. // Run a handshake against a throwaway server and hand the request the server
  24669. // received back to the caller, so tests can assert on the headers the client
  24670. // actually put on the wire.
  24671. static void capture_websocket_handshake_request(
  24672. const Headers &client_headers,
  24673. std::function<void(const Request &, int port)> verify) {
  24674. Server svr;
  24675. std::mutex mtx;
  24676. Request received;
  24677. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24678. {
  24679. std::lock_guard<std::mutex> lock(mtx);
  24680. received = req;
  24681. }
  24682. std::string msg;
  24683. while (ws.read(msg)) {
  24684. ws.send(msg);
  24685. }
  24686. });
  24687. auto port = svr.bind_to_any_port("localhost");
  24688. std::thread t([&]() { svr.listen_after_bind(); });
  24689. auto se = detail::scope_exit([&] {
  24690. svr.stop();
  24691. t.join();
  24692. });
  24693. svr.wait_until_ready();
  24694. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24695. client_headers);
  24696. ASSERT_TRUE(client.connect());
  24697. ASSERT_TRUE(client.send("hello"));
  24698. std::string msg;
  24699. ASSERT_TRUE(client.read(msg));
  24700. client.close();
  24701. {
  24702. std::lock_guard<std::mutex> lock(mtx);
  24703. verify(received, port);
  24704. }
  24705. }
  24706. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24707. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24708. // Non-default port must be present in the Host header. Default ports
  24709. // (80/443) are omitted; that logic is covered by
  24710. // MakeHostAndPortStringTest.
  24711. EXPECT_EQ("localhost:" + std::to_string(port),
  24712. req.get_header_value("Host"));
  24713. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24714. req.get_header_value("User-Agent"));
  24715. EXPECT_FALSE(req.has_header("Accept"));
  24716. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24717. EXPECT_FALSE(req.has_header("Content-Length"));
  24718. });
  24719. }
  24720. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24721. capture_websocket_handshake_request(
  24722. {{"Host", "example.com"},
  24723. {"User-Agent", "custom-agent"},
  24724. {"X-Custom", "value"}},
  24725. [](const Request &req, int) {
  24726. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24727. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24728. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24729. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24730. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24731. });
  24732. }
  24733. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24734. capture_websocket_handshake_request(
  24735. {{"Upgrade", "bogus"},
  24736. {"Connection", "close"},
  24737. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24738. {"Sec-WebSocket-Version", "8"}},
  24739. [](const Request &req, int) {
  24740. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24741. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24742. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24743. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24744. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24745. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24746. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24747. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24748. req.get_header_value("Sec-WebSocket-Key"));
  24749. });
  24750. }
  24751. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24752. // A header the client refuses to send must abort the handshake before any
  24753. // part of it reaches the wire; a lone request line would otherwise sit in
  24754. // the peer's buffer as a truncated request.
  24755. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24756. ASSERT_NE(INVALID_SOCKET, srv);
  24757. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24758. sockaddr_in addr{};
  24759. addr.sin_family = AF_INET;
  24760. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24761. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24762. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24763. ASSERT_EQ(0, ::listen(srv, 1));
  24764. sockaddr_in bound{};
  24765. socklen_t bound_len = sizeof(bound);
  24766. ASSERT_EQ(
  24767. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24768. auto port = ntohs(bound.sin_port);
  24769. ssize_t received = -1;
  24770. std::thread t([&] {
  24771. // Bound every blocking call so a regression fails the test with a bad
  24772. // value instead of hanging the suite.
  24773. fd_set rfds;
  24774. FD_ZERO(&rfds);
  24775. FD_SET(srv, &rfds);
  24776. timeval tv{5, 0};
  24777. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24778. 0) {
  24779. return;
  24780. }
  24781. sockaddr_in cli_addr{};
  24782. socklen_t cli_len = sizeof(cli_addr);
  24783. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24784. if (cli == INVALID_SOCKET) { return; }
  24785. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24786. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24787. char buf[4096];
  24788. received = ::recv(cli, buf, sizeof(buf), 0);
  24789. });
  24790. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24791. // connect() has already shut the socket down by the time it returns false,
  24792. // so the peer sees EOF without waiting for the client to be destroyed.
  24793. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24794. {{"X-Bad", "a\r\nInjected: 1"}});
  24795. EXPECT_FALSE(client.connect());
  24796. t.join();
  24797. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24798. EXPECT_EQ(0, received);
  24799. }
  24800. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24801. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24802. // contains "upgrade" as a substring is a different token and must not
  24803. // start a WebSocket handshake.
  24804. auto make_request = [](const std::vector<std::string> &connection_values) {
  24805. Request req;
  24806. req.method = "GET";
  24807. req.headers.emplace("Upgrade", "websocket");
  24808. for (const auto &value : connection_values) {
  24809. req.headers.emplace("Connection", value);
  24810. }
  24811. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24812. req.headers.emplace("Sec-WebSocket-Version", "13");
  24813. return req;
  24814. };
  24815. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24816. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24817. EXPECT_TRUE(
  24818. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24819. EXPECT_TRUE(
  24820. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24821. EXPECT_TRUE(
  24822. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24823. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24824. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24825. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24826. EXPECT_FALSE(
  24827. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24828. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24829. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24830. }
  24831. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24832. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24833. // asks recipients to match each protocol-name case-insensitively, and RFC
  24834. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24835. // client naming websocket alongside another protocol, or on a second field
  24836. // line, is offering websocket; a value that merely contains "websocket" as a
  24837. // substring is a different protocol name and is not.
  24838. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24839. Request req;
  24840. req.method = "GET";
  24841. for (const auto &value : upgrade_values) {
  24842. req.headers.emplace("Upgrade", value);
  24843. }
  24844. req.headers.emplace("Connection", "Upgrade");
  24845. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24846. req.headers.emplace("Sec-WebSocket-Version", "13");
  24847. return req;
  24848. };
  24849. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24850. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24851. EXPECT_TRUE(
  24852. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24853. EXPECT_TRUE(
  24854. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24855. EXPECT_TRUE(
  24856. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24857. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24858. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24859. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24860. EXPECT_FALSE(
  24861. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24862. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24863. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24864. }
  24865. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24866. Server svr;
  24867. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24868. auto port = svr.bind_to_any_port("localhost");
  24869. std::thread t([&]() { svr.listen_after_bind(); });
  24870. auto se = detail::scope_exit([&] {
  24871. svr.stop();
  24872. t.join();
  24873. });
  24874. svr.wait_until_ready();
  24875. Headers headers = {{"Upgrade", "websocket"},
  24876. {"Connection", "notupgrade"},
  24877. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24878. {"Sec-WebSocket-Version", "13"}};
  24879. Client cli("localhost", port);
  24880. auto res = cli.Get("/ws", headers);
  24881. // The route exists only as a WebSocket route, so a request that fails the
  24882. // handshake check falls through to ordinary routing.
  24883. ASSERT_TRUE(res);
  24884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24885. }
  24886. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24887. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24888. // Connection value is the only thing left for the client to reject.
  24889. Server svr;
  24890. svr.Get("/ws", [](const Request &req, Response &res) {
  24891. res.status = StatusCode::SwitchingProtocol_101;
  24892. res.set_header("Upgrade", "websocket");
  24893. res.set_header("Connection", "notupgrade");
  24894. res.set_header("Sec-WebSocket-Accept",
  24895. detail::websocket_accept_key(
  24896. req.get_header_value("Sec-WebSocket-Key")));
  24897. });
  24898. auto port = svr.bind_to_any_port("localhost");
  24899. std::thread t([&]() { svr.listen_after_bind(); });
  24900. auto se = detail::scope_exit([&] {
  24901. svr.stop();
  24902. t.join();
  24903. });
  24904. svr.wait_until_ready();
  24905. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24906. auto res = client.connect();
  24907. EXPECT_FALSE(res);
  24908. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24909. EXPECT_FALSE(client.is_open());
  24910. }
  24911. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24912. Server svr;
  24913. svr.Get("/ws", [](const Request &req, Response &res) {
  24914. res.status = StatusCode::SwitchingProtocol_101;
  24915. res.set_header("Upgrade", "websocket");
  24916. res.set_header("Connection", "Upgrade");
  24917. res.set_header("Sec-WebSocket-Accept",
  24918. detail::websocket_accept_key(
  24919. req.get_header_value("Sec-WebSocket-Key")));
  24920. res.set_header("Sec-WebSocket-Protocol", "admin");
  24921. });
  24922. auto port = svr.bind_to_any_port("localhost");
  24923. std::thread t([&]() { svr.listen_after_bind(); });
  24924. auto se = detail::scope_exit([&] {
  24925. svr.stop();
  24926. t.join();
  24927. });
  24928. svr.wait_until_ready();
  24929. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24930. // Server selects a subprotocol the client never offered
  24931. {
  24932. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24933. ws::WebSocketClient client(url, headers);
  24934. auto res = client.connect();
  24935. EXPECT_FALSE(res);
  24936. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24937. EXPECT_FALSE(client.is_open());
  24938. EXPECT_TRUE(client.subprotocol().empty());
  24939. }
  24940. // Client offered none but the server named one anyway
  24941. {
  24942. ws::WebSocketClient client(url);
  24943. auto res = client.connect();
  24944. EXPECT_FALSE(res);
  24945. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24946. EXPECT_FALSE(client.is_open());
  24947. EXPECT_TRUE(client.subprotocol().empty());
  24948. }
  24949. }
  24950. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24951. // The socket path doubles as the URL host, so it must not contain '/'.
  24952. const char *shard = getenv("GTEST_SHARD_INDEX");
  24953. const std::string sock_path =
  24954. shard ? std::string("httplib-ws-") + shard + ".sock"
  24955. : std::string("httplib-ws.sock");
  24956. std::remove(sock_path.c_str());
  24957. Server svr;
  24958. std::mutex mtx;
  24959. std::string received_host;
  24960. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24961. {
  24962. std::lock_guard<std::mutex> lock(mtx);
  24963. received_host = req.get_header_value("Host");
  24964. }
  24965. std::string msg;
  24966. while (ws.read(msg)) {
  24967. ws.send(msg);
  24968. }
  24969. });
  24970. svr.set_address_family(AF_UNIX);
  24971. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24972. auto se = detail::scope_exit([&] {
  24973. svr.stop();
  24974. t.join();
  24975. std::remove(sock_path.c_str());
  24976. });
  24977. svr.wait_until_ready();
  24978. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24979. client.set_address_family(AF_UNIX);
  24980. ASSERT_TRUE(client.connect());
  24981. ASSERT_TRUE(client.send("hello"));
  24982. std::string msg;
  24983. ASSERT_TRUE(client.read(msg));
  24984. client.close();
  24985. {
  24986. std::lock_guard<std::mutex> lock(mtx);
  24987. // There is no host:port for a Unix socket, so the same "localhost"
  24988. // placeholder the HTTP client uses is expected.
  24989. EXPECT_EQ("localhost", received_host);
  24990. }
  24991. }
  24992. // Two threads must never parse WebSocket frames from the same stream.
  24993. // close() used to read the peer's Close reply with its own frame read, so it
  24994. // raced a reader thread that was in the middle of a payload: the payload loop
  24995. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24996. // so bytes taken by close() were replaced with bytes from further along the
  24997. // stream. The message kept its length and silently changed content.
  24998. //
  24999. // The raw peer below sends a frame header plus part of the payload, waits for
  25000. // the handler to call close(), and only then sends the rest. Whichever thread
  25001. // would win the race for those bytes, the message must arrive intact, because
  25002. // close() must not touch the stream while read() owns it.
  25003. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25004. #ifndef _WIN32
  25005. signal(SIGPIPE, SIG_IGN);
  25006. #endif
  25007. const size_t payload_len = 120; // fits the 7-bit length field
  25008. const size_t prefix_len = 8;
  25009. const int attempts = 8;
  25010. std::string expected(payload_len, '\0');
  25011. for (size_t i = 0; i < payload_len; i++) {
  25012. expected[i] = static_cast<char>('a' + i % 26);
  25013. }
  25014. std::atomic<bool> peer_stalled{false};
  25015. std::atomic<bool> handler_done{false};
  25016. std::mutex received_mutex;
  25017. std::vector<std::string> received;
  25018. // Bound every wait, so a regression fails the test instead of hanging the
  25019. // suite.
  25020. auto wait_for = [](const std::atomic<bool> &flag) {
  25021. for (int i = 0; i < 500 && !flag; i++) {
  25022. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25023. }
  25024. };
  25025. Server svr;
  25026. svr.set_websocket_ping_interval(0);
  25027. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25028. std::thread reader([&]() {
  25029. std::string msg;
  25030. while (ws.read(msg)) {
  25031. std::lock_guard<std::mutex> guard(received_mutex);
  25032. received.push_back(msg);
  25033. }
  25034. });
  25035. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25036. // inside read_websocket_frame() when close() runs.
  25037. wait_for(peer_stalled);
  25038. ws.close();
  25039. reader.join();
  25040. handler_done = true;
  25041. });
  25042. auto port = svr.bind_to_any_port("127.0.0.1");
  25043. std::thread t([&]() { svr.listen_after_bind(); });
  25044. auto se = detail::scope_exit([&] {
  25045. svr.stop();
  25046. t.join();
  25047. });
  25048. svr.wait_until_ready();
  25049. auto send_bytes = [](socket_t s, const std::string &data) {
  25050. #ifdef _WIN32
  25051. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25052. #else
  25053. auto n = ::send(s, data.data(), data.size(), 0);
  25054. #endif
  25055. return n == static_cast<decltype(n)>(data.size());
  25056. };
  25057. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25058. // Every length used here fits the 7-bit length field.
  25059. auto masked_header = [](uint8_t first_byte, size_t len) {
  25060. std::string h;
  25061. h += static_cast<char>(first_byte);
  25062. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25063. h.append(4, '\0'); // mask key
  25064. return h;
  25065. };
  25066. for (int attempt = 0; attempt < attempts; attempt++) {
  25067. peer_stalled = false;
  25068. handler_done = false;
  25069. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25070. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25071. auto se_sock = detail::scope_exit([&] {
  25072. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25073. });
  25074. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25075. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25076. sockaddr_in addr{};
  25077. addr.sin_family = AF_INET;
  25078. addr.sin_port = htons(static_cast<uint16_t>(port));
  25079. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25080. ASSERT_EQ(
  25081. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25082. << "attempt " << attempt;
  25083. ASSERT_TRUE(send_bytes(sock,
  25084. "GET /ws HTTP/1.1\r\n"
  25085. "Host: 127.0.0.1\r\n"
  25086. "Upgrade: websocket\r\n"
  25087. "Connection: Upgrade\r\n"
  25088. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25089. "Sec-WebSocket-Version: 13\r\n"
  25090. "\r\n"))
  25091. << "attempt " << attempt;
  25092. std::string response;
  25093. while (response.find("\r\n\r\n") == std::string::npos) {
  25094. char buf[512];
  25095. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25096. if (n <= 0) { break; }
  25097. response.append(buf, static_cast<size_t>(n));
  25098. }
  25099. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25100. << "attempt " << attempt;
  25101. // Send the header of a Binary message but only the first prefix_len bytes
  25102. // of its payload, leaving the reader thread stalled inside the payload.
  25103. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25104. expected.substr(0, prefix_len)))
  25105. << "attempt " << attempt;
  25106. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25107. peer_stalled = true;
  25108. // Let close() send its Close frame and park in its own read before the
  25109. // rest of the payload arrives, so both threads are waiting for it.
  25110. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25111. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25112. close_frame += static_cast<char>(0x03); // status 1000
  25113. close_frame += static_cast<char>(0xE8);
  25114. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25115. << "attempt " << attempt;
  25116. // Closing the peer releases the reader thread even on the buggy path,
  25117. // where it waits for bytes another thread already consumed.
  25118. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25119. detail::close_socket(sock);
  25120. sock = INVALID_SOCKET;
  25121. wait_for(handler_done);
  25122. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25123. }
  25124. std::lock_guard<std::mutex> guard(received_mutex);
  25125. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25126. << "a message in flight when close() ran was dropped";
  25127. for (size_t i = 0; i < received.size(); i++) {
  25128. EXPECT_EQ(expected, received[i]) << "message " << i;
  25129. }
  25130. }
  25131. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25132. // returning the socket, or INVALID_SOCKET.
  25133. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25134. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25135. if (sock == INVALID_SOCKET) { return sock; }
  25136. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25137. sockaddr_in addr{};
  25138. addr.sin_family = AF_INET;
  25139. addr.sin_port = htons(static_cast<uint16_t>(port));
  25140. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25141. std::string req = "GET " + path +
  25142. " HTTP/1.1\r\n"
  25143. "Host: 127.0.0.1\r\n"
  25144. "Upgrade: websocket\r\n"
  25145. "Connection: Upgrade\r\n"
  25146. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25147. "Sec-WebSocket-Version: 13\r\n"
  25148. "\r\n";
  25149. std::string res;
  25150. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25151. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25152. static_cast<ssize_t>(req.size())) {
  25153. char c;
  25154. while (res.find("\r\n\r\n") == std::string::npos &&
  25155. ::recv(sock, &c, 1, 0) == 1) {
  25156. res += c;
  25157. }
  25158. }
  25159. if (res.find(" 101 ") == std::string::npos) {
  25160. detail::close_socket(sock);
  25161. return INVALID_SOCKET;
  25162. }
  25163. return sock;
  25164. }
  25165. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25166. // The payload must fit the 7-bit length field.
  25167. static std::string masked_frame(uint8_t first_byte,
  25168. const std::string &payload) {
  25169. std::string f;
  25170. f += static_cast<char>(first_byte);
  25171. f += static_cast<char>(0x80 | payload.size());
  25172. f.append(4, '\0');
  25173. return f + payload;
  25174. }
  25175. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25176. std::atomic<bool> done{false};
  25177. std::string received;
  25178. Server svr;
  25179. svr.set_websocket_ping_interval(0);
  25180. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25181. std::string msg;
  25182. if (ws.read(msg) == ws::Binary) { received = msg; }
  25183. done = true;
  25184. });
  25185. auto port = svr.bind_to_any_port("127.0.0.1");
  25186. std::thread t([&]() { svr.listen_after_bind(); });
  25187. auto se = detail::scope_exit([&] {
  25188. svr.stop();
  25189. t.join();
  25190. });
  25191. svr.wait_until_ready();
  25192. auto sock = connect_raw_websocket(port, "/ws");
  25193. ASSERT_NE(INVALID_SOCKET, sock);
  25194. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25195. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25196. masked_frame(0x89, "p") + // FIN + Ping
  25197. masked_frame(0x80, "lo"); // FIN + Continuation
  25198. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25199. for (int i = 0; i < 500 && !done; i++) {
  25200. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25201. }
  25202. ASSERT_TRUE(done);
  25203. EXPECT_EQ("Hello", received);
  25204. // The Ping between the fragments is answered with a Pong.
  25205. char pong[3];
  25206. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25207. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25208. }
  25209. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25210. Server svr;
  25211. svr.set_websocket_ping_interval(-1);
  25212. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25213. std::string msg;
  25214. while (ws.read(msg)) {}
  25215. });
  25216. auto port = svr.bind_to_any_port("127.0.0.1");
  25217. std::thread t([&]() { svr.listen_after_bind(); });
  25218. auto se = detail::scope_exit([&] {
  25219. svr.stop();
  25220. t.join();
  25221. });
  25222. svr.wait_until_ready();
  25223. auto sock = connect_raw_websocket(port, "/ws");
  25224. ASSERT_NE(INVALID_SOCKET, sock);
  25225. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25226. // Nothing comes while the client stays quiet.
  25227. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25228. char c;
  25229. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25230. }
  25231. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25232. // and that has to end a read() already waiting on the peer, on every platform.
  25233. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25234. // The peer sends no pings, and its handler never calls read(), which is
  25235. // where pongs are written.
  25236. std::mutex mutex;
  25237. std::condition_variable cv;
  25238. auto release = false;
  25239. svr.set_websocket_ping_interval(0);
  25240. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25241. std::unique_lock<std::mutex> lock(mutex);
  25242. cv.wait(lock, [&] { return release; });
  25243. });
  25244. auto port = svr.bind_to_any_port(HOST);
  25245. std::thread t([&]() { svr.listen_after_bind(); });
  25246. auto se = detail::scope_exit([&] {
  25247. {
  25248. std::lock_guard<std::mutex> lock(mutex);
  25249. release = true;
  25250. }
  25251. cv.notify_all();
  25252. svr.stop();
  25253. t.join();
  25254. });
  25255. svr.wait_until_ready();
  25256. ws::WebSocketClient client(std::string(scheme) +
  25257. "://localhost:" + std::to_string(port) + "/ws");
  25258. #ifdef CPPHTTPLIB_SSL_ENABLED
  25259. client.enable_server_certificate_verification(false);
  25260. #endif
  25261. // A ping a second, given up on after two go unanswered: about 3s
  25262. client.set_websocket_ping_interval(1);
  25263. client.set_websocket_max_missed_pongs(2);
  25264. // Well past that, so that a read the timeout ends instead stands out
  25265. client.set_read_timeout(10);
  25266. ASSERT_TRUE(client.connect());
  25267. auto start = std::chrono::steady_clock::now();
  25268. std::string msg;
  25269. EXPECT_EQ(ws::Fail, client.read(msg));
  25270. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25271. std::chrono::steady_clock::now() - start)
  25272. .count(),
  25273. 6000);
  25274. EXPECT_FALSE(client.is_open());
  25275. }
  25276. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25277. Server svr;
  25278. check_pong_timeout_ends_read(svr, "ws");
  25279. }
  25280. #ifdef CPPHTTPLIB_SSL_ENABLED
  25281. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25282. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25283. ASSERT_TRUE(svr.is_valid());
  25284. check_pong_timeout_ends_read(svr, "wss");
  25285. }
  25286. #endif
  25287. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25288. Server svr;
  25289. svr.set_websocket_ping_interval(0);
  25290. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25291. std::string msg;
  25292. while (ws.read(msg)) {}
  25293. });
  25294. auto port = svr.bind_to_any_port("127.0.0.1");
  25295. std::thread t([&]() { svr.listen_after_bind(); });
  25296. auto se = detail::scope_exit([&] {
  25297. svr.stop();
  25298. t.join();
  25299. });
  25300. svr.wait_until_ready();
  25301. // Each Close payload and the reply it should get: an echo when valid, 1002
  25302. // otherwise.
  25303. std::vector<std::pair<std::string, std::string>> cases = {
  25304. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25305. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25306. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25307. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25308. };
  25309. // Also between the fragments of a message.
  25310. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25311. for (const auto &c : cases) {
  25312. auto sock = connect_raw_websocket(port, "/ws");
  25313. ASSERT_NE(INVALID_SOCKET, sock);
  25314. auto frames = prefix + masked_frame(0x88, c.first);
  25315. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25316. std::string reply;
  25317. char buf[256];
  25318. while (reply.size() < 2 + c.second.size()) {
  25319. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25320. if (n <= 0) { break; }
  25321. reply.append(buf, static_cast<size_t>(n));
  25322. }
  25323. detail::close_socket(sock);
  25324. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25325. c.second,
  25326. reply);
  25327. }
  25328. }
  25329. }
  25330. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25331. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25332. protected:
  25333. void SetUp() override {
  25334. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25335. SERVER_PRIVATE_KEY_FILE);
  25336. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25337. std::string msg;
  25338. ws::ReadResult ret;
  25339. while ((ret = ws.read(msg))) {
  25340. if (ret == ws::Binary) {
  25341. ws.send(msg.data(), msg.size());
  25342. } else {
  25343. ws.send(msg);
  25344. }
  25345. }
  25346. });
  25347. port_ = server_->bind_to_any_port(HOST);
  25348. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25349. server_->wait_until_ready();
  25350. }
  25351. void TearDown() override {
  25352. server_->stop();
  25353. if (server_thread_.joinable()) { server_thread_.join(); }
  25354. }
  25355. std::unique_ptr<SSLServer> server_;
  25356. std::thread server_thread_;
  25357. int port_ = 0;
  25358. };
  25359. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25360. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25361. {
  25362. ws::WebSocketClient client(url);
  25363. client.enable_server_certificate_verification(false);
  25364. auto calls = 0;
  25365. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25366. calls++;
  25367. return false;
  25368. });
  25369. EXPECT_FALSE(client.connect());
  25370. EXPECT_GT(calls, 0);
  25371. }
  25372. {
  25373. ws::WebSocketClient client(url);
  25374. client.enable_server_certificate_verification(false);
  25375. client.set_session_verifier([](tls::session_t) {
  25376. return SSLVerifierResponse::CertificateRejected;
  25377. });
  25378. EXPECT_FALSE(client.connect());
  25379. }
  25380. {
  25381. ws::WebSocketClient client(url);
  25382. client.enable_server_certificate_verification(false);
  25383. client.set_session_verifier([](tls::session_t) {
  25384. return SSLVerifierResponse::CertificateAccepted;
  25385. });
  25386. EXPECT_TRUE(client.connect());
  25387. }
  25388. }
  25389. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25390. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25391. "/ws-echo");
  25392. client.enable_server_certificate_verification(false);
  25393. ASSERT_TRUE(client.connect());
  25394. ASSERT_TRUE(client.is_open());
  25395. ASSERT_TRUE(client.send("Hello WSS"));
  25396. std::string msg;
  25397. EXPECT_EQ(ws::Text, client.read(msg));
  25398. EXPECT_EQ("Hello WSS", msg);
  25399. client.close();
  25400. }
  25401. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25402. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25403. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25404. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25405. // client (without calling close() first) is the only path that runs
  25406. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25407. // bug exactly.
  25408. //
  25409. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25410. // when linked against an instrumented libssl; run under Valgrind to catch it
  25411. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25412. // suite (the freed session otherwise stalls on the close handshake) — this test
  25413. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25414. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25415. {
  25416. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25417. "/ws-echo");
  25418. client.enable_server_certificate_verification(false);
  25419. client.set_read_timeout(2, 0);
  25420. client.set_write_timeout(2, 0);
  25421. ASSERT_TRUE(client.connect());
  25422. ASSERT_TRUE(client.is_open());
  25423. ASSERT_TRUE(client.send("still open"));
  25424. // Intentionally do NOT call client.close(): leaving scope runs
  25425. // shutdown_and_close() with the WebSocket still open, which must send the
  25426. // close frame while the TLS session is still alive.
  25427. }
  25428. }
  25429. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25430. // shutdown_and_close() at the start of connect(), reproducing the same
  25431. // use-after-free within the test body rather than at scope exit. The second
  25432. // connect must succeed and echo, proving the close handshake ran over a live
  25433. // session. See the note above about memory-tool requirements.
  25434. TEST_F(WebSocketSSLIntegrationTest,
  25435. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25436. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25437. "/ws-echo");
  25438. client.enable_server_certificate_verification(false);
  25439. client.set_read_timeout(2, 0);
  25440. client.set_write_timeout(2, 0);
  25441. ASSERT_TRUE(client.connect());
  25442. ASSERT_TRUE(client.is_open());
  25443. ASSERT_TRUE(client.send("still open"));
  25444. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25445. // the still-open connection, which must not touch a freed TLS session.
  25446. ASSERT_TRUE(client.connect());
  25447. ASSERT_TRUE(client.is_open());
  25448. ASSERT_TRUE(client.send("after reconnect"));
  25449. std::string msg;
  25450. EXPECT_EQ(ws::Text, client.read(msg));
  25451. EXPECT_EQ("after reconnect", msg);
  25452. client.close();
  25453. }
  25454. #endif
  25455. #ifdef CPPHTTPLIB_SSL_ENABLED
  25456. class WebSocketSSLCATest : public ::testing::Test {
  25457. protected:
  25458. void SetUp() override {
  25459. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25460. SERVER_PRIVATE_KEY_FILE);
  25461. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25462. std::string msg;
  25463. while (ws.read(msg)) {
  25464. ws.send(msg);
  25465. }
  25466. });
  25467. port_ = server_->bind_to_any_port("127.0.0.1");
  25468. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25469. server_->wait_until_ready();
  25470. }
  25471. void TearDown() override {
  25472. server_->stop();
  25473. if (server_thread_.joinable()) { server_thread_.join(); }
  25474. }
  25475. std::string url() const {
  25476. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25477. }
  25478. std::unique_ptr<SSLServer> server_;
  25479. std::thread server_thread_;
  25480. int port_ = 0;
  25481. };
  25482. // A custom CA loaded as PEM verifies the server with full certificate
  25483. // verification enabled
  25484. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25485. ws::WebSocketClient client(url());
  25486. std::string cert;
  25487. read_file(SERVER_CERT2_FILE, cert);
  25488. client.load_ca_cert_store(cert.c_str(), cert.size());
  25489. ASSERT_TRUE(client.connect());
  25490. ASSERT_TRUE(client.send("hello"));
  25491. std::string msg;
  25492. EXPECT_EQ(ws::Text, client.read(msg));
  25493. EXPECT_EQ("hello", msg);
  25494. client.close();
  25495. }
  25496. // A custom CA that does not cover the server must fail verification (the
  25497. // custom CA is exclusive; system certs are not loaded alongside it)
  25498. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25499. ws::WebSocketClient client(url());
  25500. std::string cert;
  25501. read_file(CLIENT_CA_CERT_FILE, cert);
  25502. client.load_ca_cert_store(cert.c_str(), cert.size());
  25503. auto res = client.connect();
  25504. ASSERT_FALSE(res);
  25505. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25506. EXPECT_EQ(-1, res.status());
  25507. EXPECT_NE(0u, res.ssl_backend_error());
  25508. }
  25509. // The same CA as a file path rather than PEM in memory
  25510. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25511. ws::WebSocketClient client(url());
  25512. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25513. ASSERT_TRUE(client.connect());
  25514. ASSERT_TRUE(client.send("hello"));
  25515. std::string msg;
  25516. EXPECT_EQ(ws::Text, client.read(msg));
  25517. EXPECT_EQ("hello", msg);
  25518. client.close();
  25519. }
  25520. // ...and a CA file that does not cover the server still fails, so it is the
  25521. // path above that decides the outcome
  25522. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25523. ws::WebSocketClient client(url());
  25524. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25525. ASSERT_FALSE(client.connect());
  25526. }
  25527. // Regression test: reconnecting with a native custom CA store used to reuse
  25528. // a store handle the previous TLS context had already freed (use-after-free
  25529. // under the OpenSSL backend). The context now lives as long as the client.
  25530. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25531. ws::WebSocketClient client(url());
  25532. std::string cert;
  25533. read_file(SERVER_CERT2_FILE, cert);
  25534. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25535. ASSERT_TRUE(client.connect());
  25536. client.close();
  25537. ASSERT_TRUE(client.connect());
  25538. ASSERT_TRUE(client.send("again"));
  25539. std::string msg;
  25540. EXPECT_EQ(ws::Text, client.read(msg));
  25541. EXPECT_EQ("again", msg);
  25542. client.close();
  25543. }
  25544. // Regression test: a certificate with a trusted chain but no identity match
  25545. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25546. // verification entirely for IP hosts, so this connection succeeded there.
  25547. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25548. // chain verification while the identity check must still fail.
  25549. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25550. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25551. ASSERT_TRUE(svr.is_valid());
  25552. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25553. std::string msg;
  25554. while (ws.read(msg)) {
  25555. ws.send(msg);
  25556. }
  25557. });
  25558. auto port = svr.bind_to_any_port("127.0.0.1");
  25559. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25560. auto se = detail::scope_exit([&] {
  25561. svr.stop();
  25562. t.join();
  25563. });
  25564. svr.wait_until_ready();
  25565. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25566. "/echo");
  25567. std::string cert;
  25568. read_file(SERVER_CERT_FILE, cert);
  25569. client.load_ca_cert_store(cert.c_str(), cert.size());
  25570. ASSERT_FALSE(client.connect());
  25571. }
  25572. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25573. // SNI, so nothing binds the host name to the TLS session. These bind the
  25574. // server to "localhost" instead, the only shape that exercises the SNI and
  25575. // hostname-verification path with certificate verification left enabled.
  25576. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25577. protected:
  25578. void Start(const char *cert_file) {
  25579. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25580. SERVER_PRIVATE_KEY_FILE);
  25581. ASSERT_TRUE(server_->is_valid());
  25582. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25583. std::string msg;
  25584. while (ws.read(msg)) {
  25585. ws.send(msg);
  25586. }
  25587. });
  25588. port_ = server_->bind_to_any_port("localhost");
  25589. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25590. server_->wait_until_ready();
  25591. }
  25592. void TearDown() override {
  25593. if (server_) { server_->stop(); }
  25594. if (server_thread_.joinable()) { server_thread_.join(); }
  25595. }
  25596. std::string url() const {
  25597. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25598. }
  25599. std::unique_ptr<SSLServer> server_;
  25600. std::thread server_thread_;
  25601. int port_ = 0;
  25602. };
  25603. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25604. // out and the connection is usable
  25605. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25606. Start(SERVER_CERT2_FILE);
  25607. ws::WebSocketClient client(url());
  25608. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25609. ASSERT_TRUE(client.connect());
  25610. ASSERT_TRUE(client.send("hello"));
  25611. std::string msg;
  25612. EXPECT_EQ(ws::Text, client.read(msg));
  25613. EXPECT_EQ("hello", msg);
  25614. client.close();
  25615. }
  25616. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25617. // while the identity check must still reject "localhost"
  25618. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25619. Start(SERVER_CERT_FILE);
  25620. ws::WebSocketClient client(url());
  25621. client.set_ca_cert_path(SERVER_CERT_FILE);
  25622. auto res = client.connect();
  25623. ASSERT_FALSE(res);
  25624. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25625. EXPECT_EQ(-1, res.status());
  25626. }
  25627. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25628. // disabled: the chain is still checked, only the identity check is skipped
  25629. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25630. Start(SERVER_CERT_FILE);
  25631. ws::WebSocketClient client(url());
  25632. client.set_ca_cert_path(SERVER_CERT_FILE);
  25633. client.enable_server_hostname_verification(false);
  25634. ASSERT_TRUE(client.connect());
  25635. ASSERT_TRUE(client.send("hello"));
  25636. std::string msg;
  25637. EXPECT_EQ(ws::Text, client.read(msg));
  25638. EXPECT_EQ("hello", msg);
  25639. client.close();
  25640. }
  25641. // A CA that did not sign the server certificate fails the chain, even though
  25642. // the name would match
  25643. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25644. Start(SERVER_CERT2_FILE);
  25645. ws::WebSocketClient client(url());
  25646. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25647. ASSERT_FALSE(client.connect());
  25648. }
  25649. // With verification disabled, neither the chain nor the name is checked
  25650. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25651. Start(SERVER_CERT_FILE);
  25652. ws::WebSocketClient client(url());
  25653. client.enable_server_certificate_verification(false);
  25654. ASSERT_TRUE(client.connect());
  25655. ASSERT_TRUE(client.send("hello"));
  25656. std::string msg;
  25657. EXPECT_EQ(ws::Text, client.read(msg));
  25658. EXPECT_EQ("hello", msg);
  25659. client.close();
  25660. }
  25661. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25662. protected:
  25663. void SetUp() override {
  25664. server_ = httplib::detail::make_unique<SSLServer>(
  25665. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25666. ASSERT_TRUE(server_->is_valid());
  25667. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25668. std::string msg;
  25669. while (ws.read(msg)) {
  25670. ws.send(msg);
  25671. }
  25672. });
  25673. port_ = server_->bind_to_any_port("localhost");
  25674. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25675. server_->wait_until_ready();
  25676. }
  25677. void TearDown() override {
  25678. server_->stop();
  25679. if (server_thread_.joinable()) { server_thread_.join(); }
  25680. }
  25681. std::string url() const {
  25682. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25683. }
  25684. void ConnectWithClientCert(const std::string &client_cert_file,
  25685. const std::string &client_private_key_file,
  25686. const char *private_key_password) {
  25687. std::string cert_pem, key_pem;
  25688. read_file(client_cert_file, cert_pem);
  25689. read_file(client_private_key_file, key_pem);
  25690. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25691. key_pem.c_str(), key_pem.size(),
  25692. private_key_password};
  25693. ConnectWithPem(pem);
  25694. }
  25695. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25696. ws::WebSocketClient client(url(), pem);
  25697. ASSERT_TRUE(client.is_valid());
  25698. client.enable_server_certificate_verification(false);
  25699. ASSERT_TRUE(client.connect());
  25700. ASSERT_TRUE(client.send("hello"));
  25701. std::string msg;
  25702. EXPECT_EQ(ws::Text, client.read(msg));
  25703. EXPECT_EQ("hello", msg);
  25704. client.close();
  25705. }
  25706. std::unique_ptr<SSLServer> server_;
  25707. std::thread server_thread_;
  25708. int port_ = 0;
  25709. };
  25710. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25711. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25712. }
  25713. // Control for the tests above: the fixture's server really does require a
  25714. // client certificate, so it is the PEM the constructor installed that decides
  25715. // the outcome.
  25716. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25717. ws::WebSocketClient client(url());
  25718. ASSERT_TRUE(client.is_valid());
  25719. client.enable_server_certificate_verification(false);
  25720. EXPECT_FALSE(client.connect());
  25721. }
  25722. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25723. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25724. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25725. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25726. }
  25727. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25728. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25729. std::string cert_pem, key_pem;
  25730. read_file(CLIENT_CERT_FILE, cert_pem);
  25731. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25732. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25733. std::vector<char> key(key_pem.begin(), key_pem.end());
  25734. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25735. key.size(), nullptr};
  25736. ConnectWithPem(pem);
  25737. }
  25738. #endif
  25739. #if !defined(_WIN32)
  25740. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25741. auto secret_dir = std::string("./symlink_test_secret");
  25742. auto served_dir = std::string("./symlink_test_served");
  25743. auto secret_file = secret_dir + "/secret.txt";
  25744. auto symlink_path = served_dir + "/escape";
  25745. // Setup: create directories and files
  25746. mkdir(secret_dir.c_str(), 0755);
  25747. mkdir(served_dir.c_str(), 0755);
  25748. {
  25749. std::ofstream ofs(secret_file);
  25750. ofs << "SECRET_DATA";
  25751. }
  25752. // Create symlink using absolute path so it resolves correctly
  25753. #ifdef PATH_MAX
  25754. char abs_secret[PATH_MAX];
  25755. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25756. #else
  25757. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25758. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25759. ASSERT_NE(nullptr, abs_secret);
  25760. #endif
  25761. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25762. auto se = detail::scope_exit([&] {
  25763. unlink(symlink_path.c_str());
  25764. unlink(secret_file.c_str());
  25765. rmdir(served_dir.c_str());
  25766. rmdir(secret_dir.c_str());
  25767. });
  25768. Server svr;
  25769. svr.set_mount_point("/", served_dir);
  25770. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25771. auto se2 = detail::scope_exit([&] {
  25772. svr.stop();
  25773. listen_thread.join();
  25774. });
  25775. svr.wait_until_ready();
  25776. Client cli("localhost", PORT);
  25777. // Symlink pointing outside base dir should be blocked
  25778. auto res = cli.Get("/escape/secret.txt");
  25779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25780. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25781. }
  25782. #endif
  25783. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25784. // "GET /smuggled" request), reads the first response, and only then sends the
  25785. // embedded request as the body. Returns how many times /smuggled ran.
  25786. //
  25787. // The body is sent AFTER receiving the first response (as in the original
  25788. // PoC) so that the stream_line_reader cannot buffer it together with the
  25789. // headers of the first request.
  25790. static int count_smuggled_requests(const std::string &outer_head,
  25791. std::string &first_response) {
  25792. Server svr;
  25793. svr.set_mount_point("/", "./www");
  25794. std::atomic<int> smuggled_count(0);
  25795. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25796. smuggled_count++;
  25797. res.set_content("oops", "text/plain");
  25798. });
  25799. svr.Post("/post", [&](const Request &req, Response &res) {
  25800. res.set_content(req.body, "text/plain");
  25801. });
  25802. auto port = svr.bind_to_any_port("localhost");
  25803. thread t = thread([&] { svr.listen_after_bind(); });
  25804. auto se = detail::scope_exit([&] {
  25805. svr.stop();
  25806. t.join();
  25807. });
  25808. svr.wait_until_ready();
  25809. auto error = Error::Success;
  25810. auto sock = detail::create_client_socket(
  25811. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25812. /*connection_timeout_sec=*/2, 0,
  25813. /*read_timeout_sec=*/2, 0,
  25814. /*write_timeout_sec=*/2, 0, std::string(), error);
  25815. EXPECT_NE(INVALID_SOCKET, sock);
  25816. if (sock == INVALID_SOCKET) { return -1; }
  25817. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25818. // The "smuggled" request will be sent as the body of the outer request
  25819. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25820. "Host: localhost\r\n"
  25821. "Connection: close\r\n"
  25822. "\r\n";
  25823. auto head = outer_head;
  25824. auto len = std::to_string(smuggled.size());
  25825. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25826. pos = head.find("{len}", pos + len.size())) {
  25827. head.replace(pos, 5, len);
  25828. }
  25829. // Step 1: Send only the outer request headers (no body yet)
  25830. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25831. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25832. // Step 2: Read the first response
  25833. char buf[4096];
  25834. for (;;) {
  25835. auto n = recv(sock, buf, sizeof(buf), 0);
  25836. if (n <= 0) break;
  25837. first_response.append(buf, static_cast<size_t>(n));
  25838. // Stop once we have a complete response (headers + body)
  25839. auto hdr_end = first_response.find("\r\n\r\n");
  25840. if (hdr_end != std::string::npos) {
  25841. // Check for Content-Length to know when the body is complete
  25842. auto cl_pos = first_response.find("Content-Length:");
  25843. if (cl_pos != std::string::npos) {
  25844. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25845. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25846. auto cl = std::stoul(
  25847. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25848. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25849. } else {
  25850. break; // No Content-Length, assume headers-only response
  25851. }
  25852. }
  25853. }
  25854. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25855. // vulnerable server the keep-alive loop reads this as a second request. The
  25856. // server may already have closed the connection, so the result is ignored.
  25857. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25858. // Half-close so that a server which drained the body sees EOF and closes,
  25859. // instead of the read below waiting for the read timeout.
  25860. #ifdef _WIN32
  25861. ::shutdown(sock, SD_SEND);
  25862. #else
  25863. ::shutdown(sock, SHUT_WR);
  25864. #endif
  25865. // Step 4: Read until the server closes the connection
  25866. for (;;) {
  25867. auto n = recv(sock, buf, sizeof(buf), 0);
  25868. if (n <= 0) break;
  25869. }
  25870. return smuggled_count.load();
  25871. }
  25872. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25873. // A GET request with Content-Length to a static file handler must have its
  25874. // body drained before the keep-alive connection is reused. Otherwise the
  25875. // unread body bytes are interpreted as the next HTTP request.
  25876. std::string first_response;
  25877. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25878. "Host: localhost\r\n"
  25879. "Content-Length: {len}\r\n"
  25880. "\r\n",
  25881. first_response));
  25882. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25883. }
  25884. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25885. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25886. // be answered with 400 and the connection closed. Treating it as "no body"
  25887. // leaves the body to be parsed as the next request.
  25888. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25889. const char *targets[] = {
  25890. "GET /file", // handler that never reads the body
  25891. "GET /not-found", // no handler matches (404)
  25892. "POST /post", // handler that reads the body
  25893. };
  25894. for (auto target : targets) {
  25895. for (auto value : values) {
  25896. std::string first_response;
  25897. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25898. " HTTP/1.1\r\n"
  25899. "Host: localhost\r\n"
  25900. "Content-Length: " +
  25901. value + "\r\n\r\n",
  25902. first_response))
  25903. << target << " with Content-Length: " << value;
  25904. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25905. << target << " with Content-Length: " << value;
  25906. }
  25907. }
  25908. }
  25909. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25910. // A 400 for an unparseable request line leaves the rest of the message
  25911. // unread, so the connection must be closed rather than reused.
  25912. std::string first_response;
  25913. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25914. "Host: localhost\r\n"
  25915. "Content-Length: {len}\r\n"
  25916. "\r\n",
  25917. first_response));
  25918. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25919. }
  25920. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25921. // Same as above for a header block that fails to parse.
  25922. std::string first_response;
  25923. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25924. "Host: localhost\r\n"
  25925. "Bad Header\r\n"
  25926. "Content-Length: {len}\r\n"
  25927. "\r\n",
  25928. first_response));
  25929. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25930. }
  25931. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25932. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25933. // server must not read another request on that connection, even when the
  25934. // request had no body to drain.
  25935. std::string first_response;
  25936. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25937. "Host: localhost\r\n"
  25938. "\r\n",
  25939. first_response));
  25940. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25941. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25942. }
  25943. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25944. // A content reader that stops early leaves the stream inside the body.
  25945. // Draining the whole Content-Length from there, or reading the body again,
  25946. // reads into the next request, and whatever follows is parsed as a request
  25947. // of its own.
  25948. Server svr;
  25949. std::atomic<int> smuggled_count(0);
  25950. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25951. svr.Post("/upload", [](const Request &req, Response &res,
  25952. const ContentReader &content_reader) {
  25953. // Stop at the last chunk, so the whole body has been read however it
  25954. // arrives.
  25955. auto length = req.get_header_value_u64("Content-Length");
  25956. size_t total = 0;
  25957. auto consumed = content_reader([&](const char *, size_t n) {
  25958. total += n;
  25959. return total < length;
  25960. });
  25961. EXPECT_FALSE(consumed);
  25962. if (req.has_param("retry")) {
  25963. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25964. }
  25965. // Replace the 400 the aborted read set, which would close the connection.
  25966. res.set_redirect("/done");
  25967. });
  25968. auto port = svr.bind_to_any_port(HOST);
  25969. thread t = thread([&] { svr.listen_after_bind(); });
  25970. auto se = detail::scope_exit([&] {
  25971. svr.stop();
  25972. t.join();
  25973. });
  25974. svr.wait_until_ready();
  25975. // A front end sees the second request as a POST whose body is the GET. The
  25976. // first body is as long as the POST's headers, so draining it again reads
  25977. // exactly those and leaves the GET to be parsed next.
  25978. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25979. "Host: localhost\r\n"
  25980. "\r\n";
  25981. std::string second_head = "POST /post HTTP/1.1\r\n"
  25982. "Host: localhost\r\n"
  25983. "Content-Length: " +
  25984. std::to_string(inner.size()) +
  25985. "\r\n"
  25986. "\r\n";
  25987. for (auto target : {"/upload", "/upload?retry"}) {
  25988. smuggled_count = 0;
  25989. std::string request = "POST " + std::string(target) +
  25990. " HTTP/1.1\r\n"
  25991. "Host: localhost\r\n"
  25992. "Content-Length: " +
  25993. std::to_string(second_head.size()) +
  25994. "\r\n"
  25995. "\r\n" +
  25996. std::string(second_head.size(), 'A') + second_head +
  25997. inner;
  25998. std::string response;
  25999. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  26000. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  26001. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  26002. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  26003. EXPECT_EQ(0, smuggled_count.load()) << target;
  26004. }
  26005. }
  26006. // An error response closes the connection anyway, so the body is left unread
  26007. // with a redirect, such as one to a login page.
  26008. static void serve_redirects(Server &svr,
  26009. const std::function<void(int)> &client) {
  26010. svr.set_pre_routing_handler([](const Request &, Response &res) {
  26011. res.set_redirect("/login");
  26012. return Server::HandlerResponse::Handled;
  26013. });
  26014. auto port = svr.bind_to_any_port(HOST);
  26015. ASSERT_GT(port, 0);
  26016. thread t = thread([&] { svr.listen_after_bind(); });
  26017. auto se = detail::scope_exit([&] {
  26018. svr.stop();
  26019. t.join();
  26020. ASSERT_FALSE(svr.is_running());
  26021. });
  26022. svr.wait_until_ready();
  26023. client(port);
  26024. }
  26025. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  26026. Server svr;
  26027. serve_redirects(svr, [](int port) {
  26028. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  26029. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  26030. std::to_string(body.size()) + "\r\n\r\n" + body +
  26031. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  26032. std::string resp;
  26033. ASSERT_TRUE(send_request(1, req, &resp, port));
  26034. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  26035. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  26036. });
  26037. }
  26038. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  26039. Server svr;
  26040. svr.set_read_timeout(0, 200000);
  26041. serve_redirects(svr, [](int port) {
  26042. // A byte every 100 ms keeps each read within the read timeout, but not the
  26043. // body as a whole, so the server closes and the bytes sent after that fail.
  26044. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  26045. "Content-Length: 10\r\n\r\n"};
  26046. parts.resize(11, "x");
  26047. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26048. });
  26049. }
  26050. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26051. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26052. // must be rejected with 400 Bad Request.
  26053. Server svr;
  26054. svr.Post("/test", [&](const Request &, Response &res) {
  26055. res.set_content("ok", "text/plain");
  26056. });
  26057. thread t = thread([&] { svr.listen(HOST, PORT); });
  26058. auto se = detail::scope_exit([&] {
  26059. svr.stop();
  26060. t.join();
  26061. ASSERT_FALSE(svr.is_running());
  26062. });
  26063. svr.wait_until_ready();
  26064. // Exact "chunked"
  26065. {
  26066. auto req = "POST /test HTTP/1.1\r\n"
  26067. "Host: localhost\r\n"
  26068. "Content-Length: 5\r\n"
  26069. "Transfer-Encoding: chunked\r\n"
  26070. "Connection: close\r\n"
  26071. "\r\n"
  26072. "hello";
  26073. std::string response;
  26074. ASSERT_TRUE(send_request(1, req, &response));
  26075. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26076. response.substr(0, response.find("\r\n")));
  26077. }
  26078. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26079. {
  26080. auto req = "POST /test HTTP/1.1\r\n"
  26081. "Host: localhost\r\n"
  26082. "Content-Length: 5\r\n"
  26083. "Transfer-Encoding: gzip, chunked\r\n"
  26084. "Connection: close\r\n"
  26085. "\r\n"
  26086. "hello";
  26087. std::string response;
  26088. ASSERT_TRUE(send_request(1, req, &response));
  26089. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26090. response.substr(0, response.find("\r\n")));
  26091. }
  26092. }
  26093. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26094. Server svr;
  26095. svr.Post("/test", [&](const Request &, Response &res) {
  26096. res.set_content("ok", "text/plain");
  26097. });
  26098. thread t = thread([&] { svr.listen(HOST, PORT); });
  26099. auto se = detail::scope_exit([&] {
  26100. svr.stop();
  26101. t.join();
  26102. ASSERT_FALSE(svr.is_running());
  26103. });
  26104. svr.wait_until_ready();
  26105. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26106. // length cannot be determined, so the server must answer 400 and close
  26107. // rather than treat the request as bodyless and leave the body in the
  26108. // socket for the next request to pick up.
  26109. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26110. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26111. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26112. std::string response;
  26113. ASSERT_TRUE(send_request(1, req, &response));
  26114. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26115. response.substr(0, response.find("\r\n")))
  26116. << transfer_encoding;
  26117. }
  26118. // RFC 9110 5.3: the codings may also be split across several
  26119. // Transfer-Encoding lines, which combine in the order they were received.
  26120. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26121. // just like the single-line "chunked, gzip" above.
  26122. {
  26123. auto req = "POST /test HTTP/1.1\r\n"
  26124. "Host: localhost\r\n"
  26125. "Transfer-Encoding: chunked\r\n"
  26126. "Transfer-Encoding: gzip\r\n"
  26127. "\r\n"
  26128. "0\r\n\r\n";
  26129. std::string response;
  26130. ASSERT_TRUE(send_request(1, req, &response));
  26131. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26132. response.substr(0, response.find("\r\n")));
  26133. }
  26134. }
  26135. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26136. Server svr;
  26137. svr.Post("/test", [&](const Request &, Response &res) {
  26138. res.set_content("ok", "text/plain");
  26139. });
  26140. auto port = svr.bind_to_any_port(HOST);
  26141. ASSERT_GT(port, 0);
  26142. thread t = thread([&] { svr.listen_after_bind(); });
  26143. auto se = detail::scope_exit([&] {
  26144. svr.stop();
  26145. t.join();
  26146. ASSERT_FALSE(svr.is_running());
  26147. });
  26148. svr.wait_until_ready();
  26149. for (auto transfer_encoding :
  26150. {"Transfer-Encoding: gzip, chunked\r\n",
  26151. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26152. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26153. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26154. transfer_encoding + "\r\n0\r\n\r\n";
  26155. std::string response;
  26156. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26157. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26158. response.substr(0, response.find("\r\n")))
  26159. << transfer_encoding;
  26160. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26161. << transfer_encoding;
  26162. }
  26163. }
  26164. // Regression for issue #2450: a DELETE without Content-Length on a
  26165. // keep-alive connection must not let the post-response drain consume the
  26166. // next request's bytes.
  26167. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26168. Server svr;
  26169. std::atomic<int> delete_count(0);
  26170. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26171. delete_count++;
  26172. res.status = StatusCode::NoContent_204;
  26173. });
  26174. auto port = svr.bind_to_any_port(HOST);
  26175. thread t = thread([&] { svr.listen_after_bind(); });
  26176. auto se = detail::scope_exit([&] {
  26177. svr.stop();
  26178. t.join();
  26179. });
  26180. svr.wait_until_ready();
  26181. auto error = Error::Success;
  26182. auto sock = detail::create_client_socket(
  26183. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26184. /*connection_timeout_sec=*/2, 0,
  26185. /*read_timeout_sec=*/2, 0,
  26186. /*write_timeout_sec=*/2, 0, std::string(), error);
  26187. ASSERT_NE(INVALID_SOCKET, sock);
  26188. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26189. auto send_request_and_read_response = [&](const std::string &req,
  26190. std::string &out) -> bool {
  26191. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26192. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26193. char buf[4096];
  26194. for (;;) {
  26195. auto n = recv(sock, buf, sizeof(buf), 0);
  26196. if (n <= 0) { return !out.empty(); }
  26197. out.append(buf, static_cast<size_t>(n));
  26198. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26199. }
  26200. };
  26201. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26202. "Host: localhost\r\n"
  26203. "\r\n";
  26204. std::string resp1;
  26205. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26206. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26207. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26208. "Host: localhost\r\n"
  26209. "Connection: close\r\n"
  26210. "\r\n";
  26211. std::string resp2;
  26212. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26213. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26214. EXPECT_EQ(2, delete_count.load());
  26215. }
  26216. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26217. Server svr;
  26218. svr.Post("/ingest", [&](const Request &, Response &res,
  26219. const ContentReader &content_reader) {
  26220. auto consumed = content_reader([](const char *, size_t) { return false; });
  26221. EXPECT_FALSE(consumed);
  26222. res.status = StatusCode::Conflict_409;
  26223. res.set_header("Connection", "close");
  26224. });
  26225. auto port = svr.bind_to_any_port(HOST);
  26226. thread t = thread([&] { svr.listen_after_bind(); });
  26227. auto se = detail::scope_exit([&] {
  26228. svr.stop();
  26229. t.join();
  26230. });
  26231. svr.wait_until_ready();
  26232. auto error = Error::Success;
  26233. auto sock = detail::create_client_socket(
  26234. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26235. /*connection_timeout_sec=*/2, 0,
  26236. /*read_timeout_sec=*/1, 0,
  26237. /*write_timeout_sec=*/2, 0, std::string(), error);
  26238. ASSERT_NE(INVALID_SOCKET, sock);
  26239. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26240. std::string request = "POST /ingest HTTP/1.1\r\n"
  26241. "Host: localhost\r\n"
  26242. "Transfer-Encoding: chunked\r\n"
  26243. "\r\n"
  26244. "4\r\n"
  26245. "data\r\n";
  26246. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26247. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26248. std::string response;
  26249. ssize_t received = 0;
  26250. do {
  26251. char buf[4096];
  26252. received = recv(sock, buf, sizeof(buf), 0);
  26253. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26254. } while (received > 0);
  26255. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26256. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26257. EXPECT_EQ(0, received);
  26258. }
  26259. namespace no_proxy_test {
  26260. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26261. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26262. // calling listen().
  26263. class ScopedServer {
  26264. public:
  26265. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26266. ~ScopedServer() {
  26267. svr_.stop();
  26268. if (th_.joinable()) { th_.join(); }
  26269. }
  26270. Server &svr() { return svr_; }
  26271. int port() const { return port_; }
  26272. void listen() {
  26273. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26274. svr_.wait_until_ready();
  26275. }
  26276. private:
  26277. Server svr_;
  26278. std::thread th_;
  26279. int port_ = 0;
  26280. };
  26281. class ProxyAndTargetServers {
  26282. public:
  26283. ProxyAndTargetServers() {
  26284. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26285. proxy_hits_++;
  26286. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26287. res.set_content("via-proxy", "text/plain");
  26288. });
  26289. target_.Get(".*", [this](const Request &req, Response &res) {
  26290. target_hits_++;
  26291. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26292. res.set_content("direct", "text/plain");
  26293. });
  26294. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26295. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26296. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26297. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26298. proxy_mock_.wait_until_ready();
  26299. target_.wait_until_ready();
  26300. }
  26301. ~ProxyAndTargetServers() {
  26302. proxy_mock_.stop();
  26303. target_.stop();
  26304. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26305. if (target_thread_.joinable()) { target_thread_.join(); }
  26306. }
  26307. Server &proxy_mock() { return proxy_mock_; }
  26308. Server &target() { return target_; }
  26309. int proxy_port() const { return proxy_port_; }
  26310. int target_port() const { return target_port_; }
  26311. int proxy_hits() const { return proxy_hits_.load(); }
  26312. int target_hits() const { return target_hits_.load(); }
  26313. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26314. void reset_counters() {
  26315. proxy_hits_ = 0;
  26316. target_hits_ = 0;
  26317. last_had_proxy_authz_ = false;
  26318. }
  26319. private:
  26320. Server proxy_mock_;
  26321. Server target_;
  26322. std::thread proxy_thread_;
  26323. std::thread target_thread_;
  26324. int proxy_port_ = 0;
  26325. int target_port_ = 0;
  26326. std::atomic<int> proxy_hits_{0};
  26327. std::atomic<int> target_hits_{0};
  26328. std::atomic<bool> last_had_proxy_authz_{false};
  26329. };
  26330. inline std::unique_ptr<Client> make_client(const std::string &host,
  26331. ProxyAndTargetServers &s) {
  26332. auto cli = detail::make_unique<Client>(host, s.target_port());
  26333. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  26334. cli->set_proxy("127.0.0.1", s.proxy_port());
  26335. return cli;
  26336. }
  26337. } // namespace no_proxy_test
  26338. using no_proxy_test::make_client;
  26339. using no_proxy_test::ProxyAndTargetServers;
  26340. // A stream request carries the credentials a buffered request does
  26341. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26342. no_proxy_test::ScopedServer origin;
  26343. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26344. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26345. });
  26346. origin.listen();
  26347. Client cli("127.0.0.1", origin.port());
  26348. cli.set_basic_auth("user", "pass");
  26349. auto handle = cli.open_stream("GET", "/x");
  26350. ASSERT_TRUE(handle.is_valid());
  26351. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26352. Client bearer("127.0.0.1", origin.port());
  26353. bearer.set_bearer_token_auth("tok");
  26354. auto handle2 = bearer.open_stream("GET", "/x");
  26355. ASSERT_TRUE(handle2.is_valid());
  26356. EXPECT_EQ("Bearer tok", read_all(handle2));
  26357. }
  26358. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26359. // takes its own credentials, as for a buffered request
  26360. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26361. std::string target, authz, proxy_authz;
  26362. no_proxy_test::ScopedServer proxy;
  26363. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26364. target = req.target;
  26365. authz = req.get_header_value("Authorization");
  26366. proxy_authz = req.get_header_value("Proxy-Authorization");
  26367. res.set_content("ok", "text/plain");
  26368. });
  26369. proxy.listen();
  26370. Client cli("origin.example", 8080);
  26371. cli.set_proxy("127.0.0.1", proxy.port());
  26372. cli.set_proxy_basic_auth("puser", "ppass");
  26373. cli.set_basic_auth("user", "pass");
  26374. auto handle = cli.open_stream("GET", "/x");
  26375. ASSERT_TRUE(handle.is_valid());
  26376. EXPECT_EQ("ok", read_all(handle));
  26377. EXPECT_EQ("http://origin.example:8080/x", target);
  26378. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26379. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26380. }
  26381. // In absolute-form the path follows the authority, so a path that does not
  26382. // begin with '/' would make the proxy connect to another host
  26383. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26384. std::vector<std::string> targets;
  26385. no_proxy_test::ScopedServer proxy;
  26386. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26387. targets.push_back(req.target);
  26388. res.set_content("ok", "text/plain");
  26389. });
  26390. proxy.listen();
  26391. Client cli("origin.example", 8080);
  26392. cli.set_proxy("127.0.0.1", proxy.port());
  26393. cli.set_basic_auth("user", "pass");
  26394. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26395. auto res = cli.Get(path);
  26396. EXPECT_FALSE(res) << path;
  26397. auto handle = cli.open_stream("GET", path);
  26398. EXPECT_FALSE(handle.is_valid()) << path;
  26399. }
  26400. EXPECT_TRUE(targets.empty());
  26401. auto res = cli.Get("/x");
  26402. ASSERT_TRUE(res);
  26403. ASSERT_EQ(1u, targets.size());
  26404. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26405. }
  26406. TEST(NoProxyTest, ExactHostnameBypasses) {
  26407. ProxyAndTargetServers s;
  26408. auto cli = make_client("example.com", s);
  26409. cli->set_no_proxy({"example.com"});
  26410. auto res = cli->Get("/");
  26411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26412. EXPECT_EQ(0, s.proxy_hits());
  26413. EXPECT_EQ(1, s.target_hits());
  26414. }
  26415. TEST(NoProxyTest, SubdomainBypasses) {
  26416. ProxyAndTargetServers s;
  26417. auto cli = make_client("foo.example.com", s);
  26418. cli->set_no_proxy({"example.com"});
  26419. auto res = cli->Get("/");
  26420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26421. EXPECT_EQ(0, s.proxy_hits());
  26422. EXPECT_EQ(1, s.target_hits());
  26423. }
  26424. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26425. // Regression guard: "evilexample.com" must not be considered a subdomain
  26426. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26427. // check would let traffic bypass the proxy and leak credentials direct
  26428. // to the attacker host.
  26429. ProxyAndTargetServers s;
  26430. auto cli = make_client("evilexample.com", s);
  26431. cli->set_no_proxy({"example.com"});
  26432. auto res = cli->Get("/");
  26433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26434. EXPECT_GE(s.proxy_hits(), 1);
  26435. EXPECT_EQ(0, s.target_hits());
  26436. }
  26437. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26438. ProxyAndTargetServers s;
  26439. auto cli = make_client("example.com.evil.com", s);
  26440. cli->set_no_proxy({"example.com"});
  26441. auto res = cli->Get("/");
  26442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26443. EXPECT_GE(s.proxy_hits(), 1);
  26444. EXPECT_EQ(0, s.target_hits());
  26445. }
  26446. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26447. ProxyAndTargetServers s;
  26448. auto cli = make_client("example.com", s);
  26449. cli->set_no_proxy({".example.com"});
  26450. auto res = cli->Get("/");
  26451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26452. EXPECT_EQ(0, s.proxy_hits());
  26453. EXPECT_EQ(1, s.target_hits());
  26454. }
  26455. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26456. ProxyAndTargetServers s;
  26457. auto cli = make_client("Example.COM", s);
  26458. cli->set_no_proxy({"EXAMPLE.com"});
  26459. auto res = cli->Get("/");
  26460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26461. EXPECT_EQ(0, s.proxy_hits());
  26462. EXPECT_EQ(1, s.target_hits());
  26463. }
  26464. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26465. ProxyAndTargetServers s;
  26466. auto cli = make_client("example.com.", s);
  26467. cli->set_no_proxy({"example.com"});
  26468. auto res = cli->Get("/");
  26469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26470. EXPECT_EQ(0, s.proxy_hits());
  26471. EXPECT_EQ(1, s.target_hits());
  26472. }
  26473. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26474. // Trailing dots must be normalized on BOTH sides — host and entry.
  26475. // An implementation that only strips the host-side trailing dot would
  26476. // fail to match host "example.com" against entry "example.com." because
  26477. // a literal substring search would compare 11 chars against 12.
  26478. ProxyAndTargetServers s;
  26479. auto cli = make_client("example.com", s);
  26480. cli->set_no_proxy({"example.com."});
  26481. auto res = cli->Get("/");
  26482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26483. EXPECT_EQ(0, s.proxy_hits());
  26484. EXPECT_EQ(1, s.target_hits());
  26485. }
  26486. TEST(NoProxyTest, WildcardBypassesEverything) {
  26487. ProxyAndTargetServers s;
  26488. auto cli = make_client("anything.invalid.test", s);
  26489. cli->set_no_proxy({"*"});
  26490. auto res = cli->Get("/");
  26491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26492. EXPECT_EQ(0, s.proxy_hits());
  26493. EXPECT_EQ(1, s.target_hits());
  26494. }
  26495. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26496. ProxyAndTargetServers s;
  26497. Client cli("127.0.0.1", s.target_port());
  26498. cli.set_proxy("127.0.0.1", s.proxy_port());
  26499. cli.set_no_proxy({"127.0.0.1"});
  26500. auto res = cli.Get("/");
  26501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26502. EXPECT_EQ(0, s.proxy_hits());
  26503. EXPECT_EQ(1, s.target_hits());
  26504. }
  26505. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26506. ProxyAndTargetServers s;
  26507. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26508. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26509. cli.set_proxy("127.0.0.1", s.proxy_port());
  26510. cli.set_no_proxy({"::1"});
  26511. auto res = cli.Get("/");
  26512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26513. EXPECT_EQ(0, s.proxy_hits());
  26514. EXPECT_EQ(1, s.target_hits());
  26515. }
  26516. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26517. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26518. // must still be recognized as IPv6 for CIDR matching. Implementations
  26519. // that detect IPv6 only when the host begins with '[' would parse the
  26520. // host as a hostname and miss the match.
  26521. ProxyAndTargetServers s;
  26522. Client cli("fe80::1", s.target_port());
  26523. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26524. cli.set_proxy("127.0.0.1", s.proxy_port());
  26525. cli.set_no_proxy({"fe80::/10"});
  26526. auto res = cli.Get("/");
  26527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26528. EXPECT_EQ(0, s.proxy_hits());
  26529. EXPECT_EQ(1, s.target_hits());
  26530. }
  26531. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26532. ProxyAndTargetServers s;
  26533. Client cli("::1", s.target_port());
  26534. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  26535. cli.set_proxy("127.0.0.1", s.proxy_port());
  26536. cli.set_no_proxy({"[::1]"});
  26537. auto res = cli.Get("/");
  26538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26539. EXPECT_EQ(0, s.proxy_hits());
  26540. EXPECT_EQ(1, s.target_hits());
  26541. }
  26542. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26543. ProxyAndTargetServers s;
  26544. Client cli("fe80::1", s.target_port());
  26545. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26546. cli.set_proxy("127.0.0.1", s.proxy_port());
  26547. cli.set_no_proxy({"[fe80::]/10"});
  26548. auto res = cli.Get("/");
  26549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26550. EXPECT_EQ(0, s.proxy_hits());
  26551. EXPECT_EQ(1, s.target_hits());
  26552. }
  26553. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26554. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26555. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26556. // tricks via address-family conversion.
  26557. ProxyAndTargetServers s;
  26558. Client cli("::ffff:127.0.0.1", s.target_port());
  26559. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26560. cli.set_proxy("127.0.0.1", s.proxy_port());
  26561. cli.set_no_proxy({"127.0.0.1"});
  26562. auto res = cli.Get("/");
  26563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26564. EXPECT_GE(s.proxy_hits(), 1);
  26565. EXPECT_EQ(0, s.target_hits());
  26566. }
  26567. TEST(NoProxyTest, IPv4CidrMatch) {
  26568. ProxyAndTargetServers s;
  26569. Client cli("127.0.0.1", s.target_port());
  26570. cli.set_proxy("127.0.0.1", s.proxy_port());
  26571. cli.set_no_proxy({"127.0.0.0/8"});
  26572. auto res = cli.Get("/");
  26573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26574. EXPECT_EQ(0, s.proxy_hits());
  26575. EXPECT_EQ(1, s.target_hits());
  26576. }
  26577. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26578. ProxyAndTargetServers s;
  26579. Client cli("127.0.0.1", s.target_port());
  26580. cli.set_proxy("127.0.0.1", s.proxy_port());
  26581. cli.set_no_proxy({"10.0.0.0/8"});
  26582. auto res = cli.Get("/");
  26583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26584. EXPECT_GE(s.proxy_hits(), 1);
  26585. EXPECT_EQ(0, s.target_hits());
  26586. }
  26587. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26588. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26589. // IPv4 target matches.
  26590. ProxyAndTargetServers s;
  26591. Client cli("127.0.0.1", s.target_port());
  26592. cli.set_proxy("127.0.0.1", s.proxy_port());
  26593. cli.set_no_proxy({"0.0.0.0/0"});
  26594. auto res = cli.Get("/");
  26595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26596. EXPECT_EQ(0, s.proxy_hits());
  26597. EXPECT_EQ(1, s.target_hits());
  26598. }
  26599. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26600. ProxyAndTargetServers s;
  26601. Client cli("127.0.0.1", s.target_port());
  26602. cli.set_proxy("127.0.0.1", s.proxy_port());
  26603. cli.set_no_proxy({"127.0.0.1"});
  26604. auto res = cli.Get("/");
  26605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26606. EXPECT_EQ(0, s.proxy_hits());
  26607. EXPECT_EQ(1, s.target_hits());
  26608. }
  26609. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26610. ProxyAndTargetServers s;
  26611. Client cli("127.0.0.1", s.target_port());
  26612. cli.set_proxy("127.0.0.1", s.proxy_port());
  26613. cli.set_no_proxy({"127.0.0.0/33"});
  26614. auto res = cli.Get("/");
  26615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26616. EXPECT_GE(s.proxy_hits(), 1);
  26617. EXPECT_EQ(0, s.target_hits());
  26618. }
  26619. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26620. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26621. ProxyAndTargetServers s;
  26622. Client cli("127.0.0.1", s.target_port());
  26623. cli.set_proxy("127.0.0.1", s.proxy_port());
  26624. cli.set_no_proxy({"127.0.0.1/"});
  26625. auto res = cli.Get("/");
  26626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26627. EXPECT_GE(s.proxy_hits(), 1);
  26628. EXPECT_EQ(0, s.target_hits());
  26629. }
  26630. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26631. ProxyAndTargetServers s;
  26632. auto cli = make_client("internal.corp", s);
  26633. cli->set_proxy_basic_auth("u", "p");
  26634. cli->set_no_proxy({"internal.corp"});
  26635. auto res = cli->Get("/");
  26636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26637. EXPECT_EQ(1, s.target_hits());
  26638. EXPECT_EQ(0, s.proxy_hits());
  26639. EXPECT_FALSE(s.last_had_proxy_authz())
  26640. << "Proxy-Authorization must not be sent direct to the target";
  26641. }
  26642. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26643. ProxyAndTargetServers s;
  26644. auto cli = make_client("public.example", s);
  26645. cli->set_proxy_basic_auth("u", "p");
  26646. cli->set_no_proxy({"internal.corp"}); // does not match
  26647. auto res = cli->Get("/");
  26648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26649. EXPECT_GE(s.proxy_hits(), 1);
  26650. EXPECT_TRUE(s.last_had_proxy_authz());
  26651. }
  26652. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26653. std::atomic<int> hits{0};
  26654. std::atomic<int> hits_with_authz{0};
  26655. no_proxy_test::ScopedServer proxy_mock;
  26656. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26657. hits++;
  26658. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26659. if (req.target.find("/redir") != std::string::npos) {
  26660. res.set_redirect("http://other.example/landed");
  26661. } else {
  26662. res.set_content("via-proxy", "text/plain");
  26663. }
  26664. });
  26665. proxy_mock.listen();
  26666. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26667. hits = 0;
  26668. hits_with_authz = 0;
  26669. Client cli("public.example", 80);
  26670. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26671. cli.set_proxy_basic_auth(c.first, c.second);
  26672. cli.set_follow_location(true);
  26673. // The redirect to another host goes through the proxy as well
  26674. auto res = cli.Get("/redir");
  26675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26676. EXPECT_EQ(2, hits.load());
  26677. EXPECT_EQ(2, hits_with_authz.load());
  26678. }
  26679. }
  26680. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26681. ProxyAndTargetServers s;
  26682. auto cli = make_client("anything.test", s);
  26683. auto res = cli->Get("/");
  26684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26685. EXPECT_GE(s.proxy_hits(), 1);
  26686. EXPECT_EQ(0, s.target_hits());
  26687. }
  26688. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26689. ProxyAndTargetServers s;
  26690. auto cli = make_client("example.com", s);
  26691. cli->set_no_proxy({"example.com:8080"});
  26692. auto res = cli->Get("/");
  26693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26694. EXPECT_GE(s.proxy_hits(), 1);
  26695. EXPECT_EQ(0, s.target_hits());
  26696. }
  26697. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26698. ProxyAndTargetServers s;
  26699. auto cli = make_client("anything.test", s);
  26700. cli->set_no_proxy({"", " ", "\t"});
  26701. auto res = cli->Get("/");
  26702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26703. EXPECT_GE(s.proxy_hits(), 1);
  26704. EXPECT_EQ(0, s.target_hits());
  26705. }
  26706. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26707. // An entry with leading/trailing whitespace must still match — env-style
  26708. // values are commonly pasted with stray spaces and an implementation
  26709. // that feeds the raw token directly to inet_pton would fail to match
  26710. // valid CIDRs because of the spaces.
  26711. ProxyAndTargetServers s;
  26712. Client cli("127.0.0.1", s.target_port());
  26713. cli.set_proxy("127.0.0.1", s.proxy_port());
  26714. cli.set_no_proxy({" 127.0.0.0/8 "});
  26715. auto res = cli.Get("/");
  26716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26717. EXPECT_EQ(0, s.proxy_hits());
  26718. EXPECT_EQ(1, s.target_hits());
  26719. }
  26720. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26721. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26722. // go direct and must NOT carry Proxy-Authorization.
  26723. std::atomic<int> proxy_hits{0};
  26724. std::atomic<int> target_hits{0};
  26725. std::atomic<bool> target_saw_authz{false};
  26726. no_proxy_test::ScopedServer proxy_mock, target;
  26727. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26728. proxy_hits++;
  26729. res.status = 302;
  26730. res.set_header("Location", "http://127.0.0.1:" +
  26731. std::to_string(target.port()) + "/landed");
  26732. });
  26733. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26734. target_hits++;
  26735. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26736. res.set_content("direct", "text/plain");
  26737. });
  26738. proxy_mock.listen();
  26739. target.listen();
  26740. Client cli("public.example", target.port());
  26741. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26742. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26743. cli.set_proxy_basic_auth("u", "p");
  26744. cli.set_no_proxy({"127.0.0.1"});
  26745. cli.set_follow_location(true);
  26746. auto res = cli.Get("/redir");
  26747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26748. EXPECT_GE(proxy_hits.load(), 1);
  26749. EXPECT_GE(target_hits.load(), 1);
  26750. EXPECT_FALSE(target_saw_authz.load());
  26751. }
  26752. #ifdef CPPHTTPLIB_SSL_ENABLED
  26753. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26754. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26755. // proxy creds would be sent to the (possibly hostile) origin.
  26756. std::atomic<int> target_hits{0};
  26757. std::atomic<bool> target_saw_proxy_authz{false};
  26758. no_proxy_test::ScopedServer target;
  26759. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26760. target_hits++;
  26761. if (req.has_header("Proxy-Authorization")) {
  26762. target_saw_proxy_authz = true;
  26763. }
  26764. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26765. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26766. "nonce=\"abc\", algorithm=MD5");
  26767. });
  26768. target.listen();
  26769. // The proxy address is set to the target's port: the bypass MUST kick in;
  26770. // if it doesn't, the test still routes "via proxy" to the same server and
  26771. // the Proxy-Authorization assertion below catches the leak.
  26772. Client cli("evil.example", target.port());
  26773. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26774. cli.set_proxy("127.0.0.1", target.port());
  26775. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26776. cli.set_no_proxy({"evil.example"});
  26777. auto res = cli.Get("/x");
  26778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26779. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26780. EXPECT_EQ(1, target_hits.load());
  26781. EXPECT_FALSE(target_saw_proxy_authz.load());
  26782. }
  26783. #endif
  26784. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26785. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26786. std::atomic<int> proxy_hits{0};
  26787. std::atomic<int> bypass_hits{0};
  26788. std::atomic<bool> proxy_saw_c_url{false};
  26789. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26790. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26791. proxy_hits++;
  26792. if (req.path.find("/start") != std::string::npos) {
  26793. res.status = 302;
  26794. res.set_header("Location", "http://127.0.0.1:" +
  26795. std::to_string(bypass_server.port()) +
  26796. "/middle");
  26797. return;
  26798. }
  26799. if (req.path.find("/end") != std::string::npos) {
  26800. proxy_saw_c_url = true;
  26801. res.set_content("c-via-proxy", "text/plain");
  26802. return;
  26803. }
  26804. res.set_content("unexpected", "text/plain");
  26805. });
  26806. // public.example's "advertised" port is arbitrary (the request never lands
  26807. // there — it goes through the proxy), but use a dynamic value to stay
  26808. // friendly with sharded parallel runs.
  26809. int public_port = bypass_server.port();
  26810. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26811. bypass_hits++;
  26812. res.status = 302;
  26813. res.set_header("Location", "http://public.example:" +
  26814. std::to_string(public_port) + "/end");
  26815. });
  26816. proxy_mock.listen();
  26817. bypass_server.listen();
  26818. Client cli("public.example", public_port);
  26819. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26820. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26821. cli.set_no_proxy({"127.0.0.1"});
  26822. cli.set_follow_location(true);
  26823. auto res = cli.Get("/start");
  26824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26825. EXPECT_EQ(StatusCode::OK_200, res->status);
  26826. EXPECT_EQ("c-via-proxy", res->body);
  26827. EXPECT_GE(proxy_hits.load(), 2);
  26828. EXPECT_GE(bypass_hits.load(), 1);
  26829. EXPECT_TRUE(proxy_saw_c_url.load());
  26830. }
  26831. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26832. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26833. // request reconnects to the correct endpoint.
  26834. std::atomic<int> proxy_hits{0};
  26835. std::atomic<int> target_hits{0};
  26836. no_proxy_test::ScopedServer proxy_mock, target;
  26837. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26838. proxy_hits++;
  26839. res.set_content("via-proxy", "text/plain");
  26840. });
  26841. target.svr().Get(".*", [&](const Request &, Response &res) {
  26842. target_hits++;
  26843. res.set_content("direct", "text/plain");
  26844. });
  26845. proxy_mock.listen();
  26846. target.listen();
  26847. Client cli("public.example", target.port());
  26848. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26849. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26850. cli.set_keep_alive(true);
  26851. auto res1 = cli.Get("/a");
  26852. ASSERT_TRUE(res1);
  26853. EXPECT_EQ("via-proxy", res1->body);
  26854. EXPECT_EQ(1, proxy_hits.load());
  26855. EXPECT_EQ(0, target_hits.load());
  26856. cli.set_no_proxy({"public.example"});
  26857. auto res2 = cli.Get("/b");
  26858. ASSERT_TRUE(res2);
  26859. EXPECT_EQ("direct", res2->body);
  26860. EXPECT_EQ(1, proxy_hits.load());
  26861. EXPECT_EQ(1, target_hits.load());
  26862. }
  26863. // Forward declarations (see the base64_encode note).
  26864. namespace httplib {
  26865. namespace detail {
  26866. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26867. int shutdown_socket(socket_t sock) noexcept;
  26868. } // namespace detail
  26869. } // namespace httplib
  26870. namespace proxy_tunnel_test {
  26871. const char *const kTunnelEstablished =
  26872. "HTTP/1.1 200 Connection established\r\n\r\n";
  26873. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26874. using ConnectReply = std::function<std::string(const std::string &head)>;
  26875. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26876. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26877. class ScopedConnectProxy {
  26878. public:
  26879. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26880. : forward_port_(forward_port), reply_(std::move(reply)) {
  26881. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26882. if (listen_sock_ == INVALID_SOCKET) { return; }
  26883. auto a = loopback(0);
  26884. auto addr = reinterpret_cast<sockaddr *>(&a);
  26885. socklen_t alen = sizeof(a);
  26886. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26887. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26888. ::listen(listen_sock_, 4) != 0) {
  26889. return;
  26890. }
  26891. port_ = ntohs(a.sin_port);
  26892. th_ = std::thread([this] { run(); });
  26893. }
  26894. ~ScopedConnectProxy() {
  26895. if (th_.joinable()) {
  26896. stop_ = true;
  26897. auto wake = connect_to(port_);
  26898. th_.join();
  26899. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26900. }
  26901. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26902. }
  26903. int port() const { return port_; }
  26904. int connect_hits() const { return connect_hits_.load(); }
  26905. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26906. std::string connect_request() const {
  26907. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26908. return connect_request_;
  26909. }
  26910. private:
  26911. static sockaddr_in loopback(int port) {
  26912. sockaddr_in a{};
  26913. a.sin_family = AF_INET;
  26914. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26915. a.sin_port = htons(static_cast<unsigned short>(port));
  26916. return a;
  26917. }
  26918. static socket_t connect_to(int port) {
  26919. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26920. if (sock == INVALID_SOCKET) { return sock; }
  26921. auto a = loopback(port);
  26922. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26923. detail::close_socket(sock);
  26924. return INVALID_SOCKET;
  26925. }
  26926. return sock;
  26927. }
  26928. static bool send_all(socket_t sock, const char *data, size_t size) {
  26929. while (size > 0) {
  26930. auto n = detail::send_socket(sock, data, size, 0);
  26931. if (n <= 0) { return false; }
  26932. data += n;
  26933. size -= static_cast<size_t>(n);
  26934. }
  26935. return true;
  26936. }
  26937. void run() {
  26938. for (;;) {
  26939. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26940. if (stop_) {
  26941. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26942. return;
  26943. }
  26944. if (client == INVALID_SOCKET) { continue; }
  26945. serve(client);
  26946. detail::close_socket(client);
  26947. }
  26948. }
  26949. void serve(socket_t client) {
  26950. std::string head;
  26951. char buf[2048];
  26952. while (head.find("\r\n\r\n") == std::string::npos) {
  26953. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26954. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26955. if (n <= 0) { return; }
  26956. head.append(buf, static_cast<size_t>(n));
  26957. }
  26958. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26959. connect_hits_++;
  26960. {
  26961. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26962. connect_request_ = head;
  26963. }
  26964. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26965. if (!send_all(client, res.data(), res.size()) ||
  26966. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26967. return;
  26968. }
  26969. auto origin = connect_to(forward_port_);
  26970. if (origin == INVALID_SOCKET) { return; }
  26971. // When either side stops, shut both down so the other pump returns too.
  26972. auto pump = [&](socket_t from, socket_t to) {
  26973. char b[8192];
  26974. for (;;) {
  26975. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26976. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26977. }
  26978. detail::shutdown_socket(client);
  26979. detail::shutdown_socket(origin);
  26980. };
  26981. std::thread up([&] { pump(client, origin); });
  26982. pump(origin, client);
  26983. up.join();
  26984. detail::close_socket(origin);
  26985. }
  26986. int forward_port_;
  26987. ConnectReply reply_;
  26988. socket_t listen_sock_ = INVALID_SOCKET;
  26989. int port_ = 0;
  26990. std::thread th_;
  26991. std::atomic<bool> stop_{false};
  26992. std::atomic<int> connect_hits_{0};
  26993. mutable std::mutex connect_request_mutex_;
  26994. std::string connect_request_;
  26995. };
  26996. } // namespace proxy_tunnel_test
  26997. #ifdef CPPHTTPLIB_SSL_ENABLED
  26998. namespace proxy_tunnel_test {
  26999. // SSLServer counterpart to no_proxy_test::ScopedServer.
  27000. class ScopedSSLServer {
  27001. public:
  27002. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  27003. port_ = svr_.bind_to_any_port("127.0.0.1");
  27004. }
  27005. ~ScopedSSLServer() {
  27006. svr_.stop();
  27007. if (th_.joinable()) { th_.join(); }
  27008. }
  27009. SSLServer &svr() { return svr_; }
  27010. int port() const { return port_; }
  27011. void listen() {
  27012. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27013. svr_.wait_until_ready();
  27014. }
  27015. private:
  27016. SSLServer svr_;
  27017. std::thread th_;
  27018. int port_ = 0;
  27019. };
  27020. // Sends one request through the CONNECT proxy to the TLS origin with a
  27021. // credential configured for each hop, and checks that each credential reaches
  27022. // only the hop it was configured for: the proxy's on the CONNECT request, the
  27023. // origin's (every header in origin_headers) on the tunnelled request.
  27024. void CredentialsStayWithTheirHop(
  27025. const std::function<void(SSLClient &)> &set_credentials,
  27026. const std::string &scheme,
  27027. const std::vector<std::string> &origin_headers = {"Authorization"},
  27028. bool stream = false) {
  27029. std::atomic<int> origin_hits{0};
  27030. std::atomic<bool> origin_saw_proxy_authz{false};
  27031. std::atomic<bool> origin_saw_headers{false};
  27032. ScopedSSLServer origin;
  27033. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27034. origin_hits++;
  27035. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  27036. origin_saw_headers =
  27037. std::all_of(origin_headers.begin(), origin_headers.end(),
  27038. [&](const std::string &h) { return req.has_header(h); });
  27039. res.set_content("ok", "text/plain");
  27040. });
  27041. origin.listen();
  27042. ScopedConnectProxy proxy(origin.port());
  27043. ASSERT_NE(0, proxy.port());
  27044. // Pinned to 127.0.0.1 for the same reason as the test below.
  27045. SSLClient cli("127.0.0.1", origin.port());
  27046. cli.enable_server_certificate_verification(false);
  27047. cli.set_proxy("127.0.0.1", proxy.port());
  27048. set_credentials(cli);
  27049. if (stream) {
  27050. auto handle = cli.open_stream("GET", "/x");
  27051. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27052. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27053. } else {
  27054. auto res = cli.Get("/x");
  27055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27056. EXPECT_EQ(StatusCode::OK_200, res->status);
  27057. }
  27058. EXPECT_EQ(1, origin_hits.load());
  27059. EXPECT_EQ(1, proxy.connect_hits());
  27060. EXPECT_TRUE(origin_saw_headers.load());
  27061. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27062. << "Proxy-Authorization must not be sent inside the tunnel";
  27063. auto connect_req = proxy.connect_request();
  27064. EXPECT_NE(std::string::npos,
  27065. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27066. for (const auto &h : origin_headers) {
  27067. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27068. << h << " must not be sent to the proxy on CONNECT";
  27069. }
  27070. }
  27071. } // namespace proxy_tunnel_test
  27072. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27073. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27074. [](SSLClient &cli) {
  27075. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27076. cli.set_basic_auth("origin-user", "origin-pass");
  27077. },
  27078. "Basic");
  27079. }
  27080. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27081. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27082. [](SSLClient &cli) {
  27083. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27084. cli.set_basic_auth("origin-user", "origin-pass");
  27085. },
  27086. "Basic", {"Authorization"}, true);
  27087. }
  27088. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27089. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27090. [](SSLClient &cli) {
  27091. cli.set_proxy_bearer_token_auth("proxy-token");
  27092. cli.set_bearer_token_auth("origin-token");
  27093. },
  27094. "Bearer");
  27095. }
  27096. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27097. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27098. [](SSLClient &cli) {
  27099. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27100. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27101. {"Cookie", "sid=origin-session"},
  27102. {"X-Api-Key", "origin-key"}});
  27103. },
  27104. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27105. }
  27106. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27107. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27108. // retry; otherwise proxy creds would be sent to the origin.
  27109. std::atomic<int> origin_hits{0};
  27110. std::atomic<bool> origin_saw_proxy_authz{false};
  27111. proxy_tunnel_test::ScopedSSLServer origin;
  27112. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27113. origin_hits++;
  27114. if (req.has_header("Proxy-Authorization")) {
  27115. origin_saw_proxy_authz = true;
  27116. }
  27117. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27118. res.set_header("Proxy-Authenticate",
  27119. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27120. "algorithm=MD5");
  27121. });
  27122. origin.listen();
  27123. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27124. ASSERT_NE(0, proxy.port());
  27125. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27126. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27127. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27128. // and answer with its own status, making this test flaky.
  27129. SSLClient cli("127.0.0.1", origin.port());
  27130. cli.enable_server_certificate_verification(false);
  27131. cli.set_proxy("127.0.0.1", proxy.port());
  27132. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27133. auto res = cli.Get("/x");
  27134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27135. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27136. EXPECT_EQ(1, origin_hits.load());
  27137. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27138. EXPECT_EQ(1, proxy.connect_hits());
  27139. }
  27140. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27141. std::string origin_sni;
  27142. std::string origin_host;
  27143. proxy_tunnel_test::ScopedSSLServer origin;
  27144. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27145. origin_sni = req.sni();
  27146. origin_host = req.get_header_value("Host");
  27147. res.set_content("ok", "text/plain");
  27148. });
  27149. origin.listen();
  27150. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27151. ASSERT_NE(0, proxy.port());
  27152. SSLClient cli("origin.example", origin.port());
  27153. cli.enable_server_certificate_verification(false);
  27154. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27155. cli.set_proxy("127.0.0.1", proxy.port());
  27156. auto res = cli.Get("/x");
  27157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27158. EXPECT_EQ(StatusCode::OK_200, res->status);
  27159. auto port = std::to_string(origin.port());
  27160. auto target = "127.0.0.1:" + port;
  27161. auto connect_req = proxy.connect_request();
  27162. EXPECT_EQ(1, proxy.connect_hits());
  27163. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27164. EXPECT_NE(std::string::npos,
  27165. connect_req.find("\r\nHost: " + target + "\r\n"));
  27166. EXPECT_EQ("origin.example", origin_sni);
  27167. EXPECT_EQ("origin.example:" + port, origin_host);
  27168. }
  27169. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27170. proxy_tunnel_test::ScopedSSLServer origin;
  27171. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27172. res.set_content("ok", "text/plain");
  27173. });
  27174. origin.listen();
  27175. proxy_tunnel_test::ScopedConnectProxy proxy(
  27176. origin.port(), [](const std::string &head) -> std::string {
  27177. if (head.find(
  27178. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27179. std::string::npos) {
  27180. return proxy_tunnel_test::kTunnelEstablished;
  27181. }
  27182. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27183. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27184. "nonce=\"abc\", algorithm=MD5\r\n"
  27185. "Content-Length: 0\r\n\r\n";
  27186. });
  27187. ASSERT_NE(0, proxy.port());
  27188. SSLClient cli("origin.example", origin.port());
  27189. cli.enable_server_certificate_verification(false);
  27190. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27191. cli.set_proxy("127.0.0.1", proxy.port());
  27192. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27193. auto res = cli.Get("/x");
  27194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27195. EXPECT_EQ(StatusCode::OK_200, res->status);
  27196. // The retried CONNECT is the one the proxy saw last.
  27197. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27198. auto connect_req = proxy.connect_request();
  27199. EXPECT_EQ(2, proxy.connect_hits());
  27200. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27201. EXPECT_NE(std::string::npos,
  27202. connect_req.find("\r\nHost: " + target + "\r\n"));
  27203. }
  27204. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27205. proxy_tunnel_test::ScopedSSLServer origin;
  27206. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27207. res.set_content("ok", "text/plain");
  27208. });
  27209. origin.listen();
  27210. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27211. ASSERT_NE(0, proxy.port());
  27212. SSLClient cli("origin.example", origin.port());
  27213. cli.enable_server_certificate_verification(false);
  27214. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27215. cli.set_proxy("127.0.0.1", proxy.port());
  27216. auto res = cli.Get("/x");
  27217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27218. EXPECT_EQ(StatusCode::OK_200, res->status);
  27219. auto target = "origin.example:" + std::to_string(origin.port());
  27220. auto connect_req = proxy.connect_request();
  27221. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27222. EXPECT_NE(std::string::npos,
  27223. connect_req.find("\r\nHost: " + target + "\r\n"));
  27224. }
  27225. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27226. proxy_tunnel_test::ScopedSSLServer origin;
  27227. auto port = std::to_string(origin.port());
  27228. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27229. res.set_redirect("https://next.example:" + port + "/y");
  27230. });
  27231. origin.svr().Get("/y", [](const Request &, Response &res) {
  27232. res.set_content("ok", "text/plain");
  27233. });
  27234. origin.listen();
  27235. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27236. ASSERT_NE(0, proxy.port());
  27237. SSLClient cli("origin.example", origin.port());
  27238. cli.enable_server_certificate_verification(false);
  27239. cli.set_tunnel_hostname_addr_map(
  27240. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27241. cli.set_proxy("127.0.0.1", proxy.port());
  27242. cli.set_follow_location(true);
  27243. auto res = cli.Get("/x");
  27244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27245. EXPECT_EQ("ok", res->body);
  27246. // The last CONNECT is the redirect client's.
  27247. ASSERT_EQ(2, proxy.connect_hits());
  27248. auto target = "127.0.0.1:" + port;
  27249. auto connect_req = proxy.connect_request();
  27250. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27251. EXPECT_NE(std::string::npos,
  27252. connect_req.find("\r\nHost: " + target + "\r\n"));
  27253. }
  27254. #endif
  27255. namespace proxy_tunnel_test {
  27256. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27257. // anything else gets a 407 with `challenge`.
  27258. ConnectReply require_proxy_auth(const std::string &expected,
  27259. const std::string &challenge) {
  27260. return [=](const std::string &head) -> std::string {
  27261. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27262. std::string::npos) {
  27263. return kTunnelEstablished;
  27264. }
  27265. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27266. "Proxy-Authenticate: " +
  27267. challenge + "\r\nContent-Length: 0\r\n\r\n";
  27268. };
  27269. }
  27270. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  27271. // request, then echoes.
  27272. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  27273. ws.send(
  27274. "authorization:" + req.get_header_value("Authorization") +
  27275. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  27276. std::string msg;
  27277. while (ws.read(msg)) {
  27278. ws.send(msg);
  27279. }
  27280. }
  27281. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  27282. class ScopedWebSocketOrigin {
  27283. public:
  27284. ScopedWebSocketOrigin() {
  27285. server_.svr().WebSocket("/ws", report_auth_then_echo);
  27286. server_.listen();
  27287. }
  27288. int port() const { return server_.port(); }
  27289. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  27290. std::string url() const {
  27291. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  27292. }
  27293. private:
  27294. no_proxy_test::ScopedServer server_;
  27295. };
  27296. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  27297. // passed as a constructor header, and checks that each reaches only its hop.
  27298. void WebSocketCredentialsStayWithTheirHop(
  27299. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  27300. const std::string &proxy_authz, const std::string &origin_authz) {
  27301. ScopedWebSocketOrigin origin;
  27302. ScopedConnectProxy proxy(
  27303. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27304. ASSERT_NE(0, proxy.port());
  27305. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  27306. client.set_proxy("127.0.0.1", proxy.port());
  27307. set_proxy_credentials(client);
  27308. auto res = client.connect();
  27309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27310. std::string msg;
  27311. ASSERT_TRUE(client.read(msg));
  27312. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27313. client.close();
  27314. EXPECT_EQ(1, proxy.connect_hits());
  27315. EXPECT_EQ(std::string::npos,
  27316. proxy.connect_request().find("\r\nAuthorization: "))
  27317. << "origin credentials must not be sent to the proxy";
  27318. }
  27319. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  27320. void WebSocketSetterCredentialsStayWithTheirHop(
  27321. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  27322. const std::string &proxy_authz, const std::string &origin_authz) {
  27323. ScopedWebSocketOrigin origin;
  27324. ScopedConnectProxy proxy(
  27325. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  27326. ASSERT_NE(0, proxy.port());
  27327. ws::WebSocketClient client(origin.url());
  27328. client.set_proxy("127.0.0.1", proxy.port());
  27329. set_credentials(client);
  27330. auto res = client.connect();
  27331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27332. std::string msg;
  27333. ASSERT_TRUE(client.read(msg));
  27334. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  27335. client.close();
  27336. EXPECT_EQ(1, proxy.connect_hits());
  27337. EXPECT_EQ(std::string::npos,
  27338. proxy.connect_request().find("\r\nAuthorization: "))
  27339. << "origin credentials must not be sent to the proxy";
  27340. }
  27341. } // namespace proxy_tunnel_test
  27342. namespace {
  27343. // Connects `client` and returns the Authorization header its upgrade
  27344. // request carried, or "<failed>" when the connection could not be opened.
  27345. std::string websocket_authorization(ws::WebSocketClient &client) {
  27346. if (!client.connect()) { return "<failed>"; }
  27347. std::string msg;
  27348. if (!client.read(msg)) { return "<failed>"; }
  27349. client.close();
  27350. auto prefix = std::string("authorization:");
  27351. auto end = msg.find("|proxy-authorization:");
  27352. return msg.substr(prefix.size(), end - prefix.size());
  27353. }
  27354. } // namespace
  27355. TEST(WebSocketClientAuthTest, BasicAuth) {
  27356. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27357. ws::WebSocketClient client(origin.url());
  27358. client.set_basic_auth("user", "pass");
  27359. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27360. websocket_authorization(client));
  27361. }
  27362. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  27363. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27364. ws::WebSocketClient client(origin.url());
  27365. client.set_basic_auth("user", "");
  27366. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  27367. websocket_authorization(client));
  27368. }
  27369. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  27370. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27371. ws::WebSocketClient client(origin.url());
  27372. client.set_bearer_token_auth("token123");
  27373. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  27374. }
  27375. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  27376. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27377. ws::WebSocketClient client(origin.url());
  27378. client.set_bearer_token_auth("token123");
  27379. client.set_basic_auth("user", "pass");
  27380. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  27381. websocket_authorization(client));
  27382. }
  27383. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  27384. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27385. ws::WebSocketClient client(origin.url(),
  27386. {{"Authorization", "Bearer from-header"}});
  27387. client.set_bearer_token_auth("from-setter");
  27388. client.set_basic_auth("user", "pass");
  27389. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  27390. }
  27391. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  27392. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27393. ws::WebSocketClient client(origin.url());
  27394. EXPECT_EQ("", websocket_authorization(client));
  27395. client.set_bearer_token_auth("first");
  27396. EXPECT_EQ("Bearer first", websocket_authorization(client));
  27397. client.set_bearer_token_auth("second");
  27398. EXPECT_EQ("Bearer second", websocket_authorization(client));
  27399. client.set_bearer_token_auth("");
  27400. EXPECT_EQ("", websocket_authorization(client));
  27401. }
  27402. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  27403. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27404. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27405. ASSERT_NE(0, proxy.port());
  27406. ws::WebSocketClient client(origin.url());
  27407. client.set_proxy("127.0.0.1", proxy.port());
  27408. auto res = client.connect();
  27409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27410. std::string msg;
  27411. ASSERT_TRUE(client.read(msg));
  27412. ASSERT_TRUE(client.send("hello"));
  27413. ASSERT_TRUE(client.read(msg));
  27414. EXPECT_EQ("hello", msg);
  27415. client.close();
  27416. EXPECT_EQ(1, proxy.connect_hits());
  27417. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27418. auto connect_req = proxy.connect_request();
  27419. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27420. EXPECT_NE(std::string::npos,
  27421. connect_req.find("\r\nHost: " + target + "\r\n"));
  27422. }
  27423. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  27424. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27425. [](ws::WebSocketClient &cli) {
  27426. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27427. },
  27428. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27429. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27430. }
  27431. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  27432. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  27433. [](ws::WebSocketClient &cli) {
  27434. cli.set_proxy_bearer_token_auth("proxy-token");
  27435. },
  27436. "Bearer proxy-token", "Bearer origin-token");
  27437. }
  27438. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  27439. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27440. [](ws::WebSocketClient &cli) {
  27441. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27442. cli.set_basic_auth("origin-user", "origin-pass");
  27443. },
  27444. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  27445. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  27446. }
  27447. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  27448. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  27449. [](ws::WebSocketClient &cli) {
  27450. cli.set_proxy_bearer_token_auth("proxy-token");
  27451. cli.set_bearer_token_auth("origin-token");
  27452. },
  27453. "Bearer proxy-token", "Bearer origin-token");
  27454. }
  27455. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  27456. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27457. proxy_tunnel_test::ScopedConnectProxy proxy(
  27458. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27459. "Basic " + detail::base64_encode("proxy-user:"),
  27460. "Basic realm=\"proxy\""));
  27461. ASSERT_NE(0, proxy.port());
  27462. ws::WebSocketClient client(origin.url());
  27463. client.set_proxy("127.0.0.1", proxy.port());
  27464. client.set_proxy_basic_auth("proxy-user", "");
  27465. auto res = client.connect();
  27466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27467. client.close();
  27468. EXPECT_EQ(1, proxy.connect_hits());
  27469. }
  27470. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  27471. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27472. proxy_tunnel_test::ScopedConnectProxy proxy(
  27473. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27474. "Bearer proxy-token", "Basic realm=\"proxy\""));
  27475. ASSERT_NE(0, proxy.port());
  27476. ws::WebSocketClient client(origin.url());
  27477. client.set_proxy("127.0.0.1", proxy.port());
  27478. auto res = client.connect();
  27479. EXPECT_FALSE(res);
  27480. EXPECT_EQ(Error::ProxyConnection, res.error());
  27481. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  27482. EXPECT_EQ("Basic realm=\"proxy\"",
  27483. res.get_header_value("Proxy-Authenticate"));
  27484. EXPECT_FALSE(client.is_open());
  27485. }
  27486. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  27487. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27488. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27489. ASSERT_NE(0, proxy.port());
  27490. ws::WebSocketClient client(origin.url());
  27491. client.set_proxy("127.0.0.1", proxy.port());
  27492. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27493. client.set_no_proxy({"127.0.0.1"});
  27494. auto res = client.connect();
  27495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27496. std::string msg;
  27497. ASSERT_TRUE(client.read(msg));
  27498. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27499. << "proxy credentials must not reach a bypassed origin";
  27500. client.close();
  27501. EXPECT_EQ(0, proxy.connect_hits());
  27502. }
  27503. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27504. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27505. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27506. ASSERT_NE(0, proxy.port());
  27507. ws::WebSocketClient client(origin.url());
  27508. client.set_proxy("127.0.0.1", proxy.port());
  27509. ASSERT_TRUE(client.connect());
  27510. ASSERT_TRUE(client.connect());
  27511. client.close();
  27512. EXPECT_EQ(2, proxy.connect_hits());
  27513. }
  27514. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27515. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27516. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27517. ASSERT_NE(0, proxy.port());
  27518. auto port = std::to_string(origin.port());
  27519. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27520. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27521. client.set_proxy("127.0.0.1", proxy.port());
  27522. auto res = client.connect();
  27523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27524. std::string msg;
  27525. ASSERT_TRUE(client.read(msg));
  27526. client.close();
  27527. EXPECT_EQ(1, proxy.connect_hits());
  27528. auto target = "127.0.0.1:" + port;
  27529. auto connect_req = proxy.connect_request();
  27530. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27531. EXPECT_NE(std::string::npos,
  27532. connect_req.find("\r\nHost: " + target + "\r\n"));
  27533. }
  27534. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27535. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27536. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27537. ASSERT_NE(0, proxy.port());
  27538. auto port = std::to_string(origin.port());
  27539. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  27540. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27541. client.set_proxy("127.0.0.1", proxy.port());
  27542. auto res = client.connect();
  27543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27544. client.close();
  27545. auto target = "origin.example:" + port;
  27546. auto connect_req = proxy.connect_request();
  27547. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27548. EXPECT_NE(std::string::npos,
  27549. connect_req.find("\r\nHost: " + target + "\r\n"));
  27550. }
  27551. #ifdef CPPHTTPLIB_SSL_ENABLED
  27552. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27553. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27554. proxy_tunnel_test::ScopedConnectProxy proxy(
  27555. origin.port(), [](const std::string &head) -> std::string {
  27556. if (head.find(
  27557. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27558. std::string::npos) {
  27559. return proxy_tunnel_test::kTunnelEstablished;
  27560. }
  27561. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27562. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27563. "nonce=\"abc\", algorithm=MD5\r\n"
  27564. "Content-Length: 0\r\n\r\n";
  27565. });
  27566. ASSERT_NE(0, proxy.port());
  27567. ws::WebSocketClient client(origin.url());
  27568. client.set_proxy("127.0.0.1", proxy.port());
  27569. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27570. auto res = client.connect();
  27571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27572. std::string msg;
  27573. ASSERT_TRUE(client.read(msg));
  27574. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27575. client.close();
  27576. EXPECT_EQ(2, proxy.connect_hits());
  27577. }
  27578. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27579. proxy_tunnel_test::ScopedSSLServer origin;
  27580. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27581. origin.listen();
  27582. proxy_tunnel_test::ScopedConnectProxy proxy(
  27583. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27584. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27585. ASSERT_NE(0, proxy.port());
  27586. ws::WebSocketClient client(
  27587. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27588. client.enable_server_certificate_verification(false);
  27589. client.set_proxy("127.0.0.1", proxy.port());
  27590. client.set_proxy_bearer_token_auth("proxy-token");
  27591. auto res = client.connect();
  27592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27593. std::string msg;
  27594. ASSERT_TRUE(client.read(msg));
  27595. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27596. << "Proxy-Authorization must not be sent inside the tunnel";
  27597. client.close();
  27598. EXPECT_EQ(1, proxy.connect_hits());
  27599. }
  27600. #endif