test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615
  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_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. bool is_valid_path(const std::string &path);
  492. #ifdef CPPHTTPLIB_SSL_ENABLED
  493. bool match_hostname(const std::string &pattern, const std::string &hostname);
  494. #endif
  495. } // namespace detail
  496. } // namespace httplib
  497. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  498. struct {
  499. const char *line;
  500. const char *version;
  501. int status;
  502. const char *reason;
  503. } cases[] = {
  504. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  505. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  506. // The reason phrase may be empty, or left out along with its space.
  507. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  508. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  509. };
  510. for (const auto &c : cases) {
  511. std::string version;
  512. int status = 0;
  513. std::string reason = "unset";
  514. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  515. << c.line;
  516. EXPECT_EQ(c.version, version);
  517. EXPECT_EQ(c.status, status);
  518. EXPECT_EQ(c.reason, reason);
  519. }
  520. }
  521. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  522. const char *lines[] = {
  523. "HTTP/2 200 OK\r\n",
  524. "HTTP/1.2 200 OK\r\n",
  525. "HTTP/1.1 20 OK\r\n",
  526. "HTTP/1.1 2000 OK\r\n",
  527. "HTTP/1.1 2x0 OK\r\n",
  528. "HTTP/1.1 200 OK\r\n",
  529. "HTTP/1.1 200OK\r\n",
  530. "HTTP/1.1 200 O\rK\r\n",
  531. "HTTP/1.1 200 OK",
  532. "HTTP/1.1 200 OK\r\nX",
  533. "",
  534. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  535. "HTTP/1.1 200 OK\n",
  536. #endif
  537. };
  538. for (auto line : lines) {
  539. std::string version;
  540. int status = 0;
  541. std::string reason;
  542. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  543. << line;
  544. }
  545. }
  546. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  547. // Long enough to overflow the stack when matched with std::regex.
  548. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  549. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  550. std::string version;
  551. int status = 0;
  552. std::string reason;
  553. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  554. EXPECT_EQ(200, status);
  555. EXPECT_EQ(long_reason, reason);
  556. }
  557. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  558. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  559. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  560. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  561. EXPECT_EQ("", detail::file_extension("noext"));
  562. EXPECT_EQ("", detail::file_extension("a."));
  563. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  564. EXPECT_EQ("", detail::file_extension("a.b-c"));
  565. // Long enough to overflow the stack when matched with std::regex.
  566. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  567. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  568. }
  569. #ifdef CPPHTTPLIB_SSL_ENABLED
  570. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  571. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  573. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  574. // A wildcard needs two labels after it, in the leftmost label only
  575. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  576. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  577. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  578. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  579. EXPECT_FALSE(
  580. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  581. // No name may have an empty label
  582. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  583. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  584. }
  585. #endif
  586. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  587. detail::case_ignore::hash hash;
  588. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  589. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  590. // Long enough to overflow the stack if hashed one call per character.
  591. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  592. }
  593. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  594. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  595. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  596. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  597. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  598. // Same 26-bit hash as html, svg and js.
  599. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  601. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  602. }
  603. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  604. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  605. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  606. }
  607. }
  608. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  609. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  610. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  611. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  612. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  613. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  614. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  615. // Same 26-bit hash as application/json.
  616. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  617. }
  618. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  619. Request req;
  620. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  621. EXPECT_TRUE(req.is_multipart_form_data());
  622. std::string boundary;
  623. EXPECT_TRUE(detail::parse_multipart_boundary(
  624. req.get_header_value("Content-Type"), boundary));
  625. EXPECT_EQ("x", boundary);
  626. }
  627. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  628. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  629. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  630. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  631. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  632. // Same 26-bit hash as REMOTE_ADDR.
  633. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  634. }
  635. // Forward declaration: in split builds split.py strips `inline` and moves the
  636. // definition into httplib.cc, so detail::base64_encode is not visible from the
  637. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  638. // in both header-only and split builds.
  639. namespace httplib {
  640. namespace detail {
  641. std::string base64_encode(const std::string &in);
  642. } // namespace detail
  643. } // namespace httplib
  644. TEST(Base64EncodeTest, KnownAnswers) {
  645. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  646. // where the accumulator's top bit is already set before the next shift.
  647. EXPECT_EQ("", detail::base64_encode(""));
  648. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  649. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  650. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  651. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  652. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  653. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  654. // High bytes keep the top bit set across several rounds.
  655. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  656. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  657. }
  658. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(ClientQueryOrder, PreserveOrder) {
  668. // This test reproduces Issue #2259: client may reorder query parameters
  669. // when sending a GET request. The expected behavior is that the client
  670. // preserves the original query string order when the caller supplied it
  671. // as part of the path.
  672. Server svr;
  673. svr.Get("/", [&](const Request &req, Response &res) {
  674. // Echo back the raw target so the test can assert ordering
  675. res.set_content(req.target, "text/plain");
  676. });
  677. std::thread t{[&] { svr.listen(HOST, PORT); }};
  678. auto se = detail::scope_exit([&] {
  679. svr.stop();
  680. t.join();
  681. ASSERT_FALSE(svr.is_running());
  682. });
  683. svr.wait_until_ready();
  684. Client cli(HOST, PORT);
  685. ASSERT_TRUE(cli.is_valid());
  686. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  687. auto res = cli.Get(original);
  688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  689. // Expect the echoed target to exactly match the original path (order
  690. // preserved)
  691. EXPECT_EQ(res->body, original);
  692. }
  693. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  694. string chineseCharacters = U8("中国語");
  695. string russianCharacters = U8("дом");
  696. string brazilianCharacters = U8("óculos");
  697. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  698. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  699. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  700. "%D0%B4%D0%BE%D0%BC");
  701. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  702. }
  703. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  704. string unescapedCharacters = "-_.!~*'()";
  705. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  706. }
  707. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  708. string reservedCharacters = ";,/?:@&=+$";
  709. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  710. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  711. }
  712. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  713. string chineseCharacters = U8("中国語");
  714. string russianCharacters = U8("дом");
  715. string brazilianCharacters = U8("óculos");
  716. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  717. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  718. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  719. "%D0%B4%D0%BE%D0%BC");
  720. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  721. }
  722. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  723. // Issue #2082 use case: encoding path component with ampersand
  724. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  725. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  726. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  727. }
  728. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  729. string unescapedCharacters = "-_.!~*'()";
  730. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  731. }
  732. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  733. string reservedCharacters = ";,/?:@&=+$#";
  734. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  735. }
  736. TEST(EncodeUriTest, TestUTF8Characters) {
  737. string chineseCharacters = U8("中国語");
  738. string russianCharacters = U8("дом");
  739. string brazilianCharacters = U8("óculos");
  740. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  741. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  742. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  743. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  744. }
  745. TEST(EncodeUriTest, TestCompleteUri) {
  746. string uri =
  747. "https://example.com/path/to/resource?query=value&param=test#fragment";
  748. EXPECT_EQ(
  749. httplib::encode_uri(uri),
  750. "https://example.com/path/to/resource?query=value&param=test#fragment");
  751. }
  752. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  753. string uri =
  754. "https://example.com/path with spaces/file name.html?q=hello world";
  755. EXPECT_EQ(httplib::encode_uri(uri),
  756. "https://example.com/path%20with%20spaces/"
  757. "file%20name.html?q=hello%20world");
  758. }
  759. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  760. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  762. }
  763. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  764. string unescapedCharacters = "-_.!~*'()";
  765. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  766. }
  767. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  768. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  769. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  770. string encodedBrazilian = "%C3%B3culos";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  772. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  773. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  774. }
  775. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  776. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  777. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  778. "Piri Tommy Villiers - on & on");
  779. }
  780. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  781. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  782. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  783. }
  784. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  785. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  786. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  787. }
  788. TEST(DecodeUriTest, TestUTF8Characters) {
  789. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  790. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  791. string encodedBrazilian = "%C3%B3culos";
  792. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  793. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  794. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  795. }
  796. TEST(DecodeUriTest, TestCompleteUri) {
  797. string encodedUri = "https://example.com/path%20with%20spaces/"
  798. "file%20name.html?q=hello%20world";
  799. EXPECT_EQ(
  800. httplib::decode_uri(encodedUri),
  801. "https://example.com/path with spaces/file name.html?q=hello world");
  802. }
  803. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  804. string original =
  805. "https://example.com/path with spaces/file name.html?q=hello world";
  806. string encoded = httplib::encode_uri(original);
  807. string decoded = httplib::decode_uri(encoded);
  808. EXPECT_EQ(decoded, original);
  809. }
  810. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  811. // decode_uri is the inverse of encode_uri: an escaped reserved character
  812. // stays encoded so it is not promoted into a real delimiter, while
  813. // non-reserved escapes still decode (like JS decodeURI).
  814. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  815. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  816. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  817. "%3F%3A%40%26%3D%2B%24%2C%3B");
  818. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  819. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  820. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  821. "http://example.com/a%2Fb");
  822. // decode_uri_component still decodes the reserved character.
  823. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  824. }
  825. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  826. string original = "Piri Tommy Villiers - on & on";
  827. string encoded = httplib::encode_uri_component(original);
  828. string decoded = httplib::decode_uri_component(encoded);
  829. EXPECT_EQ(decoded, original);
  830. }
  831. TEST(TrimTests, TrimStringTests) {
  832. EXPECT_EQ("abc", detail::trim_copy("abc"));
  833. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  834. EXPECT_TRUE(detail::trim_copy("").empty());
  835. }
  836. TEST(AsciiTest, LocaleIndependentClassification) {
  837. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  838. // which consult the global C locale: std::isalnum(0xC5) can return true
  839. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  840. // helpers must classify every byte by the ASCII grammar alone.
  841. for (int i = 0; i < 256; i++) {
  842. auto c = static_cast<char>(i);
  843. auto is_digit = i >= '0' && i <= '9';
  844. auto is_upper = i >= 'A' && i <= 'Z';
  845. auto is_lower = i >= 'a' && i <= 'z';
  846. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  847. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  848. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  849. << "byte " << i;
  850. }
  851. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  852. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  853. // Non-ASCII bytes must be percent-encoded, never passed through as
  854. // alphanumeric.
  855. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  856. }
  857. TEST(FromCharsTest, Double) {
  858. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  859. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  860. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  861. auto parse = [](const std::string &s, double &v) {
  862. return detail::from_chars(s.data(), s.data() + s.size(), v);
  863. };
  864. double v = -1.0;
  865. // Representative quality values.
  866. EXPECT_EQ(parse("0", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.0);
  868. EXPECT_EQ(parse("1", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.8);
  872. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 0.001);
  874. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  875. EXPECT_DOUBLE_EQ(v, 1.0);
  876. // A missing integer or fractional part is tolerated.
  877. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.5);
  879. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  880. EXPECT_DOUBLE_EQ(v, 5.0);
  881. // Values outside [0, 1] still parse; the caller range-checks them.
  882. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  883. EXPECT_DOUBLE_EQ(v, 123.456);
  884. // Stops at the first byte that is not part of the number and reports where.
  885. std::string trailing = "0.9, text/html";
  886. auto r = parse(trailing, v);
  887. EXPECT_EQ(r.ec, std::errc{});
  888. EXPECT_DOUBLE_EQ(v, 0.9);
  889. EXPECT_EQ(*r.ptr, ',');
  890. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  891. // outright, and an 'e'/'E' simply ends the number.
  892. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  894. std::string exp_input = "1.5e3";
  895. r = parse(exp_input, v);
  896. EXPECT_EQ(r.ec, std::errc{});
  897. EXPECT_DOUBLE_EQ(v, 1.5);
  898. EXPECT_EQ(*r.ptr, 'e');
  899. // Invalid inputs.
  900. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  901. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  902. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  903. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  904. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  905. // Pathological but well-formed inputs must stay bounded (no overflow, no
  906. // out-of-bounds table access) and stay within [0, 1] for the caller.
  907. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  908. std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.0);
  910. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  911. std::errc{});
  912. EXPECT_GE(v, 0.0);
  913. EXPECT_LE(v, 1.0);
  914. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  915. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  916. }
  917. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  918. // Simple case without quality values
  919. std::vector<std::string> result1;
  920. EXPECT_TRUE(detail::parse_accept_header(
  921. "text/html,application/json,text/plain", result1));
  922. EXPECT_EQ(result1.size(), 3U);
  923. EXPECT_EQ(result1[0], "text/html");
  924. EXPECT_EQ(result1[1], "application/json");
  925. EXPECT_EQ(result1[2], "text/plain");
  926. // With quality values
  927. std::vector<std::string> result2;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  930. EXPECT_EQ(result2.size(), 3U);
  931. EXPECT_EQ(result2[0], "application/json"); // highest q value
  932. EXPECT_EQ(result2[1], "text/html");
  933. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  934. }
  935. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  936. // Mixed with and without quality values
  937. std::vector<std::string> result;
  938. EXPECT_TRUE(detail::parse_accept_header(
  939. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  940. EXPECT_EQ(result.size(), 3U);
  941. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  942. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  943. EXPECT_EQ(result[2], "application/json"); // q=0.5
  944. }
  945. TEST(ParseAcceptHeaderTest, EdgeCases) {
  946. // Empty header
  947. std::vector<std::string> empty_result;
  948. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  949. EXPECT_TRUE(empty_result.empty());
  950. // Single type
  951. std::vector<std::string> single_result;
  952. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  953. EXPECT_EQ(single_result.size(), 1U);
  954. EXPECT_EQ(single_result[0], "application/json");
  955. // Wildcard types
  956. std::vector<std::string> wildcard_result;
  957. EXPECT_TRUE(detail::parse_accept_header(
  958. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  959. EXPECT_EQ(wildcard_result.size(), 3U);
  960. EXPECT_EQ(wildcard_result[0], "application/json");
  961. EXPECT_EQ(wildcard_result[1], "text/*");
  962. EXPECT_EQ(wildcard_result[2], "*/*");
  963. }
  964. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  965. // Common browser Accept header
  966. std::vector<std::string> browser_result;
  967. EXPECT_TRUE(
  968. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  969. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  970. browser_result));
  971. EXPECT_EQ(browser_result.size(), 6U);
  972. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  973. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  974. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  975. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  976. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  977. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  978. // API client header
  979. std::vector<std::string> api_result;
  980. EXPECT_TRUE(detail::parse_accept_header(
  981. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  982. api_result));
  983. EXPECT_EQ(api_result.size(), 3U);
  984. EXPECT_EQ(api_result[0], "application/json");
  985. EXPECT_EQ(api_result[1], "application/xml");
  986. EXPECT_EQ(api_result[2], "text/plain");
  987. }
  988. TEST(ParseAcceptHeaderTest, SpecialCases) {
  989. // Quality value with 3 decimal places
  990. std::vector<std::string> decimal_result;
  991. EXPECT_TRUE(detail::parse_accept_header(
  992. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  993. EXPECT_EQ(decimal_result.size(), 2U);
  994. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  995. EXPECT_EQ(decimal_result[1], "text/html");
  996. // Zero quality (should still be included but with lowest priority)
  997. std::vector<std::string> zero_q_result;
  998. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  999. zero_q_result));
  1000. EXPECT_EQ(zero_q_result.size(), 2U);
  1001. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1002. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1003. // No spaces around commas
  1004. std::vector<std::string> no_space_result;
  1005. EXPECT_TRUE(detail::parse_accept_header(
  1006. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1007. no_space_result));
  1008. EXPECT_EQ(no_space_result.size(), 3U);
  1009. EXPECT_EQ(no_space_result[0], "text/html");
  1010. EXPECT_EQ(no_space_result[1], "application/json");
  1011. EXPECT_EQ(no_space_result[2], "text/plain");
  1012. }
  1013. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1014. // Quality values always use '.' as the decimal separator, so parsing must
  1015. // not depend on the process locale. An embedding application may have
  1016. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1017. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1018. std::string saved = cur ? cur : "C";
  1019. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1020. "fr_FR.UTF-8"};
  1021. bool switched = false;
  1022. for (const auto loc : comma_locales) {
  1023. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1024. std::localeconv()->decimal_point[0] == ',') {
  1025. switched = true;
  1026. break;
  1027. }
  1028. }
  1029. if (!switched) {
  1030. std::setlocale(LC_NUMERIC, saved.c_str());
  1031. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1032. }
  1033. // The higher-weighted type appears later in the list, so a correct parse
  1034. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1035. // sensitive parse reads both weights as 0 and leaves the original order.
  1036. std::vector<std::string> result;
  1037. EXPECT_TRUE(detail::parse_accept_header(
  1038. "application/json;q=0.1,text/html;q=0.9", result));
  1039. ASSERT_EQ(result.size(), 2U);
  1040. EXPECT_EQ(result[0], "text/html");
  1041. EXPECT_EQ(result[1], "application/json");
  1042. std::setlocale(LC_NUMERIC, saved.c_str());
  1043. }
  1044. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1045. std::vector<std::string> result;
  1046. // Invalid quality value (> 1.0)
  1047. EXPECT_FALSE(
  1048. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1049. // Invalid quality value (< 0.0)
  1050. EXPECT_FALSE(
  1051. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1052. // Invalid quality value (not a number)
  1053. EXPECT_FALSE(detail::parse_accept_header(
  1054. "text/html;q=invalid,application/json", result));
  1055. // A valid numeric prefix does not make the entire quality value valid.
  1056. EXPECT_FALSE(detail::parse_accept_header(
  1057. "text/html;q=0.5junk,application/json", result));
  1058. // Empty quality value
  1059. EXPECT_FALSE(
  1060. detail::parse_accept_header("text/html;q=,application/json", result));
  1061. // Invalid media type format (no slash and not wildcard)
  1062. EXPECT_FALSE(
  1063. detail::parse_accept_header("invalidtype,application/json", result));
  1064. // Valid cases should still work
  1065. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "*/*");
  1068. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1069. EXPECT_EQ(result.size(), 1U);
  1070. EXPECT_EQ(result[0], "*");
  1071. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1072. EXPECT_EQ(result.size(), 1U);
  1073. EXPECT_EQ(result[0], "text/*");
  1074. }
  1075. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1076. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1077. // and must not be answered with 400 Bad Request.
  1078. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1079. struct {
  1080. const char *value;
  1081. std::vector<std::string> expected;
  1082. } cases[] = {
  1083. {",application/json", {"application/json"}},
  1084. {"text/html,", {"text/html"}},
  1085. {"text/html,,*/*", {"text/html", "*/*"}},
  1086. // An empty element may be spelled with whitespace in it
  1087. {"text/html, , application/json", {"text/html", "application/json"}},
  1088. // Nothing but empty elements is an empty list, which means the same
  1089. // thing as no Accept header at all
  1090. {",,,", {}},
  1091. // Quality values still apply across ignored empty elements
  1092. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1093. };
  1094. for (const auto &c : cases) {
  1095. std::vector<std::string> result;
  1096. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1097. << "value: " << c.value;
  1098. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1099. }
  1100. // An invalid entry is still rejected when empty elements surround it
  1101. std::vector<std::string> result;
  1102. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1103. }
  1104. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1105. // or ';' inside one does not end the list element or the parameter. Section
  1106. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1107. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1108. struct {
  1109. const char *value;
  1110. std::vector<std::string> expected;
  1111. } cases[] = {
  1112. {"text/html;profile=\"a,b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // A "q=" inside a quoted value is not the weight
  1115. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1116. {"text/html", "application/json"}},
  1117. // The weight after a quoted value still applies
  1118. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1119. {"application/json", "text/html"}},
  1120. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1121. {"application/json", "text/html"}},
  1122. {"text/html;profile=\"a\\\"b\",application/json",
  1123. {"text/html", "application/json"}},
  1124. // An escaped backslash does not escape the '"' after it
  1125. {"text/html;profile=\"a\\\\\",application/json",
  1126. {"text/html", "application/json"}},
  1127. };
  1128. for (const auto &c : cases) {
  1129. std::vector<std::string> result;
  1130. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1131. << "value: " << c.value;
  1132. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1133. }
  1134. }
  1135. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1136. Server svr;
  1137. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1138. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1139. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1140. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1141. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1142. res.set_content("ok", "text/plain");
  1143. });
  1144. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1145. EXPECT_TRUE(false);
  1146. res.set_content("bad request", "text/plain");
  1147. });
  1148. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1149. auto se = detail::scope_exit([&] {
  1150. svr.stop();
  1151. listen_thread.join();
  1152. ASSERT_FALSE(svr.is_running());
  1153. });
  1154. svr.wait_until_ready();
  1155. Client cli("localhost", PORT);
  1156. {
  1157. auto res = cli.Get(
  1158. "/accept_ok",
  1159. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. {
  1164. auto res = cli.Get("/accept_bad_request",
  1165. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1167. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1168. }
  1169. }
  1170. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1171. Server svr;
  1172. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1173. res.set_content("ok", "text/plain");
  1174. });
  1175. std::atomic<int> start_count{0};
  1176. std::atomic<bool> running_when_called{false};
  1177. svr.set_start_handler([&]() {
  1178. running_when_called = svr.is_running();
  1179. start_count++;
  1180. });
  1181. auto port = svr.bind_to_any_port(HOST);
  1182. std::thread t([&]() { svr.listen_after_bind(); });
  1183. auto se = detail::scope_exit([&] {
  1184. svr.stop();
  1185. t.join();
  1186. ASSERT_FALSE(svr.is_running());
  1187. });
  1188. svr.wait_until_ready();
  1189. // A successful request proves the accept loop is running, which the start
  1190. // handler precedes; so by now the handler must have run exactly once.
  1191. Client cli(HOST, port);
  1192. cli.set_connection_timeout(std::chrono::seconds(5));
  1193. auto res = cli.Get("/");
  1194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1195. EXPECT_EQ(StatusCode::OK_200, res->status);
  1196. EXPECT_EQ(1, start_count.load());
  1197. EXPECT_TRUE(running_when_called.load());
  1198. }
  1199. TEST(DivideTest, DivideStringTests) {
  1200. auto divide = [](const std::string &str, char d) {
  1201. std::string lhs;
  1202. std::string rhs;
  1203. detail::divide(str, d,
  1204. [&](const char *lhs_data, std::size_t lhs_size,
  1205. const char *rhs_data, std::size_t rhs_size) {
  1206. lhs.assign(lhs_data, lhs_size);
  1207. rhs.assign(rhs_data, rhs_size);
  1208. });
  1209. return std::make_pair(std::move(lhs), std::move(rhs));
  1210. };
  1211. {
  1212. const auto res = divide("", '=');
  1213. EXPECT_EQ(res.first, "");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("=", '=');
  1218. EXPECT_EQ(res.first, "");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide(" ", '=');
  1223. EXPECT_EQ(res.first, " ");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("a", '=');
  1228. EXPECT_EQ(res.first, "a");
  1229. EXPECT_EQ(res.second, "");
  1230. }
  1231. {
  1232. const auto res = divide("a=", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "");
  1235. }
  1236. {
  1237. const auto res = divide("=b", '=');
  1238. EXPECT_EQ(res.first, "");
  1239. EXPECT_EQ(res.second, "b");
  1240. }
  1241. {
  1242. const auto res = divide("a=b", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b");
  1245. }
  1246. {
  1247. const auto res = divide("a=b=", '=');
  1248. EXPECT_EQ(res.first, "a");
  1249. EXPECT_EQ(res.second, "b=");
  1250. }
  1251. {
  1252. const auto res = divide("a=b=c", '=');
  1253. EXPECT_EQ(res.first, "a");
  1254. EXPECT_EQ(res.second, "b=c");
  1255. }
  1256. }
  1257. TEST(SplitTest, ParseQueryString) {
  1258. string s = "key1=val1&key2=val2&key3=val3";
  1259. Params dic;
  1260. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1261. [&](const char *b, const char *e) {
  1262. string key, val;
  1263. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1264. if (key.empty()) {
  1265. key.assign(b2, e2);
  1266. } else {
  1267. val.assign(b2, e2);
  1268. }
  1269. });
  1270. dic.emplace(key, val);
  1271. });
  1272. EXPECT_EQ("val1", dic.find("key1")->second);
  1273. EXPECT_EQ("val2", dic.find("key2")->second);
  1274. EXPECT_EQ("val3", dic.find("key3")->second);
  1275. }
  1276. TEST(SplitTest, ParseInvalidQueryTests) {
  1277. {
  1278. string s = " ";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. {
  1284. string s = " = =";
  1285. Params dict;
  1286. detail::parse_query_text(s, dict);
  1287. EXPECT_TRUE(dict.empty());
  1288. }
  1289. }
  1290. TEST(ParseQueryTest, ParseQueryString) {
  1291. {
  1292. std::string s = "key1=val1&key2=val2&key3=val3";
  1293. Params dic;
  1294. detail::parse_query_text(s, dic);
  1295. EXPECT_EQ("val1", dic.find("key1")->second);
  1296. EXPECT_EQ("val2", dic.find("key2")->second);
  1297. EXPECT_EQ("val3", dic.find("key3")->second);
  1298. }
  1299. {
  1300. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1301. Params dic;
  1302. detail::parse_query_text(s, dic);
  1303. EXPECT_EQ("", dic.find("key1")->second);
  1304. EXPECT_EQ("val1", dic.find("key2")->second);
  1305. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1306. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1307. }
  1308. }
  1309. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1310. Params dic;
  1311. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1312. dic.emplace("key1", "val1");
  1313. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1314. dic.emplace("key2", "val2");
  1315. dic.emplace("key3", "val3");
  1316. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1317. }
  1318. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1319. Params params;
  1320. params.emplace("a", "1");
  1321. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1322. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1323. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1324. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1325. // Long enough to overflow the stack when matched with std::regex.
  1326. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1327. EXPECT_EQ("/p?" + long_query + "&a=1",
  1328. append_query_params("/p?" + long_query, params));
  1329. }
  1330. // Joins every entry of a Headers or Params into "key=value " so a whole
  1331. // traversal can be compared in one assertion. Both are instantiations of the
  1332. // same insertion-ordered container, so one helper serves both.
  1333. template <typename Map> static std::string entries_to_string(const Map &m) {
  1334. std::string s;
  1335. for (const auto &entry : m) {
  1336. s += entry.first + "=" + entry.second + " ";
  1337. }
  1338. return s;
  1339. }
  1340. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1341. // Params used to be a std::multimap, which sorted by name and handed the
  1342. // caller's query back alphabetised. A client signing its query string could
  1343. // not reproduce the order it asked for.
  1344. Params dic;
  1345. dic.emplace("zulu", "1");
  1346. dic.emplace("alpha", "2");
  1347. dic.emplace("mike", "3");
  1348. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1349. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1350. }
  1351. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1352. Params dic;
  1353. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1354. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1355. }
  1356. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1357. Request req;
  1358. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1359. req.params);
  1360. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1361. EXPECT_EQ("first", req.get_param_value("tag"));
  1362. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1363. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1364. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1365. EXPECT_EQ("", req.get_param_value("tag", 3));
  1366. }
  1367. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1368. // Params shares its container with Headers, which matches field names
  1369. // case-insensitively. Parameter names must not pick that up.
  1370. Params dic;
  1371. dic.emplace("Key", "upper");
  1372. dic.emplace("key", "lower");
  1373. EXPECT_EQ(2U, dic.size());
  1374. EXPECT_EQ(1U, dic.count("Key"));
  1375. EXPECT_EQ(1U, dic.count("key"));
  1376. EXPECT_EQ("upper", dic.find("Key")->second);
  1377. EXPECT_EQ("lower", dic.find("key")->second);
  1378. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1379. }
  1380. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1381. Server svr;
  1382. std::string order;
  1383. svr.Get("/order", [&](const Request &req, Response &res) {
  1384. order = entries_to_string(req.params);
  1385. res.set_content("ok", "text/plain");
  1386. });
  1387. auto port = svr.bind_to_any_port(HOST);
  1388. thread t = thread([&] { svr.listen_after_bind(); });
  1389. auto se = detail::scope_exit([&] {
  1390. svr.stop();
  1391. t.join();
  1392. ASSERT_FALSE(svr.is_running());
  1393. });
  1394. svr.wait_until_ready();
  1395. Client cli(HOST, port);
  1396. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1397. ASSERT_TRUE(res);
  1398. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1399. }
  1400. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1401. Server svr;
  1402. std::string field_order, file_order;
  1403. svr.Post("/order", [&](const Request &req, Response &res) {
  1404. for (const auto &field : req.form.fields) {
  1405. field_order += field.first + "=" + field.second.content + " ";
  1406. }
  1407. for (const auto &file : req.form.files) {
  1408. file_order += file.first + "=" + file.second.filename + " ";
  1409. }
  1410. res.set_content("ok", "text/plain");
  1411. });
  1412. auto port = svr.bind_to_any_port(HOST);
  1413. thread t = thread([&] { svr.listen_after_bind(); });
  1414. auto se = detail::scope_exit([&] {
  1415. svr.stop();
  1416. t.join();
  1417. ASSERT_FALSE(svr.is_running());
  1418. });
  1419. svr.wait_until_ready();
  1420. UploadFormDataItems items = {
  1421. {"zulu", "1", "", ""},
  1422. {"alpha", "2", "", ""},
  1423. {"mike", "3", "", ""},
  1424. {"zebra", "z", "z.txt", "text/plain"},
  1425. {"apple", "a", "a.txt", "text/plain"},
  1426. };
  1427. Client cli(HOST, port);
  1428. auto res = cli.Post("/order", items);
  1429. ASSERT_TRUE(res);
  1430. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1431. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1432. }
  1433. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1434. Server svr;
  1435. std::vector<std::string> values;
  1436. std::string first, second, out_of_range, order;
  1437. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1438. values = req.form.get_fields("tag");
  1439. first = req.form.get_field("tag", 0);
  1440. second = req.form.get_field("tag", 1);
  1441. out_of_range = req.form.get_field("tag", 2);
  1442. for (const auto &field : req.form.fields) {
  1443. order += field.first + "=" + field.second.content + " ";
  1444. }
  1445. res.set_content("ok", "text/plain");
  1446. });
  1447. auto port = svr.bind_to_any_port(HOST);
  1448. thread t = thread([&] { svr.listen_after_bind(); });
  1449. auto se = detail::scope_exit([&] {
  1450. svr.stop();
  1451. t.join();
  1452. ASSERT_FALSE(svr.is_running());
  1453. });
  1454. svr.wait_until_ready();
  1455. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1456. // not adjacent in the container.
  1457. UploadFormDataItems items = {
  1458. {"tag", "first", "", ""},
  1459. {"other", "x", "", ""},
  1460. {"tag", "second", "", ""},
  1461. };
  1462. Client cli(HOST, port);
  1463. auto res = cli.Post("/repeated", items);
  1464. ASSERT_TRUE(res);
  1465. ASSERT_EQ(2U, values.size());
  1466. EXPECT_EQ("first", values[0]);
  1467. EXPECT_EQ("second", values[1]);
  1468. EXPECT_EQ("first", first);
  1469. EXPECT_EQ("second", second);
  1470. // std::multimap already kept entries sharing a name in insertion order, so
  1471. // everything above passes without this change too. The whole traversal is
  1472. // what tells the two apart: sorting by name would hoist "other" to the front
  1473. // and the two "tag" parts would end up adjacent.
  1474. EXPECT_EQ("tag=first other=x tag=second ", order);
  1475. // Advancing past the last entry of a name used to run off the container;
  1476. // the container's saturating increment makes it return the default instead.
  1477. EXPECT_EQ("", out_of_range);
  1478. }
  1479. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1480. Server svr;
  1481. std::string file_names;
  1482. svr.Post("/upload", [&](const Request &req, Response &res) {
  1483. for (const auto &file : req.form.files) {
  1484. file_names += file.first + "|" + file.second.filename + " ";
  1485. }
  1486. res.set_content("ok", "text/plain");
  1487. });
  1488. auto port = svr.bind_to_any_port(HOST);
  1489. thread t = thread([&] { svr.listen_after_bind(); });
  1490. auto se = detail::scope_exit([&] {
  1491. svr.stop();
  1492. t.join();
  1493. ASSERT_FALSE(svr.is_running());
  1494. });
  1495. svr.wait_until_ready();
  1496. // A trailing backslash would otherwise escape the closing quote.
  1497. UploadFormDataItems items = {
  1498. {"dir\\", "x", "a.txt", "text/plain"},
  1499. {"b", "y", "a\\\\b.txt", "text/plain"},
  1500. };
  1501. Client cli(HOST, port);
  1502. auto res = cli.Post("/upload", items);
  1503. ASSERT_TRUE(res);
  1504. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1505. }
  1506. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1507. // Server::read_content() keeps a FormFields::iterator alive across the
  1508. // content callbacks that fill the part it points at. The container is
  1509. // vector-backed, so a later emplace can reallocate and invalidate an older
  1510. // iterator; 64 parts grow the vector through seven reallocations, which
  1511. // checks that every part's content still lands in its own entry.
  1512. const size_t part_count = 64;
  1513. // One formula for both the parts sent and the values expected back, so the
  1514. // two cannot drift apart.
  1515. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1516. auto content_of = [](size_t i) {
  1517. return std::string(64, static_cast<char>('a' + (i % 26)));
  1518. };
  1519. Server svr;
  1520. std::vector<std::pair<std::string, std::string>> received;
  1521. svr.Post("/many", [&](const Request &req, Response &res) {
  1522. for (const auto &field : req.form.fields) {
  1523. received.emplace_back(field.first, field.second.content);
  1524. }
  1525. res.set_content("ok", "text/plain");
  1526. });
  1527. auto port = svr.bind_to_any_port(HOST);
  1528. thread t = thread([&] { svr.listen_after_bind(); });
  1529. auto se = detail::scope_exit([&] {
  1530. svr.stop();
  1531. t.join();
  1532. ASSERT_FALSE(svr.is_running());
  1533. });
  1534. svr.wait_until_ready();
  1535. UploadFormDataItems items;
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. items.push_back({name_of(i), content_of(i), "", ""});
  1538. }
  1539. Client cli(HOST, port);
  1540. auto res = cli.Post("/many", items);
  1541. ASSERT_TRUE(res);
  1542. ASSERT_EQ(part_count, received.size());
  1543. for (size_t i = 0; i < part_count; i++) {
  1544. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1545. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1546. }
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1549. string content_type = "multipart/form-data; boundary=something";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "something");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1556. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1557. string boundary;
  1558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1559. EXPECT_TRUE(ret);
  1560. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1561. }
  1562. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1563. string content_type =
  1564. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1565. string boundary;
  1566. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1567. EXPECT_TRUE(ret);
  1568. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1569. }
  1570. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1571. string content_type =
  1572. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1573. string boundary;
  1574. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1575. EXPECT_TRUE(ret);
  1576. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1577. }
  1578. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1579. const string boundary(70, 'a');
  1580. string content_type = "multipart/form-data; boundary=" + boundary;
  1581. string parsed;
  1582. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1583. EXPECT_TRUE(ret);
  1584. EXPECT_EQ(parsed, boundary);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1587. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1588. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1589. string parsed;
  1590. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1591. EXPECT_FALSE(ret);
  1592. }
  1593. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1594. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1595. // is 72 characters on the wire and still valid.
  1596. const string boundary(70, 'a');
  1597. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1598. string parsed;
  1599. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1600. EXPECT_EQ(parsed, boundary);
  1601. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1602. parsed.clear();
  1603. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1604. }
  1605. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1606. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1607. // The parameter parser must not treat that '=' as the key/value separator.
  1608. string content_type =
  1609. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1610. "charset=UTF-8";
  1611. string parsed;
  1612. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1613. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1614. }
  1615. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1616. // A ';' inside the quoted-string is part of the value, not a parameter
  1617. // separator, so it must not truncate the boundary.
  1618. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1619. string parsed;
  1620. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1621. EXPECT_EQ(parsed, "a;b");
  1622. }
  1623. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1624. string parsed;
  1625. EXPECT_TRUE(detail::parse_multipart_boundary(
  1626. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1627. EXPECT_EQ("a\\b", parsed);
  1628. EXPECT_TRUE(detail::parse_multipart_boundary(
  1629. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1630. EXPECT_EQ("a\"b", parsed);
  1631. }
  1632. TEST(ParseDispositionParamsTest, QuotedValues) {
  1633. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1634. // ';' and '=' are ordinary characters inside one.
  1635. struct {
  1636. const char *value;
  1637. std::vector<std::pair<const char *, const char *>> expected;
  1638. } cases[] = {
  1639. {"name=\"file1\"; filename=\"a.txt\"",
  1640. {{"name", "file1"}, {"filename", "a.txt"}}},
  1641. // Whitespace around '=' and ';' is still trimmed
  1642. {"name=\"file2\" ;filename = \"a.html\"",
  1643. {{"name", "file2"}, {"filename", "a.html"}}},
  1644. // '=' inside the value used to leave only the text after the last one
  1645. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1646. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1647. {"name=\"x=y\"", {{"name", "x=y"}}},
  1648. // ';' inside the value used to truncate the pair and leave a bogus one
  1649. {"name=\"file3\"; filename=\"a;b.txt\"",
  1650. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1651. // An unquoted value keeps working, and so does filename*
  1652. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1653. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1654. // A parameter with no key is dropped rather than turned into one whose
  1655. // key is the value
  1656. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1657. // An escaped quote does not end the value
  1658. {"name=\"a\\\"; filename=evil.php\"",
  1659. {{"name", "a\"; filename=evil.php"}}},
  1660. // Other backslashes, as in a Windows path, are kept
  1661. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1662. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1663. };
  1664. for (const auto &c : cases) {
  1665. Params params;
  1666. detail::parse_disposition_params(c.value, params);
  1667. for (const auto &kv : c.expected) {
  1668. auto it = params.find(kv.first);
  1669. ASSERT_NE(it, params.end())
  1670. << "value: " << c.value << ", key: " << kv.first;
  1671. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1672. }
  1673. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1674. }
  1675. }
  1676. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1677. Server svr;
  1678. std::string filename;
  1679. std::string content;
  1680. svr.Post("/upload", [&](const Request &req, Response &) {
  1681. const auto &file = req.form.get_file("file");
  1682. filename = file.filename;
  1683. content = file.content;
  1684. });
  1685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1686. auto se = detail::scope_exit([&] {
  1687. svr.stop();
  1688. thread.join();
  1689. ASSERT_FALSE(svr.is_running());
  1690. });
  1691. svr.wait_until_ready();
  1692. std::string body = "--B\r\n"
  1693. "Content-Disposition: form-data; name=\"file\"; "
  1694. "filename=\"a.txt\"\r\n"
  1695. "Content-Type: text/plain\r\n"
  1696. "\r\n"
  1697. "hello\r\n"
  1698. "--B--\r\n";
  1699. Client cli(HOST, PORT);
  1700. auto res = cli.Post(
  1701. "/upload",
  1702. [&](size_t offset, DataSink &sink) {
  1703. if (offset < body.size()) {
  1704. sink.write(&body[offset], 1);
  1705. } else {
  1706. sink.done();
  1707. }
  1708. return true;
  1709. },
  1710. "multipart/form-data; boundary=B");
  1711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. EXPECT_EQ("a.txt", filename);
  1714. EXPECT_EQ("hello", content);
  1715. }
  1716. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1717. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1718. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1719. Server svr;
  1720. std::string field_value, file_name, file_filename;
  1721. bool has_field = false, has_file = false;
  1722. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1723. has_field = req.form.has_field("x=y");
  1724. field_value = req.form.get_field("x=y");
  1725. has_file = req.form.has_file("file1");
  1726. const auto &file = req.form.get_file("file1");
  1727. file_name = file.name;
  1728. file_filename = file.filename;
  1729. res.set_content("ok", "text/plain");
  1730. });
  1731. auto port = svr.bind_to_any_port(HOST);
  1732. thread t = thread([&] { svr.listen_after_bind(); });
  1733. auto se = detail::scope_exit([&] {
  1734. svr.stop();
  1735. t.join();
  1736. ASSERT_FALSE(svr.is_running());
  1737. });
  1738. svr.wait_until_ready();
  1739. UploadFormDataItems items = {
  1740. {"x=y", "field-value", "", ""},
  1741. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1742. };
  1743. Client cli(HOST, port);
  1744. auto res = cli.Post("/quoted", items);
  1745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1746. ASSERT_EQ(StatusCode::OK_200, res->status);
  1747. EXPECT_TRUE(has_field);
  1748. EXPECT_EQ("field-value", field_value);
  1749. EXPECT_TRUE(has_file);
  1750. EXPECT_EQ("file1", file_name);
  1751. EXPECT_EQ("a;b=report.pdf", file_filename);
  1752. }
  1753. TEST(GetHeaderValueTest, DefaultValue) {
  1754. Headers headers = {{"Dummy", "Dummy"}};
  1755. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1756. EXPECT_STREQ("text/plain", val);
  1757. }
  1758. TEST(GetHeaderValueTest, DefaultValueInt) {
  1759. Headers headers = {{"Dummy", "Dummy"}};
  1760. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1761. EXPECT_EQ(100ull, val);
  1762. }
  1763. TEST(GetHeaderValueTest, RegularValue) {
  1764. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1765. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1766. EXPECT_STREQ("text/html", val);
  1767. }
  1768. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1769. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1770. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1771. EXPECT_STREQ("text/html", val);
  1772. }
  1773. TEST(GetHeaderValueTest, SetContent) {
  1774. Response res;
  1775. res.set_content("html", "text/html");
  1776. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1777. res.set_content("text", "text/plain");
  1778. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1779. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1780. }
  1781. TEST(GetHeaderValueTest, RegularValueInt) {
  1782. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1784. EXPECT_EQ(100ull, val);
  1785. }
  1786. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1787. Headers headers = {{"Content-Length", "x"}};
  1788. auto is_invalid_value = false;
  1789. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1790. is_invalid_value);
  1791. EXPECT_EQ(0ull, val);
  1792. EXPECT_TRUE(is_invalid_value);
  1793. }
  1794. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1795. // An all-digit value that overflows size_t must be reported as invalid, not
  1796. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1797. // a large length to a small one on 32-bit builds, leaving the framing length
  1798. // wrong while is_invalid_value stayed false.
  1799. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1800. auto is_invalid_value = false;
  1801. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_TRUE(is_invalid_value);
  1804. // A well-formed length is unaffected.
  1805. Headers ok = {{"Content-Length", "1234"}};
  1806. is_invalid_value = false;
  1807. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1808. is_invalid_value);
  1809. EXPECT_EQ(1234ull, val);
  1810. EXPECT_FALSE(is_invalid_value);
  1811. }
  1812. TEST(GetHeaderValueTest, Range) {
  1813. {
  1814. Headers headers = {make_range_header({{1, -1}})};
  1815. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1816. EXPECT_STREQ("bytes=1-", val);
  1817. }
  1818. {
  1819. Headers headers = {make_range_header({{-1, 1}})};
  1820. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1821. EXPECT_STREQ("bytes=-1", val);
  1822. }
  1823. {
  1824. Headers headers = {make_range_header({{1, 10}})};
  1825. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1826. EXPECT_STREQ("bytes=1-10", val);
  1827. }
  1828. {
  1829. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1830. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1831. EXPECT_STREQ("bytes=1-10, 100-", val);
  1832. }
  1833. {
  1834. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1835. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1836. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1837. }
  1838. {
  1839. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1840. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1841. EXPECT_STREQ("bytes=0-0, -1", val);
  1842. }
  1843. }
  1844. TEST(BearerTokenAuthTest, SchemeValidation) {
  1845. // A value shorter than "Bearer " must not throw from the fixed-length
  1846. // substr, and a non-Bearer scheme must not be reported as a token.
  1847. struct {
  1848. const char *value;
  1849. const char *expected;
  1850. } cases[] = {
  1851. {"x", ""},
  1852. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1853. {"Bearer abc123", "abc123"},
  1854. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1855. };
  1856. for (const auto &c : cases) {
  1857. Request req;
  1858. req.set_header("Authorization", c.value);
  1859. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1860. }
  1861. }
  1862. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1863. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1864. // to depend on the standard library (libstdc++ handed back duplicates in
  1865. // reverse insertion order, libc++ in insertion order).
  1866. Request req;
  1867. req.set_header("Accept-Encoding", "gzip");
  1868. req.set_header("Accept-Encoding", "deflate");
  1869. req.set_header("Accept-Encoding", "br");
  1870. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1871. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1872. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1873. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1874. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1875. }
  1876. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1877. Request req;
  1878. req.set_header("X-Test", "only");
  1879. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1880. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1881. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1882. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1883. }
  1884. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1885. Request req;
  1886. req.set_header("X-First", "1");
  1887. req.set_header("X-Test", "2");
  1888. req.params.emplace("first", "1");
  1889. req.params.emplace("test", "2");
  1890. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1891. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1892. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1893. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1894. // The second one is negative when read as a signed value
  1895. const auto max_id = (std::numeric_limits<size_t>::max)();
  1896. for (auto id : {max_id / 2, max_id}) {
  1897. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1898. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1899. EXPECT_EQ("", req.get_param_value("test", id));
  1900. EXPECT_EQ("", req.form.get_field("test", id));
  1901. EXPECT_EQ("", req.form.get_file("test", id).content);
  1902. }
  1903. }
  1904. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1905. Headers headers;
  1906. headers.emplace("Host", "example.com");
  1907. headers.emplace("Accept-Encoding", "gzip");
  1908. headers.emplace("User-Agent", "test");
  1909. headers.emplace("Accept-Encoding", "deflate");
  1910. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1911. "Accept-Encoding=deflate ",
  1912. entries_to_string(headers));
  1913. }
  1914. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1915. Headers headers = {{"Content-Type", "text/html"},
  1916. {"CONTENT-TYPE", "text/xml"}};
  1917. EXPECT_EQ(2U, headers.count("content-type"));
  1918. auto it = headers.find("content-type");
  1919. ASSERT_TRUE(it != headers.end());
  1920. EXPECT_EQ("text/html", it->second);
  1921. }
  1922. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1923. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1924. // drop only those fields and leave everything positioned between them.
  1925. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1926. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1927. auto rng = headers.equal_range("a");
  1928. headers.erase(rng.first, rng.second);
  1929. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1932. Headers headers = {
  1933. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1934. EXPECT_EQ(3U, headers.erase("A"));
  1935. EXPECT_EQ(0U, headers.count("A"));
  1936. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1937. }
  1938. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1939. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1940. headers.emplace_front("Host", "example.com");
  1941. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1942. entries_to_string(headers));
  1943. }
  1944. TEST(ParseHeaderValueTest, Range) {
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1960. EXPECT_TRUE(ret);
  1961. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1962. }
  1963. {
  1964. Ranges ranges;
  1965. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1966. EXPECT_FALSE(ret);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1971. EXPECT_TRUE(ret);
  1972. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. auto ret =
  1977. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1980. }
  1981. {
  1982. Ranges ranges;
  1983. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1996. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1997. EXPECT_FALSE(
  1998. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1999. EXPECT_TRUE(ranges.empty());
  2000. }
  2001. {
  2002. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2003. // remainder of the representation, so it stays accepted.
  2004. Ranges ranges;
  2005. auto ret =
  2006. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2007. EXPECT_TRUE(ret);
  2008. ASSERT_EQ(1u, ranges.size());
  2009. EXPECT_EQ(0, ranges[0].first);
  2010. EXPECT_EQ(-1, ranges[0].second);
  2011. }
  2012. // RFC 9110 14.1: range unit names are case-insensitive.
  2013. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2014. Ranges ranges;
  2015. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2016. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2017. }
  2018. }
  2019. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2020. Request req;
  2021. req.set_header("Accept-Encoding", "gzip");
  2022. Response res;
  2023. res.set_header("Content-Type", "text/plain");
  2024. auto ret = detail::encoding_type(req, res);
  2025. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2026. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2027. #else
  2028. EXPECT_TRUE(ret == detail::EncodingType::None);
  2029. #endif
  2030. }
  2031. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2032. Request req;
  2033. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2034. Response res;
  2035. res.set_header("Content-Type", "text/plain");
  2036. auto ret = detail::encoding_type(req, res);
  2037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2043. #else
  2044. EXPECT_TRUE(ret == detail::EncodingType::None);
  2045. #endif
  2046. }
  2047. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2048. Request req;
  2049. req.set_header("Accept-Encoding",
  2050. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2051. Response res;
  2052. res.set_header("Content-Type", "text/plain");
  2053. auto ret = detail::encoding_type(req, res);
  2054. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2055. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2056. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2060. #else
  2061. EXPECT_TRUE(ret == detail::EncodingType::None);
  2062. #endif
  2063. }
  2064. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2065. // All supported encodings rejected with q=0 should return None
  2066. Request req;
  2067. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2068. Response res;
  2069. res.set_header("Content-Type", "text/plain");
  2070. auto ret = detail::encoding_type(req, res);
  2071. EXPECT_TRUE(ret == detail::EncodingType::None);
  2072. }
  2073. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2074. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2075. Request req;
  2076. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2077. Response res;
  2078. res.set_header("Content-Type", "text/plain");
  2079. auto ret = detail::encoding_type(req, res);
  2080. EXPECT_TRUE(ret == detail::EncodingType::None);
  2081. }
  2082. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2083. Request req;
  2084. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2085. Response res;
  2086. res.set_header("Content-Type", "text/plain");
  2087. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2088. }
  2089. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2090. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2091. Request req;
  2092. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2093. Response res;
  2094. res.set_header("Content-Type", "text/plain");
  2095. auto ret = detail::encoding_type(req, res);
  2096. EXPECT_TRUE(ret == detail::EncodingType::None);
  2097. }
  2098. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2099. // RFC 7231: Accept-Encoding values are case-insensitive
  2100. Request req;
  2101. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2102. Response res;
  2103. res.set_header("Content-Type", "text/plain");
  2104. auto ret = detail::encoding_type(req, res);
  2105. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2106. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2107. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2108. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2109. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2110. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2111. #else
  2112. EXPECT_TRUE(ret == detail::EncodingType::None);
  2113. #endif
  2114. }
  2115. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2116. // q value should determine priority, not hardcoded order
  2117. Request req;
  2118. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2119. Response res;
  2120. res.set_header("Content-Type", "text/plain");
  2121. auto ret = detail::encoding_type(req, res);
  2122. // gzip has highest q=1.0, so it should be selected even though
  2123. // br and zstd are also supported
  2124. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2125. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2126. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2127. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2128. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2129. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2130. #else
  2131. EXPECT_TRUE(ret == detail::EncodingType::None);
  2132. #endif
  2133. }
  2134. TEST(BufferStreamTest, read) {
  2135. detail::BufferStream strm1;
  2136. Stream &strm = strm1;
  2137. EXPECT_EQ(5, strm.write("hello"));
  2138. char buf[512];
  2139. EXPECT_EQ(2, strm.read(buf, 2));
  2140. EXPECT_EQ('h', buf[0]);
  2141. EXPECT_EQ('e', buf[1]);
  2142. EXPECT_EQ(2, strm.read(buf, 2));
  2143. EXPECT_EQ('l', buf[0]);
  2144. EXPECT_EQ('l', buf[1]);
  2145. EXPECT_EQ(1, strm.read(buf, 1));
  2146. EXPECT_EQ('o', buf[0]);
  2147. EXPECT_EQ(0, strm.read(buf, 1));
  2148. }
  2149. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2150. auto host = "www.httpwatch.com";
  2151. auto ip = hosted_at(host);
  2152. EXPECT_EQ("23.96.13.243", ip);
  2153. std::vector<std::string> addrs;
  2154. hosted_at(host, addrs);
  2155. EXPECT_EQ(1u, addrs.size());
  2156. }
  2157. #if 0 // It depends on each test environment...
  2158. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2159. auto host = "www.youtube.com";
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(20u, addrs.size());
  2163. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2164. EXPECT_TRUE(it != addrs.end());
  2165. }
  2166. #endif
  2167. class ChunkedEncodingTest : public ::testing::Test {
  2168. protected:
  2169. ChunkedEncodingTest()
  2170. : cli_(HOST, PORT)
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. ,
  2173. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2174. #endif
  2175. {
  2176. cli_.set_connection_timeout(2);
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. cli_.enable_server_certificate_verification(false);
  2179. #endif
  2180. }
  2181. virtual void SetUp() {
  2182. read_file("./image.jpg", image_data_);
  2183. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2184. res.set_content("Hello World!", "text/plain");
  2185. });
  2186. svr_.Get(
  2187. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2188. res.set_chunked_content_provider(
  2189. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2190. size_t remaining = image_data_.size() - offset;
  2191. if (remaining == 0) {
  2192. sink.done();
  2193. } else {
  2194. constexpr size_t CHUNK_SIZE = 1024;
  2195. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2196. sink.write(&image_data_[offset], send_size);
  2197. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2198. }
  2199. return true;
  2200. });
  2201. });
  2202. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2203. svr_.wait_until_ready();
  2204. }
  2205. virtual void TearDown() {
  2206. svr_.stop();
  2207. if (!request_threads_.empty()) {
  2208. std::this_thread::sleep_for(std::chrono::seconds(1));
  2209. for (auto &t : request_threads_) {
  2210. t.join();
  2211. }
  2212. }
  2213. t_.join();
  2214. }
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. SSLClient cli_;
  2217. SSLServer svr_;
  2218. #else
  2219. Client cli_;
  2220. Server svr_;
  2221. #endif
  2222. thread t_;
  2223. std::vector<thread> request_threads_;
  2224. std::string image_data_;
  2225. };
  2226. TEST_F(ChunkedEncodingTest, NormalGet) {
  2227. auto res = cli_.Get("/chunked");
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. std::string out;
  2230. read_file("./image.jpg", out);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ(out, res->body);
  2233. }
  2234. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2235. std::string body;
  2236. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2237. body.append(data, data_length);
  2238. return true;
  2239. });
  2240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2241. std::string out;
  2242. read_file("./image.jpg", out);
  2243. EXPECT_EQ(StatusCode::OK_200, res->status);
  2244. EXPECT_EQ(out, body);
  2245. }
  2246. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2247. std::string body;
  2248. auto res = cli_.Get(
  2249. "/chunked",
  2250. [&](const Response &response) {
  2251. EXPECT_EQ(StatusCode::OK_200, response.status);
  2252. return true;
  2253. },
  2254. [&](const char *data, size_t data_length) {
  2255. body.append(data, data_length);
  2256. return true;
  2257. });
  2258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2259. std::string out;
  2260. read_file("./image.jpg", out);
  2261. EXPECT_EQ(StatusCode::OK_200, res->status);
  2262. EXPECT_EQ(out, body);
  2263. }
  2264. TEST(RangeTest, FromHTTPBin_Online) {
  2265. auto host = "httpbingo.org";
  2266. auto path = std::string{"/range/32"};
  2267. #ifdef CPPHTTPLIB_SSL_ENABLED
  2268. auto port = 443;
  2269. SSLClient cli(host, port);
  2270. #else
  2271. auto port = 80;
  2272. Client cli(host, port);
  2273. #endif
  2274. cli.set_connection_timeout(5);
  2275. {
  2276. auto res = cli.Get(path);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2279. EXPECT_EQ(StatusCode::OK_200, res->status);
  2280. }
  2281. {
  2282. Headers headers = {make_range_header({{1, -1}})};
  2283. auto res = cli.Get(path, headers);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, 10}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijk", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2296. // entire resource, while the original httpbin returned 200. Both are
  2297. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2298. {
  2299. Headers headers = {make_range_header({{0, 31}})};
  2300. auto res = cli.Get(path, headers);
  2301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2302. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2303. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2304. res->status == StatusCode::PartialContent_206);
  2305. }
  2306. {
  2307. Headers headers = {make_range_header({{0, -1}})};
  2308. auto res = cli.Get(path, headers);
  2309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2310. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2311. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2312. res->status == StatusCode::PartialContent_206);
  2313. }
  2314. // go-httpbin returns 206 with clamped range for over-range requests,
  2315. // while the original httpbin returned 416. Both behaviors are observed
  2316. // in real servers, so we only verify the request succeeds.
  2317. {
  2318. Headers headers = {make_range_header({{0, 32}})};
  2319. auto res = cli.Get(path, headers);
  2320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2321. }
  2322. }
  2323. TEST(RangeTest, IgnoredForPost) {
  2324. Server svr;
  2325. svr.Post("/", [](const Request &, Response &res) {
  2326. res.set_content("abcdefg", "text/plain");
  2327. });
  2328. auto port = svr.bind_to_any_port(HOST);
  2329. ASSERT_GT(port, 0);
  2330. thread t = thread([&] { svr.listen_after_bind(); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. t.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. Client cli(HOST, port);
  2338. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2339. auto res = cli.Post("/", Headers{{"Range", range}});
  2340. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2341. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2342. EXPECT_EQ("abcdefg", res->body) << range;
  2343. }
  2344. }
  2345. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2346. auto host = "unresolvableaddress.local";
  2347. auto path = std::string{"/"};
  2348. #ifdef CPPHTTPLIB_SSL_ENABLED
  2349. auto port = 443;
  2350. SSLClient cli(host, port);
  2351. #else
  2352. auto port = 80;
  2353. Client cli(host, port);
  2354. #endif
  2355. cli.set_connection_timeout(1);
  2356. {
  2357. auto res = cli.Get(path);
  2358. ASSERT_FALSE(res);
  2359. }
  2360. std::this_thread::sleep_for(std::chrono::seconds(8));
  2361. }
  2362. #if defined(__linux__) && defined(__GLIBC__) && \
  2363. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2364. // Forward declaration: in split builds split.py strips `inline` and moves the
  2365. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2366. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2367. // against the symbol in both header-only and split builds.
  2368. namespace httplib {
  2369. namespace detail {
  2370. int getaddrinfo_with_timeout(const char *node, const char *service,
  2371. const struct addrinfo *hints,
  2372. struct addrinfo **res, time_t timeout_sec);
  2373. } // namespace detail
  2374. } // namespace httplib
  2375. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2376. //
  2377. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2378. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2379. // gai_suspend() call hits the connection timeout the function calls
  2380. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2381. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2382. // still alive and still references the now-destroyed stack frame.
  2383. //
  2384. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2385. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2386. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2387. // and runs them in a container.
  2388. namespace {
  2389. bool should_run_issue_2431_tests() {
  2390. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2391. return v && *v && std::string(v) != "0";
  2392. }
  2393. std::string unique_unresolvable_host(int n) {
  2394. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2395. // glibc still asks the configured nameserver — which is exactly the path
  2396. // we want to exercise. A unique label per call avoids the resolver cache.
  2397. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2398. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2399. std::to_string(n) + ".invalid";
  2400. }
  2401. } // namespace
  2402. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2403. if (!should_run_issue_2431_tests()) {
  2404. GTEST_SKIP()
  2405. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2406. }
  2407. for (int i = 0; i < 8; ++i) {
  2408. struct addrinfo hints;
  2409. memset(&hints, 0, sizeof(hints));
  2410. hints.ai_family = AF_UNSPEC;
  2411. hints.ai_socktype = SOCK_STREAM;
  2412. auto host = unique_unresolvable_host(i);
  2413. struct addrinfo *result = nullptr;
  2414. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2415. &result, /*timeout_sec=*/1);
  2416. if (rc == 0 && result) { freeaddrinfo(result); }
  2417. }
  2418. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2419. // stack region they still believe holds their gaicb.
  2420. std::this_thread::sleep_for(std::chrono::seconds(3));
  2421. }
  2422. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2423. if (!should_run_issue_2431_tests()) {
  2424. GTEST_SKIP()
  2425. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2426. }
  2427. std::atomic<bool> stop{false};
  2428. std::vector<std::thread> threads;
  2429. for (int t = 0; t < 8; ++t) {
  2430. threads.emplace_back([t, &stop] {
  2431. int i = 0;
  2432. while (!stop.load(std::memory_order_relaxed)) {
  2433. struct addrinfo hints;
  2434. memset(&hints, 0, sizeof(hints));
  2435. hints.ai_family = AF_UNSPEC;
  2436. hints.ai_socktype = SOCK_STREAM;
  2437. auto host = unique_unresolvable_host(t * 100000 + i++);
  2438. struct addrinfo *result = nullptr;
  2439. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2440. &result, /*timeout_sec=*/1);
  2441. if (rc == 0 && result) { freeaddrinfo(result); }
  2442. }
  2443. });
  2444. }
  2445. std::this_thread::sleep_for(std::chrono::seconds(8));
  2446. stop.store(true, std::memory_order_relaxed);
  2447. for (auto &th : threads) {
  2448. th.join();
  2449. }
  2450. std::this_thread::sleep_for(std::chrono::seconds(3));
  2451. }
  2452. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2453. if (!should_run_issue_2431_tests()) {
  2454. GTEST_SKIP()
  2455. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2456. }
  2457. std::atomic<bool> stop{false};
  2458. std::vector<std::thread> threads;
  2459. for (int t = 0; t < 8; ++t) {
  2460. threads.emplace_back([t, &stop] {
  2461. int i = 0;
  2462. while (!stop.load(std::memory_order_relaxed)) {
  2463. auto host = unique_unresolvable_host(t * 100000 + i++);
  2464. Client cli(host, 80);
  2465. cli.set_connection_timeout(1, 0);
  2466. cli.set_read_timeout(1, 0);
  2467. cli.set_write_timeout(1, 0);
  2468. (void)cli.Get("/");
  2469. }
  2470. });
  2471. }
  2472. std::this_thread::sleep_for(std::chrono::seconds(8));
  2473. stop.store(true, std::memory_order_relaxed);
  2474. for (auto &th : threads) {
  2475. th.join();
  2476. }
  2477. std::this_thread::sleep_for(std::chrono::seconds(3));
  2478. }
  2479. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2480. TEST(ConnectionErrorTest, InvalidHost) {
  2481. auto host = "-abcde.com";
  2482. #ifdef CPPHTTPLIB_SSL_ENABLED
  2483. auto port = 443;
  2484. SSLClient cli(host, port);
  2485. #else
  2486. auto port = 80;
  2487. Client cli(host, port);
  2488. #endif
  2489. cli.set_connection_timeout(std::chrono::seconds(2));
  2490. auto res = cli.Get("/");
  2491. ASSERT_TRUE(!res);
  2492. EXPECT_EQ(Error::Connection, res.error());
  2493. }
  2494. TEST(ConnectionErrorTest, InvalidHost2) {
  2495. auto host = "httpcan.org/";
  2496. #ifdef CPPHTTPLIB_SSL_ENABLED
  2497. SSLClient cli(host);
  2498. #else
  2499. Client cli(host);
  2500. #endif
  2501. cli.set_connection_timeout(std::chrono::seconds(2));
  2502. auto res = cli.Get("/");
  2503. ASSERT_TRUE(!res);
  2504. EXPECT_EQ(Error::Connection, res.error());
  2505. }
  2506. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2507. auto host = "httpcan.org/";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(host);
  2510. #else
  2511. Client cli(host);
  2512. #endif
  2513. cli.set_connection_timeout(std::chrono::seconds(2));
  2514. auto res = cli.Get("/");
  2515. ASSERT_TRUE(!res);
  2516. stringstream s;
  2517. s << "error code: " << res.error();
  2518. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2519. }
  2520. TEST(ConnectionErrorTest, InvalidPort) {
  2521. auto host = "localhost";
  2522. auto port = 44380;
  2523. #ifdef CPPHTTPLIB_SSL_ENABLED
  2524. SSLClient cli(host, port);
  2525. #else
  2526. Client cli(host, port);
  2527. #endif
  2528. cli.set_connection_timeout(std::chrono::seconds(2));
  2529. auto res = cli.Get("/");
  2530. ASSERT_TRUE(!res);
  2531. EXPECT_TRUE(Error::Connection == res.error() ||
  2532. Error::ConnectionTimeout == res.error());
  2533. }
  2534. TEST(ConnectionErrorTest, Timeout_Online) {
  2535. auto host = "google.com";
  2536. #ifdef CPPHTTPLIB_SSL_ENABLED
  2537. auto port = 44380;
  2538. SSLClient cli(host, port);
  2539. #else
  2540. auto port = 8080;
  2541. Client cli(host, port);
  2542. #endif
  2543. cli.set_connection_timeout(std::chrono::seconds(2));
  2544. // only probe one address type so that the error reason
  2545. // correlates to the timed-out IPv4, not the unsupported
  2546. // IPv6 connection attempt
  2547. cli.set_address_family(AF_INET);
  2548. auto res = cli.Get("/");
  2549. ASSERT_TRUE(!res);
  2550. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2551. }
  2552. TEST(CancelTest, NoCancel_Online) {
  2553. auto host = "httpbingo.org";
  2554. auto path = std::string{"/range/32"};
  2555. #ifdef CPPHTTPLIB_SSL_ENABLED
  2556. auto port = 443;
  2557. SSLClient cli(host, port);
  2558. #else
  2559. auto port = 80;
  2560. Client cli(host, port);
  2561. #endif
  2562. cli.set_connection_timeout(std::chrono::seconds(5));
  2563. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2565. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2566. EXPECT_EQ(StatusCode::OK_200, res->status);
  2567. }
  2568. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2569. // Use /bytes with a large payload so that the DownloadProgress callback
  2570. // (which only fires for Content-Length responses) is invoked before the
  2571. // entire body is received, giving cancellation a chance to fire.
  2572. auto host = "httpbingo.org";
  2573. auto path = std::string{"/bytes/524288"};
  2574. #ifdef CPPHTTPLIB_SSL_ENABLED
  2575. auto port = 443;
  2576. SSLClient cli(host, port);
  2577. #else
  2578. auto port = 80;
  2579. Client cli(host, port);
  2580. #endif
  2581. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2582. cli.set_connection_timeout(std::chrono::seconds(5));
  2583. ASSERT_TRUE(!res);
  2584. EXPECT_EQ(Error::Canceled, res.error());
  2585. }
  2586. TEST(CancelTest, WithCancelLargePayload_Online) {
  2587. auto host = "httpbingo.org";
  2588. auto path = std::string{"/bytes/524288"};
  2589. #ifdef CPPHTTPLIB_SSL_ENABLED
  2590. auto port = 443;
  2591. SSLClient cli(host, port);
  2592. #else
  2593. auto port = 80;
  2594. Client cli(host, port);
  2595. #endif
  2596. cli.set_connection_timeout(std::chrono::seconds(5));
  2597. uint32_t count = 0;
  2598. auto res =
  2599. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2600. ASSERT_TRUE(!res);
  2601. EXPECT_EQ(Error::Canceled, res.error());
  2602. }
  2603. TEST(CancelTest, NoCancelPost) {
  2604. Server svr;
  2605. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2606. res.set_content("Hello World!", "text/plain");
  2607. });
  2608. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2609. auto se = detail::scope_exit([&] {
  2610. svr.stop();
  2611. thread.join();
  2612. ASSERT_FALSE(svr.is_running());
  2613. });
  2614. svr.wait_until_ready();
  2615. Client cli(HOST, PORT);
  2616. cli.set_connection_timeout(std::chrono::seconds(5));
  2617. auto res =
  2618. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2619. "application/json", [](uint64_t, uint64_t) { return true; });
  2620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2621. EXPECT_EQ("Hello World!", res->body);
  2622. EXPECT_EQ(StatusCode::OK_200, res->status);
  2623. }
  2624. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2625. Server svr;
  2626. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2627. res.set_content("Hello World!", "text/plain");
  2628. });
  2629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2630. auto se = detail::scope_exit([&] {
  2631. svr.stop();
  2632. thread.join();
  2633. ASSERT_FALSE(svr.is_running());
  2634. });
  2635. svr.wait_until_ready();
  2636. Client cli(HOST, PORT);
  2637. cli.set_connection_timeout(std::chrono::seconds(5));
  2638. auto res =
  2639. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2640. "application/json", [](uint64_t, uint64_t) { return false; });
  2641. ASSERT_TRUE(!res);
  2642. EXPECT_EQ(Error::Canceled, res.error());
  2643. }
  2644. TEST(CancelTest, WithCancelLargePayloadPost) {
  2645. Server svr;
  2646. svr.set_payload_max_length(200 * 1024 * 1024);
  2647. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2648. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  2659. cli.set_connection_timeout(std::chrono::seconds(5));
  2660. auto res =
  2661. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2662. "application/json", [](uint64_t, uint64_t) { return false; });
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_EQ(Error::Canceled, res.error());
  2665. }
  2666. TEST(CancelTest, NoCancelPut) {
  2667. Server svr;
  2668. svr.Put("/", [&](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.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2682. "application/json", [](uint64_t, uint64_t) { return true; });
  2683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2684. EXPECT_EQ("Hello World!", res->body);
  2685. EXPECT_EQ(StatusCode::OK_200, res->status);
  2686. }
  2687. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2688. Server svr;
  2689. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2690. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  2701. auto res =
  2702. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2703. "application/json", [](uint64_t, uint64_t) { return false; });
  2704. ASSERT_TRUE(!res);
  2705. EXPECT_EQ(Error::Canceled, res.error());
  2706. }
  2707. TEST(CancelTest, WithCancelLargePayloadPut) {
  2708. Server svr;
  2709. svr.set_payload_max_length(200 * 1024 * 1024);
  2710. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2711. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  2722. cli.set_connection_timeout(std::chrono::seconds(5));
  2723. auto res =
  2724. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2725. "application/json", [](uint64_t, uint64_t) { return false; });
  2726. ASSERT_TRUE(!res);
  2727. EXPECT_EQ(Error::Canceled, res.error());
  2728. }
  2729. TEST(CancelTest, NoCancelPatch) {
  2730. Server svr;
  2731. svr.Patch("/", [&](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.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2745. "application/json", [](uint64_t, uint64_t) { return true; });
  2746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2747. EXPECT_EQ("Hello World!", res->body);
  2748. EXPECT_EQ(StatusCode::OK_200, res->status);
  2749. }
  2750. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2751. Server svr;
  2752. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2753. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  2764. auto res =
  2765. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2766. "application/json", [](uint64_t, uint64_t) { return false; });
  2767. ASSERT_TRUE(!res);
  2768. EXPECT_EQ(Error::Canceled, res.error());
  2769. }
  2770. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2771. Server svr;
  2772. svr.set_payload_max_length(200 * 1024 * 1024);
  2773. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2774. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  2785. cli.set_connection_timeout(std::chrono::seconds(5));
  2786. auto res =
  2787. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2788. "application/json", [](uint64_t, uint64_t) { return false; });
  2789. ASSERT_TRUE(!res);
  2790. EXPECT_EQ(Error::Canceled, res.error());
  2791. }
  2792. TEST(CancelTest, NoCancelDelete) {
  2793. Server svr;
  2794. svr.Delete("/", [&](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.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2808. "application/json", [](uint64_t, uint64_t) { return true; });
  2809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2810. EXPECT_EQ("Hello World!", res->body);
  2811. EXPECT_EQ(StatusCode::OK_200, res->status);
  2812. }
  2813. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2814. Server svr;
  2815. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2816. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  2827. auto res =
  2828. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2829. "application/json", [](uint64_t, uint64_t) { return false; });
  2830. ASSERT_TRUE(!res);
  2831. EXPECT_EQ(Error::Canceled, res.error());
  2832. }
  2833. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2834. Server svr;
  2835. svr.set_payload_max_length(200 * 1024 * 1024);
  2836. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2837. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  2848. cli.set_connection_timeout(std::chrono::seconds(5));
  2849. auto res =
  2850. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2851. "application/json", [](uint64_t, uint64_t) { return false; });
  2852. ASSERT_TRUE(!res);
  2853. EXPECT_EQ(Error::Canceled, res.error());
  2854. }
  2855. static std::string remove_whitespace(const std::string &input) {
  2856. std::string output;
  2857. output.reserve(input.size());
  2858. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2859. [](unsigned char c) { return !std::isspace(c); });
  2860. return output;
  2861. }
  2862. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2863. auto host = "httpbingo.org";
  2864. auto path = std::string{"/basic-auth/hello/world"};
  2865. #ifdef CPPHTTPLIB_SSL_ENABLED
  2866. auto port = 443;
  2867. SSLClient cli(host, port);
  2868. #else
  2869. auto port = 80;
  2870. Client cli(host, port);
  2871. #endif
  2872. {
  2873. auto res = cli.Get(path);
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2876. }
  2877. {
  2878. auto res = cli.Get(
  2879. path, Headers{make_basic_authentication_header("hello", "world")});
  2880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2881. auto body = remove_whitespace(res->body);
  2882. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2883. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2884. EXPECT_EQ(StatusCode::OK_200, res->status);
  2885. }
  2886. {
  2887. cli.set_basic_auth("hello", "world");
  2888. auto res = cli.Get(path);
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. auto body = remove_whitespace(res->body);
  2891. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2892. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2893. EXPECT_EQ(StatusCode::OK_200, res->status);
  2894. }
  2895. {
  2896. cli.set_basic_auth("hello", "bad");
  2897. auto res = cli.Get(path);
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2900. }
  2901. {
  2902. cli.set_basic_auth("bad", "world");
  2903. auto res = cli.Get(path);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2906. }
  2907. }
  2908. #ifdef CPPHTTPLIB_SSL_ENABLED
  2909. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2910. auto host = "httpbingo.org";
  2911. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2912. auto paths = std::vector<std::string>{
  2913. "/digest-auth/auth/hello/world/MD5",
  2914. "/digest-auth/auth/hello/world/SHA-256",
  2915. };
  2916. auto port = 443;
  2917. SSLClient cli(host, port);
  2918. {
  2919. auto res = cli.Get(unauth_path);
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2922. }
  2923. {
  2924. cli.set_digest_auth("hello", "world");
  2925. for (const auto &path : paths) {
  2926. auto res = cli.Get(path.c_str());
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. auto body = remove_whitespace(res->body);
  2929. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2930. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2931. EXPECT_EQ(StatusCode::OK_200, res->status);
  2932. }
  2933. cli.set_digest_auth("hello", "bad");
  2934. for (const auto &path : paths) {
  2935. auto res = cli.Get(path.c_str());
  2936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2937. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2938. }
  2939. }
  2940. }
  2941. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2942. // comma-separated list of challenges, and each challenge may itself carry a
  2943. // comma-separated auth-param list, so a server can legally offer Basic
  2944. // before Digest, either as two field lines or packed into one. Runs one 401
  2945. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2946. // value() joins them in receipt order) and checks that the retry carries a
  2947. // well-formed Digest Authorization header naming expected_realm.
  2948. static void
  2949. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2950. const std::string &expected_realm) {
  2951. std::atomic<int> hits{0};
  2952. Server svr;
  2953. svr.Get("/x", [&](const Request &req, Response &res) {
  2954. if (++hits == 1) {
  2955. res.status = StatusCode::Unauthorized_401;
  2956. for (const auto &challenge : challenges) {
  2957. res.set_header("WWW-Authenticate", challenge);
  2958. }
  2959. } else {
  2960. auto authorization = req.get_header_value("Authorization");
  2961. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2962. EXPECT_NE(std::string::npos,
  2963. authorization.find("realm=\"" + expected_realm + "\""));
  2964. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2965. res.set_content("ok", "text/plain");
  2966. }
  2967. });
  2968. auto port = svr.bind_to_any_port(HOST);
  2969. std::thread t([&]() { svr.listen_after_bind(); });
  2970. auto se = detail::scope_exit([&] {
  2971. svr.stop();
  2972. t.join();
  2973. });
  2974. svr.wait_until_ready();
  2975. Client cli(HOST, port);
  2976. cli.set_digest_auth("hello", "world");
  2977. auto res = cli.Get("/x");
  2978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2979. EXPECT_EQ(2, hits.load());
  2980. }
  2981. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2982. static const char *kDigestChallenge =
  2983. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2984. "algorithm=MD5";
  2985. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2986. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2987. "testrealm");
  2988. }
  2989. // Same challenge list with the schemes in the opposite order, to make sure
  2990. // the fix above didn't just special-case "Basic first".
  2991. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2992. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2993. "testrealm");
  2994. }
  2995. // A comma inside a quoted auth-param value must not be mistaken for the
  2996. // separator between two challenges (or two auth-params).
  2997. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2998. run_digest_challenge_list_test(
  2999. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3000. "algorithm=MD5"},
  3001. "test,realm");
  3002. }
  3003. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3004. // the params and leaves out the fragment.
  3005. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3006. Server svr;
  3007. std::string uri, target;
  3008. svr.Get("/a b", [&](const Request &req, Response &res) {
  3009. auto auth = req.get_header_value("Authorization");
  3010. if (auth.empty()) {
  3011. res.status = StatusCode::Unauthorized_401;
  3012. res.set_header("WWW-Authenticate",
  3013. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3014. return;
  3015. }
  3016. auto b = auth.find("uri=\"") + 5;
  3017. uri = auth.substr(b, auth.find('"', b) - b);
  3018. target = req.target;
  3019. });
  3020. auto port = svr.bind_to_any_port(HOST);
  3021. std::thread t([&]() { svr.listen_after_bind(); });
  3022. auto se = detail::scope_exit([&] {
  3023. svr.stop();
  3024. t.join();
  3025. });
  3026. svr.wait_until_ready();
  3027. Client cli(HOST, port);
  3028. cli.set_digest_auth("hello", "world");
  3029. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3031. EXPECT_EQ("/a%20b?x=1", target);
  3032. EXPECT_EQ(target, uri);
  3033. }
  3034. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3035. // make_digest_authentication_header() dereferences both unconditionally, so
  3036. // a server sending a challenge missing either one must not be treated as
  3037. // usable -- doing so used to crash the client with std::out_of_range.
  3038. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3039. Server svr;
  3040. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3041. res.status = StatusCode::Unauthorized_401;
  3042. res.set_header("WWW-Authenticate", challenge);
  3043. });
  3044. auto port = svr.bind_to_any_port(HOST);
  3045. std::thread t([&]() { svr.listen_after_bind(); });
  3046. auto se = detail::scope_exit([&] {
  3047. svr.stop();
  3048. t.join();
  3049. });
  3050. svr.wait_until_ready();
  3051. Client cli(HOST, port);
  3052. cli.set_digest_auth("hello", "world");
  3053. auto res = cli.Get("/x");
  3054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3055. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3056. }
  3057. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3058. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3059. }
  3060. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3061. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3062. }
  3063. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3064. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3065. }
  3066. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3067. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3068. // when storing the values, so the header builder has to re-escape them (and
  3069. // keep algorithm a bare token); otherwise the value breaks out of its
  3070. // quoted-string and injects extra auth-params into the client's Authorization.
  3071. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3072. std::atomic<int> hits{0};
  3073. std::string authorization;
  3074. Server svr;
  3075. svr.Get("/x", [&](const Request &req, Response &res) {
  3076. if (++hits == 1) {
  3077. res.status = StatusCode::Unauthorized_401;
  3078. // On the wire the quotes embedded in the values are backslash-escaped.
  3079. res.set_header("WWW-Authenticate",
  3080. "Digest realm=\"testrealm\", "
  3081. "nonce=\"n\\\"; injected=\\\"x\", "
  3082. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3083. } else {
  3084. authorization = req.get_header_value("Authorization");
  3085. res.set_content("ok", "text/plain");
  3086. }
  3087. });
  3088. auto port = svr.bind_to_any_port(HOST);
  3089. std::thread t([&]() { svr.listen_after_bind(); });
  3090. auto se = detail::scope_exit([&] {
  3091. svr.stop();
  3092. t.join();
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(HOST, port);
  3096. cli.set_digest_auth("hello", "world");
  3097. auto res = cli.Get("/x");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(2, hits.load());
  3100. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3101. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3102. // inside its quoted-string rather than starting an "injected" auth-param.
  3103. EXPECT_NE(std::string::npos,
  3104. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3105. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3106. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3107. }
  3108. #endif
  3109. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3110. auto host = "google.com";
  3111. auto another_host = "example.com";
  3112. auto wrong_ip = "0.0.0.0";
  3113. #ifdef CPPHTTPLIB_SSL_ENABLED
  3114. SSLClient cli(host);
  3115. #else
  3116. Client cli(host);
  3117. #endif
  3118. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3119. auto res = cli.Get("/");
  3120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3121. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3122. }
  3123. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3124. auto host = "google.com";
  3125. auto wrong_ip = "0.0.0.0";
  3126. #ifdef CPPHTTPLIB_SSL_ENABLED
  3127. SSLClient cli(host);
  3128. #else
  3129. Client cli(host);
  3130. #endif
  3131. cli.set_hostname_addr_map({{host, wrong_ip}});
  3132. auto res = cli.Get("/");
  3133. ASSERT_TRUE(!res);
  3134. EXPECT_EQ(Error::Connection, res.error());
  3135. }
  3136. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3137. // A mapped value that is not an IP literal must be resolved. "localhost"
  3138. // resolves from the hosts file, so this test needs no external DNS.
  3139. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3140. auto host = "target.invalid";
  3141. Server svr;
  3142. std::string received_host;
  3143. svr.Get("/hi", [&](const Request &req, Response &res) {
  3144. received_host = req.get_header_value("Host");
  3145. res.set_content("Hello World!", "text/plain");
  3146. });
  3147. auto port = svr.bind_to_any_port(HOST);
  3148. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3149. auto se = detail::scope_exit([&] {
  3150. svr.stop();
  3151. thread.join();
  3152. ASSERT_FALSE(svr.is_running());
  3153. });
  3154. svr.wait_until_ready();
  3155. Client cli(host, port);
  3156. cli.set_hostname_addr_map({{host, HOST}});
  3157. auto res = cli.Get("/hi");
  3158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3159. EXPECT_EQ(StatusCode::OK_200, res->status);
  3160. // The mapping only redirects the connection; the identity stays host_.
  3161. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3162. }
  3163. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3164. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3165. auto host = "target.invalid";
  3166. Server svr;
  3167. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3168. res.set_content("Hello World!", "text/plain");
  3169. });
  3170. auto port = svr.bind_to_any_port("127.0.0.1");
  3171. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3172. auto se = detail::scope_exit([&] {
  3173. svr.stop();
  3174. thread.join();
  3175. ASSERT_FALSE(svr.is_running());
  3176. });
  3177. svr.wait_until_ready();
  3178. Client cli(host, port);
  3179. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3180. auto res = cli.Get("/hi");
  3181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3182. EXPECT_EQ(StatusCode::OK_200, res->status);
  3183. }
  3184. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3185. // An empty mapped value must leave host_ as the connection target. Without
  3186. // that guard the empty value would become the host argument, getaddrinfo
  3187. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3188. // loopback - silently connecting somewhere the caller never asked for.
  3189. // The server listens on loopback, so such a fallback would succeed and is
  3190. // therefore observable as a failure of this test.
  3191. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3192. Server svr;
  3193. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3194. res.set_content("Hello World!", "text/plain");
  3195. });
  3196. auto port = svr.bind_to_any_port(HOST);
  3197. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3198. auto se = detail::scope_exit([&] {
  3199. svr.stop();
  3200. thread.join();
  3201. ASSERT_FALSE(svr.is_running());
  3202. });
  3203. svr.wait_until_ready();
  3204. Client cli(blackhole, port);
  3205. cli.set_hostname_addr_map({{blackhole, ""}});
  3206. cli.set_connection_timeout(1);
  3207. auto res = cli.Get("/hi");
  3208. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3209. }
  3210. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3211. auto host = "httpbingo.org";
  3212. auto path = std::string{"/absolute-redirect/3"};
  3213. #ifdef CPPHTTPLIB_SSL_ENABLED
  3214. SSLClient cli(host);
  3215. #else
  3216. Client cli(host);
  3217. #endif
  3218. cli.set_follow_location(true);
  3219. auto res = cli.Get(path);
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST(RedirectTest, Redirect_Online) {
  3224. auto host = "httpbingo.org";
  3225. auto path = std::string{"/redirect/3"};
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. SSLClient cli(host);
  3228. #else
  3229. Client cli(host);
  3230. #endif
  3231. cli.set_follow_location(true);
  3232. auto res = cli.Get(path);
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. }
  3236. TEST(RelativeRedirectTest, Redirect_Online) {
  3237. auto host = "httpbingo.org";
  3238. auto path = std::string{"/relative-redirect/3"};
  3239. #ifdef CPPHTTPLIB_SSL_ENABLED
  3240. SSLClient cli(host);
  3241. #else
  3242. Client cli(host);
  3243. #endif
  3244. cli.set_follow_location(true);
  3245. auto res = cli.Get(path);
  3246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3247. EXPECT_EQ(StatusCode::OK_200, res->status);
  3248. }
  3249. TEST(TooManyRedirectTest, Redirect_Online) {
  3250. auto host = "httpbingo.org";
  3251. auto path = std::string{"/redirect/21"};
  3252. #ifdef CPPHTTPLIB_SSL_ENABLED
  3253. SSLClient cli(host);
  3254. #else
  3255. Client cli(host);
  3256. #endif
  3257. cli.set_follow_location(true);
  3258. auto res = cli.Get(path);
  3259. ASSERT_TRUE(!res);
  3260. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3261. }
  3262. #ifdef CPPHTTPLIB_SSL_ENABLED
  3263. TEST(YahooRedirectTest, Redirect_Online) {
  3264. Client cli("yahoo.com");
  3265. auto res = cli.Get("/");
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3268. cli.set_follow_location(true);
  3269. res = cli.Get("/");
  3270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3271. EXPECT_EQ(StatusCode::OK_200, res->status);
  3272. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3273. }
  3274. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3275. #define REDIR_HOST "httpbingo.org"
  3276. #define REDIR_PATH "/redirect-to"
  3277. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3278. SSLClient cli(REDIR_HOST);
  3279. cli.set_follow_location(true);
  3280. auto res =
  3281. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. }
  3285. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3286. SSLClient cli(REDIR_HOST);
  3287. cli.set_follow_location(true);
  3288. Params params;
  3289. params.emplace("url", "http://example.com");
  3290. params.emplace("status_code", "302");
  3291. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. }
  3295. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3296. SSLClient cli(REDIR_HOST);
  3297. cli.set_follow_location(true);
  3298. Params params;
  3299. params.emplace("url", "http://example.com");
  3300. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3302. EXPECT_EQ(StatusCode::OK_200, res->status);
  3303. }
  3304. TEST(UrlWithSpace, Redirect_Online) {
  3305. SSLClient cli("edge.forgecdn.net");
  3306. cli.set_follow_location(true);
  3307. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3309. EXPECT_EQ(StatusCode::OK_200, res->status);
  3310. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3311. }
  3312. #endif
  3313. #if !defined(_WIN32) && !defined(_WIN64)
  3314. TEST(ReceiveSignals, Signal) {
  3315. auto setupSignalHandlers = []() {
  3316. struct sigaction act;
  3317. sigemptyset(&act.sa_mask);
  3318. act.sa_flags = SA_SIGINFO;
  3319. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3320. switch (sig) {
  3321. case SIGINT:
  3322. default: break;
  3323. }
  3324. };
  3325. ::sigaction(SIGINT, &act, nullptr);
  3326. };
  3327. Server svr;
  3328. int port = 0;
  3329. auto thread = std::thread([&]() {
  3330. setupSignalHandlers();
  3331. port = svr.bind_to_any_port(HOST);
  3332. svr.listen_after_bind();
  3333. });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. thread.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. ASSERT_TRUE(svr.is_running());
  3341. pthread_kill(thread.native_handle(), SIGINT);
  3342. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3343. ASSERT_TRUE(svr.is_running());
  3344. }
  3345. #endif
  3346. TEST(RedirectToDifferentPort, Redirect) {
  3347. Server svr1;
  3348. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3349. res.set_content("Hello World!", "text/plain");
  3350. });
  3351. int svr1_port = 0;
  3352. auto thread1 = std::thread([&]() {
  3353. svr1_port = svr1.bind_to_any_port(HOST);
  3354. svr1.listen_after_bind();
  3355. });
  3356. Server svr2;
  3357. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3358. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3359. });
  3360. int svr2_port = 0;
  3361. auto thread2 = std::thread([&]() {
  3362. svr2_port = svr2.bind_to_any_port(HOST);
  3363. svr2.listen_after_bind();
  3364. });
  3365. auto se = detail::scope_exit([&] {
  3366. svr2.stop();
  3367. thread2.join();
  3368. svr1.stop();
  3369. thread1.join();
  3370. ASSERT_FALSE(svr2.is_running());
  3371. ASSERT_FALSE(svr1.is_running());
  3372. });
  3373. svr1.wait_until_ready();
  3374. svr2.wait_until_ready();
  3375. Client cli("localhost", svr2_port);
  3376. cli.set_follow_location(true);
  3377. auto res = cli.Get("/2");
  3378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3379. EXPECT_EQ(StatusCode::OK_200, res->status);
  3380. EXPECT_EQ("Hello World!", res->body);
  3381. }
  3382. // GET /redir on one server redirects to /target on another port, so the
  3383. // client follows it with a new client.
  3384. static Result
  3385. GetThroughRedirectToDifferentPort(Server::Handler target,
  3386. const std::function<void(Client &)> &setup,
  3387. const Headers &headers = Headers()) {
  3388. Server target_svr;
  3389. target_svr.Get("/target", target);
  3390. int target_port = 0;
  3391. auto target_thread = std::thread([&]() {
  3392. target_port = target_svr.bind_to_any_port(HOST);
  3393. target_svr.listen_after_bind();
  3394. });
  3395. Server origin_svr;
  3396. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3397. res.set_redirect(
  3398. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3399. });
  3400. int origin_port = 0;
  3401. auto origin_thread = std::thread([&]() {
  3402. origin_port = origin_svr.bind_to_any_port(HOST);
  3403. origin_svr.listen_after_bind();
  3404. });
  3405. auto se = detail::scope_exit([&] {
  3406. origin_svr.stop();
  3407. origin_thread.join();
  3408. target_svr.stop();
  3409. target_thread.join();
  3410. });
  3411. target_svr.wait_until_ready();
  3412. origin_svr.wait_until_ready();
  3413. Client cli("localhost", origin_port);
  3414. cli.set_follow_location(true);
  3415. setup(cli);
  3416. return cli.Get("/redir", headers);
  3417. }
  3418. static void
  3419. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3420. std::string captured_authorization;
  3421. auto result = GetThroughRedirectToDifferentPort(
  3422. [&](const Request &req, Response &res) {
  3423. captured_authorization = req.get_header_value("Authorization");
  3424. res.set_content("OK", "text/plain");
  3425. },
  3426. set_auth);
  3427. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3428. EXPECT_EQ(StatusCode::OK_200, result->status);
  3429. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3430. EXPECT_TRUE(captured_authorization.empty());
  3431. }
  3432. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3433. TestDoNotForwardCredentialsOnRedirect(
  3434. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3435. }
  3436. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3437. TestDoNotForwardCredentialsOnRedirect(
  3438. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3439. }
  3440. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3441. std::string captured_cookie;
  3442. auto result = GetThroughRedirectToDifferentPort(
  3443. [&](const Request &req, Response &res) {
  3444. captured_cookie = req.get_header_value("Cookie");
  3445. res.set_content("OK", "text/plain");
  3446. },
  3447. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3448. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3449. EXPECT_EQ(StatusCode::OK_200, result->status);
  3450. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3451. EXPECT_TRUE(captured_cookie.empty());
  3452. }
  3453. TEST(RedirectToSamePort, ForwardCookie) {
  3454. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3455. // header so that ordinary session flows keep working.
  3456. Server svr;
  3457. std::string captured_cookie;
  3458. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3459. res.set_redirect("/target", 302);
  3460. });
  3461. svr.Get("/target", [&](const Request &req, Response &res) {
  3462. captured_cookie = req.get_header_value("Cookie");
  3463. res.set_content("OK", "text/plain");
  3464. });
  3465. auto port = svr.bind_to_any_port(HOST);
  3466. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3467. auto se = detail::scope_exit([&] {
  3468. svr.stop();
  3469. thread.join();
  3470. ASSERT_FALSE(svr.is_running());
  3471. });
  3472. svr.wait_until_ready();
  3473. Client cli(HOST, port);
  3474. cli.set_follow_location(true);
  3475. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3476. auto res = cli.Get("/redir", headers);
  3477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3478. EXPECT_EQ(StatusCode::OK_200, res->status);
  3479. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3480. }
  3481. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3482. std::string authorization;
  3483. std::string trace_id;
  3484. auto result = GetThroughRedirectToDifferentPort(
  3485. [&](const Request &req, Response &res) {
  3486. authorization = req.get_header_value("Authorization");
  3487. trace_id = req.get_header_value("X-Trace-Id");
  3488. res.set_content("OK", "text/plain");
  3489. },
  3490. [](Client &cli) {
  3491. cli.set_default_headers(
  3492. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3493. });
  3494. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3495. EXPECT_EQ(StatusCode::OK_200, result->status);
  3496. // Like a header given with the request, a default one goes along unless it
  3497. // carries credentials (RFC 9110 15.4).
  3498. EXPECT_TRUE(authorization.empty());
  3499. EXPECT_EQ("42", trace_id);
  3500. }
  3501. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3502. auto result = GetThroughRedirectToDifferentPort(
  3503. [](const Request &, Response &res) {
  3504. res.set_content(std::string(2048, 'x'), "text/plain");
  3505. },
  3506. [](Client &cli) { cli.set_payload_max_length(1024); });
  3507. EXPECT_FALSE(result);
  3508. }
  3509. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3510. auto result = GetThroughRedirectToDifferentPort(
  3511. [](const Request &req, Response &res) {
  3512. // Answer after a second, or once the client gives up.
  3513. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3514. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3515. }
  3516. res.set_content("late", "text/plain");
  3517. },
  3518. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3519. ASSERT_FALSE(result);
  3520. EXPECT_EQ(Error::Read, result.error());
  3521. }
  3522. #ifdef CPPHTTPLIB_SSL_ENABLED
  3523. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3524. auto result = GetThroughRedirectToDifferentPort(
  3525. [](const Request &, Response &res) {
  3526. res.status = StatusCode::Unauthorized_401;
  3527. res.set_header("WWW-Authenticate",
  3528. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3529. },
  3530. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3531. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3532. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3533. }
  3534. #endif
  3535. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3536. Server svr;
  3537. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3538. // Port number that overflows int — should not crash
  3539. res.set_redirect("http://localhost:99999999999999999999/target");
  3540. });
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3543. auto se = detail::scope_exit([&] {
  3544. svr.stop();
  3545. thread.join();
  3546. ASSERT_FALSE(svr.is_running());
  3547. });
  3548. svr.wait_until_ready();
  3549. Client cli(HOST, port);
  3550. cli.set_follow_location(true);
  3551. auto res = cli.Get("/redir");
  3552. // Should fail gracefully, not crash (no valid response due to bad port)
  3553. EXPECT_FALSE(res);
  3554. }
  3555. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3556. Server svr;
  3557. auto port = svr.bind_to_any_port(HOST);
  3558. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3559. // The server's own port followed by junk must not be followed
  3560. res.set_redirect("http://" + std::string(HOST) + ":" +
  3561. std::to_string(port) + "junk/target");
  3562. });
  3563. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("target", "text/plain");
  3565. });
  3566. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. Client cli(HOST, port);
  3574. cli.set_follow_location(true);
  3575. auto res = cli.Get("/redir");
  3576. EXPECT_FALSE(res);
  3577. }
  3578. TEST(RedirectFromPageWithContent, Redirect) {
  3579. Server svr;
  3580. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3581. res.set_content("___", "text/plain");
  3582. res.set_redirect("/2");
  3583. });
  3584. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3585. res.set_content("Hello World!", "text/plain");
  3586. });
  3587. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3588. auto se = detail::scope_exit([&] {
  3589. svr.stop();
  3590. th.join();
  3591. ASSERT_FALSE(svr.is_running());
  3592. });
  3593. svr.wait_until_ready();
  3594. {
  3595. Client cli("localhost", PORT);
  3596. cli.set_follow_location(true);
  3597. std::string body;
  3598. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3599. body.append(data, data_length);
  3600. return true;
  3601. });
  3602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3603. EXPECT_EQ(StatusCode::OK_200, res->status);
  3604. EXPECT_EQ("Hello World!", body);
  3605. }
  3606. {
  3607. Client cli("localhost", PORT);
  3608. std::string body;
  3609. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3610. body.append(data, data_length);
  3611. return true;
  3612. });
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::Found_302, res->status);
  3615. EXPECT_EQ("___", body);
  3616. }
  3617. }
  3618. // A server can close the connection after a request with "Connection: close"
  3619. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3620. // redirected request must go out on a new connection.
  3621. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3622. #ifndef _WIN32
  3623. signal(SIGPIPE, SIG_IGN);
  3624. #endif
  3625. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3626. default_socket_options(srv);
  3627. sockaddr_in addr{};
  3628. addr.sin_family = AF_INET;
  3629. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3630. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3631. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3632. ASSERT_EQ(0, ::listen(srv, 2));
  3633. auto send_text = [](socket_t sock, const std::string &text) {
  3634. ::send(sock,
  3635. #ifdef _WIN32
  3636. static_cast<const char *>(text.c_str()),
  3637. static_cast<int>(text.size()),
  3638. #else
  3639. text.c_str(), text.size(),
  3640. #endif
  3641. 0);
  3642. };
  3643. auto reused = false;
  3644. auto server_thread = std::thread([&] {
  3645. char buf[4096];
  3646. auto first = ::accept(srv, nullptr, nullptr);
  3647. if (first == INVALID_SOCKET) { return; }
  3648. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3649. ::recv(first, buf, sizeof(buf), 0);
  3650. send_text(
  3651. first,
  3652. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3653. auto next = first;
  3654. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3655. reused = true;
  3656. } else {
  3657. detail::close_socket(first);
  3658. next = ::accept(srv, nullptr, nullptr);
  3659. if (next == INVALID_SOCKET) { return; }
  3660. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3661. ::recv(next, buf, sizeof(buf), 0);
  3662. }
  3663. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3664. "Connection: close\r\n\r\nok");
  3665. detail::close_socket(next);
  3666. });
  3667. Client cli("127.0.0.1", PORT + 2);
  3668. cli.set_follow_location(true);
  3669. cli.set_read_timeout(5, 0);
  3670. auto res = cli.Get("/1");
  3671. server_thread.join();
  3672. detail::close_socket(srv);
  3673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3674. EXPECT_EQ(StatusCode::OK_200, res->status);
  3675. EXPECT_EQ("ok", res->body);
  3676. EXPECT_FALSE(reused);
  3677. }
  3678. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3679. Server svr;
  3680. auto port_str = std::to_string(PORT);
  3681. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3682. auto expected_host = "[::1]:" + port_str;
  3683. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3684. res.set_content("___", "text/plain");
  3685. // res.set_redirect("/2");
  3686. res.set_redirect(redirect_url);
  3687. });
  3688. svr.Get("/2", [&](const Request &req, Response &res) {
  3689. auto host_header = req.headers.find("Host");
  3690. ASSERT_TRUE(host_header != req.headers.end());
  3691. EXPECT_EQ(expected_host, host_header->second);
  3692. res.set_content("Hello World!", "text/plain");
  3693. });
  3694. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3695. auto se = detail::scope_exit([&] {
  3696. svr.stop();
  3697. th.join();
  3698. ASSERT_FALSE(svr.is_running());
  3699. });
  3700. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3701. // actually starts anything, so the condition !svr.is_running() will
  3702. // always remain true, and the loop never stops.
  3703. // This basically counts how many milliseconds have passed since the
  3704. // call to svr.listen(), and if after 5 seconds nothing started yet
  3705. // aborts the test.
  3706. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3707. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3708. ASSERT_LT(milliseconds, 5000U);
  3709. }
  3710. {
  3711. Client cli("::1", PORT);
  3712. cli.set_follow_location(true);
  3713. std::string body;
  3714. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3715. body.append(data, data_length);
  3716. return true;
  3717. });
  3718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3719. EXPECT_EQ(StatusCode::OK_200, res->status);
  3720. EXPECT_EQ("Hello World!", body);
  3721. }
  3722. {
  3723. Client cli("::1", PORT);
  3724. std::string body;
  3725. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3726. body.append(data, data_length);
  3727. return true;
  3728. });
  3729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3730. EXPECT_EQ(StatusCode::Found_302, res->status);
  3731. EXPECT_EQ("___", body);
  3732. }
  3733. }
  3734. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3735. Server svr;
  3736. svr.Get("/foo", [](const Request &req, Response &res) {
  3737. auto a = req.params.find("a");
  3738. if (a != req.params.end()) {
  3739. res.set_content((*a).second, "text/plain");
  3740. res.status = StatusCode::OK_200;
  3741. } else {
  3742. res.status = StatusCode::BadRequest_400;
  3743. }
  3744. });
  3745. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3746. auto se = detail::scope_exit([&] {
  3747. svr.stop();
  3748. thread.join();
  3749. ASSERT_FALSE(svr.is_running());
  3750. });
  3751. svr.wait_until_ready();
  3752. {
  3753. Client cli(HOST, PORT);
  3754. cli.set_path_encode(false);
  3755. auto res = cli.Get("/foo?a=explicitly+encoded");
  3756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3757. EXPECT_EQ(StatusCode::OK_200, res->status);
  3758. // This expects it back with a space, as the `+` won't have been
  3759. // url-encoded, and server-side the params get decoded turning `+`
  3760. // into spaces.
  3761. EXPECT_EQ("explicitly encoded", res->body);
  3762. }
  3763. }
  3764. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3765. // When path encoding is disabled the client must transmit the supplied
  3766. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3767. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3768. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3769. // than a space (0x20). Assert on the raw wire target to catch this.
  3770. Server svr;
  3771. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3772. svr.Get("/foo", [&](const Request &req, Response &res) {
  3773. EXPECT_EQ(expected_target, req.target);
  3774. res.status = StatusCode::OK_200;
  3775. });
  3776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3777. auto se = detail::scope_exit([&] {
  3778. svr.stop();
  3779. thread.join();
  3780. ASSERT_FALSE(svr.is_running());
  3781. });
  3782. svr.wait_until_ready();
  3783. {
  3784. Client cli(HOST, PORT);
  3785. cli.set_path_encode(false);
  3786. auto res = cli.Get(expected_target.c_str());
  3787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3788. EXPECT_EQ(StatusCode::OK_200, res->status);
  3789. }
  3790. }
  3791. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3792. // `open_stream()` used to skip the path encoding that the buffered send
  3793. // path applies, so the same `path` produced different bytes in the request
  3794. // line depending on which API was used. Assert the two agree.
  3795. Server svr;
  3796. std::string target;
  3797. svr.Get(".*", [&](const Request &req, Response &res) {
  3798. target = req.target;
  3799. res.status = StatusCode::OK_200;
  3800. });
  3801. auto port = svr.bind_to_any_port(HOST);
  3802. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3803. auto se = detail::scope_exit([&] {
  3804. svr.stop();
  3805. thread.join();
  3806. ASSERT_FALSE(svr.is_running());
  3807. });
  3808. svr.wait_until_ready();
  3809. struct {
  3810. const char *path;
  3811. const char *expected;
  3812. } cases[] = {
  3813. {"/a b?x=1", "/a%20b?x=1"},
  3814. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3815. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3816. };
  3817. for (const auto &c : cases) {
  3818. Client cli(HOST, port);
  3819. target.clear();
  3820. auto res = cli.Get(c.path);
  3821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3822. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3823. auto buffered_target = target;
  3824. target.clear();
  3825. auto handle = cli.open_stream("GET", c.path);
  3826. EXPECT_TRUE(handle.is_valid())
  3827. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3828. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3829. }
  3830. }
  3831. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3832. // The `set_path_encode(false)` contract — transmit the supplied target
  3833. // verbatim — must hold for the streaming API too.
  3834. Server svr;
  3835. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3836. std::string target;
  3837. svr.Get("/foo", [&](const Request &req, Response &res) {
  3838. target = req.target;
  3839. res.status = StatusCode::OK_200;
  3840. });
  3841. auto port = svr.bind_to_any_port(HOST);
  3842. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3843. auto se = detail::scope_exit([&] {
  3844. svr.stop();
  3845. thread.join();
  3846. ASSERT_FALSE(svr.is_running());
  3847. });
  3848. svr.wait_until_ready();
  3849. {
  3850. Client cli(HOST, port);
  3851. cli.set_path_encode(false);
  3852. auto handle = cli.open_stream("GET", expected_target);
  3853. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3854. EXPECT_EQ(expected_target, target);
  3855. }
  3856. }
  3857. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3858. // With path encoding enabled a CR/LF in the target is percent-encoded
  3859. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3860. // write_request_line still backstops `set_path_encode(false)`, which is
  3861. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3862. Server svr;
  3863. // Captured before routing: the decoded path contains a newline, which a
  3864. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3865. std::string target;
  3866. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3867. target = req.target;
  3868. res.status = StatusCode::OK_200;
  3869. return Server::HandlerResponse::Handled;
  3870. });
  3871. auto port = svr.bind_to_any_port(HOST);
  3872. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3873. auto se = detail::scope_exit([&] {
  3874. svr.stop();
  3875. thread.join();
  3876. ASSERT_FALSE(svr.is_running());
  3877. });
  3878. svr.wait_until_ready();
  3879. {
  3880. Client cli(HOST, port);
  3881. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3882. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3883. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3884. }
  3885. }
  3886. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3887. // Every control character is percent-encoded, not just CR/LF, so the target
  3888. // passes the request-target check in write_request_line.
  3889. Server svr;
  3890. std::string target;
  3891. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3892. target = req.target;
  3893. res.status = StatusCode::OK_200;
  3894. return Server::HandlerResponse::Handled;
  3895. });
  3896. auto port = svr.bind_to_any_port(HOST);
  3897. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3898. auto se = detail::scope_exit([&] {
  3899. svr.stop();
  3900. thread.join();
  3901. ASSERT_FALSE(svr.is_running());
  3902. });
  3903. svr.wait_until_ready();
  3904. {
  3905. Client cli(HOST, port);
  3906. auto res = cli.Get("/a\tb\x1b\x7f");
  3907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3908. EXPECT_EQ("/a%09b%1B%7F", target);
  3909. }
  3910. }
  3911. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3912. // Nothing may reach the wire: a raw CR/LF target would split the request
  3913. // line and inject headers.
  3914. Server svr;
  3915. // Pre-routing so that "not called" means nothing reached the server at all,
  3916. // rather than merely failing to match a handler pattern.
  3917. auto handler_called = false;
  3918. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3919. handler_called = true;
  3920. res.status = StatusCode::OK_200;
  3921. return Server::HandlerResponse::Handled;
  3922. });
  3923. auto port = svr.bind_to_any_port(HOST);
  3924. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3925. auto se = detail::scope_exit([&] {
  3926. svr.stop();
  3927. thread.join();
  3928. ASSERT_FALSE(svr.is_running());
  3929. });
  3930. svr.wait_until_ready();
  3931. {
  3932. Client cli(HOST, port);
  3933. cli.set_path_encode(false);
  3934. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3935. EXPECT_FALSE(handle.is_valid());
  3936. EXPECT_EQ(Error::Write, handle.error);
  3937. EXPECT_FALSE(handler_called);
  3938. }
  3939. }
  3940. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3941. // Which of the two branches runs is decided by whether the query component
  3942. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3943. // an empty query and must still fall back to building one from
  3944. // `req.params`, while a non-empty query must win over `req.params`.
  3945. Server svr;
  3946. std::string target;
  3947. svr.Get("/foo", [&](const Request &req, Response &res) {
  3948. target = req.target;
  3949. res.status = StatusCode::OK_200;
  3950. });
  3951. auto port = svr.bind_to_any_port(HOST);
  3952. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3953. auto se = detail::scope_exit([&] {
  3954. svr.stop();
  3955. thread.join();
  3956. ASSERT_FALSE(svr.is_running());
  3957. });
  3958. svr.wait_until_ready();
  3959. {
  3960. // Trailing `?` -> empty query component -> `req.params` is used.
  3961. Client cli(HOST, port);
  3962. Request req;
  3963. req.method = "GET";
  3964. req.path = "/foo?";
  3965. req.params.emplace("a", "1");
  3966. target.clear();
  3967. auto res = cli.send(req);
  3968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3969. EXPECT_EQ("/foo?a=1", target);
  3970. }
  3971. {
  3972. // Non-empty query in `req.path` -> `req.params` is not appended.
  3973. Client cli(HOST, port);
  3974. Request req;
  3975. req.method = "GET";
  3976. req.path = "/foo?b=2";
  3977. req.params.emplace("a", "1");
  3978. target.clear();
  3979. auto res = cli.send(req);
  3980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3981. EXPECT_EQ("/foo?b=2", target);
  3982. }
  3983. }
  3984. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3985. Server svr;
  3986. svr.Get("/", [](const Request &req, Response &) {
  3987. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3988. });
  3989. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3990. auto se = detail::scope_exit([&] {
  3991. svr.stop();
  3992. thread.join();
  3993. ASSERT_FALSE(svr.is_running());
  3994. });
  3995. svr.wait_until_ready();
  3996. {
  3997. Client cli(HOST, PORT);
  3998. cli.set_path_encode(false);
  3999. auto res = cli.Get("/?something=%0A");
  4000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4001. EXPECT_EQ(StatusCode::OK_200, res->status);
  4002. }
  4003. }
  4004. TEST(BindServerTest, BindDualStack) {
  4005. Server svr;
  4006. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4007. res.set_content("Hello World!", "text/plain");
  4008. });
  4009. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4010. auto se = detail::scope_exit([&] {
  4011. svr.stop();
  4012. thread.join();
  4013. ASSERT_FALSE(svr.is_running());
  4014. });
  4015. svr.wait_until_ready();
  4016. {
  4017. Client cli("127.0.0.1", PORT);
  4018. auto res = cli.Get("/1");
  4019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4020. EXPECT_EQ(StatusCode::OK_200, res->status);
  4021. EXPECT_EQ("Hello World!", res->body);
  4022. }
  4023. {
  4024. Client cli("::1", PORT);
  4025. auto res = cli.Get("/1");
  4026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4027. EXPECT_EQ(StatusCode::OK_200, res->status);
  4028. EXPECT_EQ("Hello World!", res->body);
  4029. }
  4030. }
  4031. TEST(BindServerTest, BindAndListenSeparately) {
  4032. Server svr;
  4033. int port = svr.bind_to_any_port("0.0.0.0");
  4034. ASSERT_TRUE(svr.is_valid());
  4035. ASSERT_TRUE(port > 0);
  4036. svr.stop();
  4037. }
  4038. // Reports whether anything is still listening on a loopback port. A plain
  4039. // connect() is used instead of a Client request because a socket left bound by
  4040. // mistake accepts the connection into its backlog and never answers, which
  4041. // would hang the test instead of failing it.
  4042. static bool is_loopback_port_accepting(int port) {
  4043. sockaddr_in addr{};
  4044. addr.sin_family = AF_INET;
  4045. addr.sin_port = htons(static_cast<uint16_t>(port));
  4046. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4047. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4048. EXPECT_NE(sock, INVALID_SOCKET);
  4049. if (sock == INVALID_SOCKET) { return false; }
  4050. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4051. static_cast<socklen_t>(sizeof(addr)));
  4052. detail::close_socket(sock);
  4053. return ret == 0;
  4054. }
  4055. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4056. Server svr;
  4057. auto port = svr.bind_to_any_port("127.0.0.1");
  4058. ASSERT_TRUE(port > 0);
  4059. svr.stop();
  4060. // bind_to_any_port() already called listen(2), so until stop() closed the
  4061. // descriptor the port kept accepting connections into the backlog. ASSERT
  4062. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4063. // below blocks forever in the accept loop.
  4064. ASSERT_FALSE(is_loopback_port_accepting(port));
  4065. // Nothing is left to accept on, so listen_after_bind() must report failure
  4066. // instead of returning success without ever serving.
  4067. EXPECT_FALSE(svr.listen_after_bind());
  4068. // The failed listen marks the server decommissioned, so a waiter returns
  4069. // instead of spinning forever.
  4070. svr.wait_until_ready();
  4071. }
  4072. #ifdef CPPHTTPLIB_SSL_ENABLED
  4073. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4074. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4075. CLIENT_CA_CERT_DIR);
  4076. int port = svr.bind_to_any_port("0.0.0.0");
  4077. ASSERT_TRUE(svr.is_valid());
  4078. ASSERT_TRUE(port > 0);
  4079. svr.stop();
  4080. }
  4081. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4082. // or a rejected CustomRoute() registration would not stop the server binding.
  4083. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4084. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4085. CLIENT_CA_CERT_DIR);
  4086. ASSERT_TRUE(svr.is_valid());
  4087. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4088. EXPECT_FALSE(svr.is_valid());
  4089. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4090. }
  4091. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4092. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4093. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4094. int port = svr.bind_to_any_port("0.0.0.0");
  4095. ASSERT_TRUE(svr.is_valid());
  4096. ASSERT_TRUE(port > 0);
  4097. svr.stop();
  4098. }
  4099. TEST(BindServerTest, UpdateCertsPem) {
  4100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4101. int port = svr.bind_to_any_port("0.0.0.0");
  4102. ASSERT_TRUE(svr.is_valid());
  4103. ASSERT_TRUE(port > 0);
  4104. // Read PEM files
  4105. std::string cert_pem, key_pem, ca_pem;
  4106. read_file(SERVER_CERT_FILE, cert_pem);
  4107. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4108. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4109. // Update server certificates using PEM API
  4110. ASSERT_TRUE(
  4111. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4112. ASSERT_TRUE(svr.is_valid());
  4113. svr.stop();
  4114. }
  4115. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4116. // Start server with client CA (enables client auth)
  4117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4118. ASSERT_TRUE(svr.is_valid());
  4119. bool handler_called = false;
  4120. svr.Get("/test", [&](const Request &req, Response &res) {
  4121. handler_called = true;
  4122. // Verify client certificate is present
  4123. auto cert = req.peer_cert();
  4124. EXPECT_TRUE(static_cast<bool>(cert));
  4125. res.set_content("ok", "text/plain");
  4126. });
  4127. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4128. auto se = detail::scope_exit([&] {
  4129. svr.stop();
  4130. t.join();
  4131. ASSERT_FALSE(svr.is_running());
  4132. });
  4133. svr.wait_until_ready();
  4134. // Read PEM files
  4135. std::string cert_pem, key_pem, ca_pem;
  4136. read_file(SERVER_CERT_FILE, cert_pem);
  4137. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4138. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4139. // Update server certificates and client CA using PEM API while server running
  4140. ASSERT_TRUE(
  4141. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4142. // Connect with client certificate
  4143. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4144. cli.enable_server_certificate_verification(false);
  4145. cli.set_connection_timeout(30);
  4146. auto res = cli.Get("/test");
  4147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4148. ASSERT_EQ(StatusCode::OK_200, res->status);
  4149. ASSERT_TRUE(handler_called);
  4150. EXPECT_EQ("ok", res->body);
  4151. }
  4152. // Puts a CA that did not sign the client's certificate in the old one's place.
  4153. static bool replace_client_ca(SSLServer &svr) {
  4154. std::string cert_pem, key_pem, ca_pem;
  4155. read_file(SERVER_CERT_FILE, cert_pem);
  4156. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4157. read_file(SERVER_CERT2_FILE, ca_pem);
  4158. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4159. ca_pem.c_str());
  4160. }
  4161. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4162. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4163. ASSERT_TRUE(svr.is_valid());
  4164. svr.Get("/test", [](const Request &, Response &res) {
  4165. res.set_content("ok", "text/plain");
  4166. });
  4167. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4168. auto se = detail::scope_exit([&] {
  4169. svr.stop();
  4170. t.join();
  4171. ASSERT_FALSE(svr.is_running());
  4172. });
  4173. svr.wait_until_ready();
  4174. auto get = [] {
  4175. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4176. cli.enable_server_certificate_verification(false);
  4177. return cli.Get("/test");
  4178. };
  4179. ASSERT_TRUE(get());
  4180. ASSERT_TRUE(replace_client_ca(svr));
  4181. EXPECT_FALSE(get());
  4182. }
  4183. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4184. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4186. ASSERT_TRUE(svr.is_valid());
  4187. tls::set_verify_callback(svr.tls_context(),
  4188. [](const tls::VerifyContext &) -> bool {
  4189. throw std::runtime_error("verify");
  4190. });
  4191. svr.Get("/test", [](const Request &, Response &res) {
  4192. res.set_content("ok", "text/plain");
  4193. });
  4194. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4195. auto se = detail::scope_exit([&] {
  4196. svr.stop();
  4197. t.join();
  4198. ASSERT_FALSE(svr.is_running());
  4199. });
  4200. svr.wait_until_ready();
  4201. auto get = [] {
  4202. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4203. cli.enable_server_certificate_verification(false);
  4204. return cli.Get("/test");
  4205. };
  4206. EXPECT_FALSE(get());
  4207. // The handshake is over, so an update does not wait for it.
  4208. std::string cert_pem, key_pem;
  4209. read_file(SERVER_CERT_FILE, cert_pem);
  4210. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4211. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4212. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4213. return v.preverify_ok;
  4214. });
  4215. auto res = get();
  4216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4217. EXPECT_EQ("ok", res->body);
  4218. }
  4219. #endif
  4220. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4221. // Sends each request over a new connection with a client certificate,
  4222. // resuming the session of the one before when there is one.
  4223. class ResumingClient {
  4224. public:
  4225. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4226. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4227. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4228. SSL_FILETYPE_PEM);
  4229. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4230. // callback, not through SSL_get1_session().
  4231. SSL_CTX_set_app_data(ctx_, this);
  4232. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4233. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4234. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4235. auto self = static_cast<ResumingClient *>(
  4236. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4237. SSL_SESSION_free(self->session_);
  4238. self->session_ = session;
  4239. return 1; // Keeps the reference
  4240. });
  4241. }
  4242. ~ResumingClient() {
  4243. SSL_SESSION_free(session_);
  4244. SSL_CTX_free(ctx_);
  4245. }
  4246. // Tells whether the request was answered.
  4247. bool get() {
  4248. auto error = Error::Success;
  4249. auto sock = detail::create_client_socket(
  4250. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4251. /*connection_timeout_sec=*/5, 0,
  4252. /*read_timeout_sec=*/5, 0,
  4253. /*write_timeout_sec=*/5, 0, std::string(), error);
  4254. if (sock == INVALID_SOCKET) { return false; }
  4255. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4256. auto ssl = SSL_new(ctx_);
  4257. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4258. SSL_set_fd(ssl, static_cast<int>(sock));
  4259. if (session_) { SSL_set_session(ssl, session_); }
  4260. if (SSL_connect(ssl) != 1) { return false; }
  4261. reused_ = SSL_session_reused(ssl) == 1;
  4262. // Reading the response also takes in a TLS 1.3 session ticket.
  4263. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4264. "Connection: close\r\n\r\n";
  4265. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4266. std::string res;
  4267. char buf[256];
  4268. int n;
  4269. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4270. res.append(buf, static_cast<size_t>(n));
  4271. }
  4272. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4273. SSL_shutdown(ssl);
  4274. return res.find("200 OK") != std::string::npos;
  4275. }
  4276. // Whether the last connection resumed a session
  4277. bool reused() const { return reused_; }
  4278. private:
  4279. SSL_CTX *ctx_;
  4280. SSL_SESSION *session_ = nullptr;
  4281. bool reused_ = false;
  4282. };
  4283. // A client that resumes its session gets through, but not once the client CA
  4284. // has changed, as a resumed session does not show the certificate again.
  4285. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4286. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4287. ASSERT_TRUE(svr.is_valid());
  4288. svr.Get("/test", [](const Request &, Response &res) {
  4289. res.set_content("ok", "text/plain");
  4290. });
  4291. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4292. auto se = detail::scope_exit([&] {
  4293. svr.stop();
  4294. t.join();
  4295. ASSERT_FALSE(svr.is_running());
  4296. });
  4297. svr.wait_until_ready();
  4298. ResumingClient cli;
  4299. ASSERT_TRUE(cli.get());
  4300. ASSERT_TRUE(cli.get());
  4301. EXPECT_TRUE(cli.reused());
  4302. ASSERT_TRUE(replace_client_ca(svr));
  4303. EXPECT_FALSE(cli.get());
  4304. }
  4305. // A resumed session does not show the certificate again, so the server does
  4306. // not resume one with a verify callback to run on it.
  4307. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4308. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4309. ASSERT_TRUE(svr.is_valid());
  4310. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4311. return v.preverify_ok;
  4312. });
  4313. svr.Get("/test", [](const Request &, Response &res) {
  4314. res.set_content("ok", "text/plain");
  4315. });
  4316. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4317. auto se = detail::scope_exit([&] {
  4318. svr.stop();
  4319. t.join();
  4320. ASSERT_FALSE(svr.is_running());
  4321. });
  4322. svr.wait_until_ready();
  4323. ResumingClient cli;
  4324. ASSERT_TRUE(cli.get());
  4325. ASSERT_TRUE(cli.get());
  4326. EXPECT_FALSE(cli.reused());
  4327. }
  4328. #endif
  4329. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4330. // wolfSSL shares its session cache between contexts, so a resumed session
  4331. // could carry a client certificate checked against another server's CA, or
  4332. // against a client CA since replaced.
  4333. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4334. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4335. ASSERT_TRUE(svr.is_valid());
  4336. // Trusts a CA that did not sign the client's certificate.
  4337. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4338. ASSERT_TRUE(other.is_valid());
  4339. for (auto s : {&svr, &other}) {
  4340. s->Get("/test", [](const Request &, Response &res) {
  4341. res.set_content("ok", "text/plain");
  4342. });
  4343. }
  4344. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4345. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4346. auto se = detail::scope_exit([&] {
  4347. other.stop();
  4348. svr.stop();
  4349. t2.join();
  4350. t.join();
  4351. });
  4352. svr.wait_until_ready();
  4353. other.wait_until_ready();
  4354. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4355. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4356. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4357. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4358. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4359. ASSERT_EQ(WOLFSSL_SUCCESS,
  4360. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4361. WOLFSSL_FILETYPE_PEM));
  4362. WOLFSSL_SESSION *session = nullptr;
  4363. auto session_se = detail::scope_exit([&] {
  4364. if (session) { wolfSSL_SESSION_free(session); }
  4365. });
  4366. // A request over a new connection, resuming `session` when there is one and
  4367. // keeping the connection's own in its place. Tells whether it was answered.
  4368. auto get = [&](int port) {
  4369. auto error = Error::Success;
  4370. auto sock = detail::create_client_socket(
  4371. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4372. /*connection_timeout_sec=*/5, 0,
  4373. /*read_timeout_sec=*/5, 0,
  4374. /*write_timeout_sec=*/5, 0, std::string(), error);
  4375. if (sock == INVALID_SOCKET) { return false; }
  4376. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4377. auto ssl = wolfSSL_new(ctx);
  4378. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4379. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4380. if (session) { wolfSSL_set_session(ssl, session); }
  4381. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4382. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4383. "Connection: close\r\n\r\n";
  4384. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4385. std::string res;
  4386. char buf[256];
  4387. int n;
  4388. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4389. res.append(buf, static_cast<size_t>(n));
  4390. }
  4391. wolfSSL_shutdown(ssl);
  4392. if (session) { wolfSSL_SESSION_free(session); }
  4393. session = wolfSSL_get1_session(ssl);
  4394. return res.find("200 OK") != std::string::npos;
  4395. };
  4396. ASSERT_TRUE(get(PORT));
  4397. EXPECT_FALSE(get(PORT + 1));
  4398. ASSERT_TRUE(get(PORT));
  4399. ASSERT_TRUE(replace_client_ca(svr));
  4400. EXPECT_FALSE(get(PORT));
  4401. }
  4402. #endif
  4403. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4404. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4405. ASSERT_TRUE(svr.is_valid());
  4406. svr.Get("/test", [](const Request &, Response &res) {
  4407. res.set_content("ok", "text/plain");
  4408. });
  4409. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4410. auto se = detail::scope_exit([&] {
  4411. svr.stop();
  4412. t.join();
  4413. ASSERT_FALSE(svr.is_running());
  4414. });
  4415. svr.wait_until_ready();
  4416. // A connection that sends no ClientHello keeps its handshake in progress,
  4417. // once the server has had a moment to start it.
  4418. auto error = Error::Success;
  4419. auto sock = detail::create_client_socket(
  4420. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4421. /*connection_timeout_sec=*/5, 0,
  4422. /*read_timeout_sec=*/5, 0,
  4423. /*write_timeout_sec=*/5, 0, std::string(), error);
  4424. ASSERT_NE(INVALID_SOCKET, sock);
  4425. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4426. std::string cert_pem, key_pem;
  4427. read_file(SERVER_CERT_FILE, cert_pem);
  4428. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4429. auto update = std::async(std::launch::async, [&]() {
  4430. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4431. });
  4432. EXPECT_EQ(std::future_status::timeout,
  4433. update.wait_for(std::chrono::milliseconds(200)));
  4434. detail::close_socket(sock);
  4435. EXPECT_TRUE(update.get());
  4436. SSLClient cli(HOST, PORT);
  4437. cli.enable_server_certificate_verification(false);
  4438. auto res = cli.Get("/test");
  4439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4440. EXPECT_EQ(StatusCode::OK_200, res->status);
  4441. }
  4442. #endif
  4443. TEST(ErrorHandlerTest, ContentLength) {
  4444. Server svr;
  4445. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4446. res.status = StatusCode::OK_200;
  4447. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4448. "text/html"); // <= Content-Length still 13
  4449. });
  4450. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4451. res.set_content("Hello World!\n", "text/plain");
  4452. res.status = 524;
  4453. });
  4454. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4455. auto se = detail::scope_exit([&] {
  4456. svr.stop();
  4457. thread.join();
  4458. ASSERT_FALSE(svr.is_running());
  4459. });
  4460. svr.wait_until_ready();
  4461. {
  4462. Client cli(HOST, PORT);
  4463. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4465. EXPECT_EQ(StatusCode::OK_200, res->status);
  4466. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4467. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4468. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4469. }
  4470. }
  4471. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4472. TEST(ExceptionTest, WithoutExceptionHandler) {
  4473. Server svr;
  4474. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4475. throw std::runtime_error("exception...");
  4476. });
  4477. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4478. throw std::runtime_error("exception\r\n...");
  4479. });
  4480. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4481. auto se = detail::scope_exit([&] {
  4482. svr.stop();
  4483. listen_thread.join();
  4484. ASSERT_FALSE(svr.is_running());
  4485. });
  4486. svr.wait_until_ready();
  4487. Client cli("localhost", PORT);
  4488. {
  4489. auto res = cli.Get("/exception");
  4490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4491. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4492. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4493. }
  4494. {
  4495. auto res = cli.Get("/unknown");
  4496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4497. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4498. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4499. }
  4500. }
  4501. TEST(ExceptionTest, WithExceptionHandler) {
  4502. Server svr;
  4503. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4504. std::exception_ptr ep) {
  4505. EXPECT_FALSE(ep == nullptr);
  4506. try {
  4507. std::rethrow_exception(ep);
  4508. } catch (std::exception &e) {
  4509. EXPECT_EQ("abc", std::string(e.what()));
  4510. } catch (...) {}
  4511. res.status = StatusCode::InternalServerError_500;
  4512. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4513. "text/html"); // <= Content-Length still 13 at this point
  4514. });
  4515. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4516. res.set_content("Hello World!\n", "text/plain");
  4517. throw std::runtime_error("abc");
  4518. });
  4519. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4520. auto se = detail::scope_exit([&] {
  4521. svr.stop();
  4522. thread.join();
  4523. ASSERT_FALSE(svr.is_running());
  4524. });
  4525. svr.wait_until_ready();
  4526. for (size_t i = 0; i < 10; i++) {
  4527. Client cli(HOST, PORT);
  4528. for (size_t j = 0; j < 100; j++) {
  4529. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4531. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4532. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4533. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4534. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4535. }
  4536. cli.set_keep_alive(true);
  4537. for (size_t j = 0; j < 100; j++) {
  4538. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4540. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4541. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4542. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4543. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4544. }
  4545. }
  4546. }
  4547. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4548. Server svr;
  4549. svr.set_exception_handler(
  4550. [](const Request &, Response &res, std::exception_ptr) {
  4551. res.set_content("oops", "text/plain");
  4552. });
  4553. svr.Get("/throw", [](const Request &, Response &) {
  4554. throw std::runtime_error("throw");
  4555. });
  4556. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4557. res.status = StatusCode::Created_201;
  4558. throw std::runtime_error("created-then-throw");
  4559. });
  4560. auto port = svr.bind_to_any_port(HOST);
  4561. ASSERT_GT(port, 0);
  4562. thread t = thread([&] { svr.listen_after_bind(); });
  4563. auto se = detail::scope_exit([&] {
  4564. svr.stop();
  4565. t.join();
  4566. ASSERT_FALSE(svr.is_running());
  4567. });
  4568. svr.wait_until_ready();
  4569. Client cli(HOST, port);
  4570. for (auto path : {"/throw", "/created-then-throw"}) {
  4571. auto res = cli.Get(path);
  4572. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4573. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4574. }
  4575. }
  4576. TEST(ExceptionTest, AndErrorHandler) {
  4577. Server svr;
  4578. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4579. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4580. });
  4581. svr.set_exception_handler(
  4582. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4583. EXPECT_FALSE(ep == nullptr);
  4584. try {
  4585. std::rethrow_exception(ep);
  4586. } catch (std::exception &e) {
  4587. res.set_content(e.what(), "text/html");
  4588. } catch (...) {}
  4589. res.status = StatusCode::InternalServerError_500;
  4590. });
  4591. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4592. throw std::runtime_error("EXCEPTION");
  4593. });
  4594. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4595. res.set_content("ERROR", "text/html");
  4596. res.status = StatusCode::InternalServerError_500;
  4597. });
  4598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4599. auto se = detail::scope_exit([&] {
  4600. svr.stop();
  4601. thread.join();
  4602. ASSERT_FALSE(svr.is_running());
  4603. });
  4604. svr.wait_until_ready();
  4605. Client cli(HOST, PORT);
  4606. {
  4607. auto res = cli.Get("/exception");
  4608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4609. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4610. EXPECT_EQ("EXCEPTION", res->body);
  4611. }
  4612. {
  4613. auto res = cli.Get("/error");
  4614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4615. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4616. EXPECT_EQ("ERROR", res->body);
  4617. }
  4618. {
  4619. auto res = cli.Get("/invalid");
  4620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4621. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4622. EXPECT_EQ("NOT_FOUND", res->body);
  4623. }
  4624. }
  4625. #endif
  4626. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4627. // An exception from a user callback outside process_request()'s try/catch
  4628. // used to unwind into the task queue - which does not catch - and terminate
  4629. // the process. Each test below runs the server on a single worker thread: a
  4630. // guard that catches the exception but still loses the thread would otherwise
  4631. // be hidden by a spare worker serving the follow-up request. Note that a
  4632. // regression here aborts the whole test binary rather than failing one test.
  4633. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4634. Server svr;
  4635. svr.new_task_queue = [] { return new ThreadPool(1); };
  4636. std::atomic<int> reported{0};
  4637. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4638. if (err == Error::UserCallbackException) { reported++; }
  4639. });
  4640. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4641. res.set_content_provider(
  4642. 1024, "text/plain",
  4643. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4644. sink.write("hello", 5);
  4645. throw std::runtime_error("from the content provider");
  4646. });
  4647. });
  4648. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4649. res.set_content("ok", "text/plain");
  4650. });
  4651. auto port = svr.bind_to_any_port(HOST);
  4652. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4653. auto se = detail::scope_exit([&] {
  4654. svr.stop();
  4655. listen_thread.join();
  4656. ASSERT_FALSE(svr.is_running());
  4657. });
  4658. svr.wait_until_ready();
  4659. {
  4660. Client cli(HOST, port);
  4661. cli.set_read_timeout(5, 0);
  4662. EXPECT_FALSE(cli.Get("/throw"));
  4663. }
  4664. EXPECT_TRUE(svr.is_running());
  4665. EXPECT_EQ(1, reported.load());
  4666. // A request on a fresh connection is still served.
  4667. {
  4668. Client cli(HOST, port);
  4669. auto res = cli.Get("/ok");
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. EXPECT_EQ(StatusCode::OK_200, res->status);
  4672. EXPECT_EQ("ok", res->body);
  4673. }
  4674. }
  4675. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4676. Server svr;
  4677. svr.new_task_queue = [] { return new ThreadPool(1); };
  4678. std::atomic<bool> should_throw{true};
  4679. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4680. res.set_content("hi", "text/plain");
  4681. });
  4682. svr.set_post_routing_handler(
  4683. [&](const Request & /*req*/, Response & /*res*/) {
  4684. if (should_throw) {
  4685. throw std::runtime_error("from the post-routing handler");
  4686. }
  4687. });
  4688. auto port = svr.bind_to_any_port(HOST);
  4689. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4690. auto se = detail::scope_exit([&] {
  4691. svr.stop();
  4692. listen_thread.join();
  4693. ASSERT_FALSE(svr.is_running());
  4694. });
  4695. svr.wait_until_ready();
  4696. {
  4697. Client cli(HOST, port);
  4698. cli.set_read_timeout(5, 0);
  4699. EXPECT_FALSE(cli.Get("/hi"));
  4700. }
  4701. EXPECT_TRUE(svr.is_running());
  4702. should_throw = false;
  4703. {
  4704. Client cli(HOST, port);
  4705. auto res = cli.Get("/hi");
  4706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4707. EXPECT_EQ(StatusCode::OK_200, res->status);
  4708. EXPECT_EQ("hi", res->body);
  4709. }
  4710. }
  4711. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4712. // The guard reports the caught exception through the error logger, which is
  4713. // a user callback too. A logger that throws has to be contained as well, or
  4714. // the process would terminate from inside the catch.
  4715. Server svr;
  4716. svr.new_task_queue = [] { return new ThreadPool(1); };
  4717. std::atomic<int> reported{0};
  4718. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4719. if (err == Error::UserCallbackException) {
  4720. reported++;
  4721. throw std::runtime_error("from the error logger");
  4722. }
  4723. });
  4724. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4725. res.set_content_provider(
  4726. 1024, "text/plain",
  4727. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4728. sink.write("hello", 5);
  4729. throw std::runtime_error("from the content provider");
  4730. });
  4731. });
  4732. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4733. res.set_content("ok", "text/plain");
  4734. });
  4735. auto port = svr.bind_to_any_port(HOST);
  4736. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4737. auto se = detail::scope_exit([&] {
  4738. svr.stop();
  4739. listen_thread.join();
  4740. ASSERT_FALSE(svr.is_running());
  4741. });
  4742. svr.wait_until_ready();
  4743. {
  4744. Client cli(HOST, port);
  4745. cli.set_read_timeout(5, 0);
  4746. EXPECT_FALSE(cli.Get("/throw"));
  4747. }
  4748. EXPECT_TRUE(svr.is_running());
  4749. EXPECT_EQ(1, reported.load());
  4750. {
  4751. Client cli(HOST, port);
  4752. auto res = cli.Get("/ok");
  4753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4754. EXPECT_EQ(StatusCode::OK_200, res->status);
  4755. EXPECT_EQ("ok", res->body);
  4756. }
  4757. }
  4758. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4759. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4760. // so the exception unwinds through the ws::WebSocket object on its way to
  4761. // the guard. None of the HTTP cases above cross that.
  4762. Server svr;
  4763. svr.new_task_queue = [] { return new ThreadPool(1); };
  4764. std::atomic<int> reported{0};
  4765. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4766. if (err == Error::UserCallbackException) { reported++; }
  4767. });
  4768. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4769. throw std::runtime_error("from the WebSocket handler");
  4770. });
  4771. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4772. res.set_content("ok", "text/plain");
  4773. });
  4774. auto port = svr.bind_to_any_port(HOST);
  4775. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4776. auto se = detail::scope_exit([&] {
  4777. svr.stop();
  4778. listen_thread.join();
  4779. ASSERT_FALSE(svr.is_running());
  4780. });
  4781. svr.wait_until_ready();
  4782. {
  4783. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4784. "/ws");
  4785. auto res = client.connect();
  4786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4787. // The server dropped the connection instead of dying.
  4788. std::string msg;
  4789. EXPECT_FALSE(client.read(msg));
  4790. client.close();
  4791. }
  4792. EXPECT_TRUE(svr.is_running());
  4793. EXPECT_EQ(1, reported.load());
  4794. {
  4795. Client cli(HOST, port);
  4796. auto res = cli.Get("/ok");
  4797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4798. EXPECT_EQ(StatusCode::OK_200, res->status);
  4799. EXPECT_EQ("ok", res->body);
  4800. }
  4801. }
  4802. #ifdef CPPHTTPLIB_SSL_ENABLED
  4803. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4804. // SSLServer::process_and_close_socket() is a separate overload with its own
  4805. // guard, so it is exercised on its own.
  4806. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4807. ASSERT_TRUE(svr.is_valid());
  4808. svr.new_task_queue = [] { return new ThreadPool(1); };
  4809. std::atomic<int> reported{0};
  4810. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4811. if (err == Error::UserCallbackException) { reported++; }
  4812. });
  4813. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4814. res.set_content_provider(
  4815. 1024, "text/plain",
  4816. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4817. sink.write("hello", 5);
  4818. throw std::runtime_error("from the content provider");
  4819. });
  4820. });
  4821. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4822. res.set_content("ok", "text/plain");
  4823. });
  4824. auto port = svr.bind_to_any_port(HOST);
  4825. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4826. auto se = detail::scope_exit([&] {
  4827. svr.stop();
  4828. listen_thread.join();
  4829. ASSERT_FALSE(svr.is_running());
  4830. });
  4831. svr.wait_until_ready();
  4832. {
  4833. SSLClient cli(HOST, port);
  4834. cli.enable_server_certificate_verification(false);
  4835. cli.set_read_timeout(5, 0);
  4836. EXPECT_FALSE(cli.Get("/throw"));
  4837. }
  4838. EXPECT_TRUE(svr.is_running());
  4839. EXPECT_EQ(1, reported.load());
  4840. {
  4841. SSLClient cli(HOST, port);
  4842. cli.enable_server_certificate_verification(false);
  4843. auto res = cli.Get("/ok");
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(StatusCode::OK_200, res->status);
  4846. EXPECT_EQ("ok", res->body);
  4847. }
  4848. }
  4849. #endif
  4850. #endif
  4851. TEST(NoContentTest, ContentLength) {
  4852. Server svr;
  4853. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4854. res.status = StatusCode::NoContent_204;
  4855. });
  4856. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4857. auto se = detail::scope_exit([&] {
  4858. svr.stop();
  4859. thread.join();
  4860. ASSERT_FALSE(svr.is_running());
  4861. });
  4862. svr.wait_until_ready();
  4863. {
  4864. Client cli(HOST, PORT);
  4865. auto res = cli.Get("/hi");
  4866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4867. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4868. // RFC 9110 8.6: none in a 204 response
  4869. EXPECT_FALSE(res->has_header("Content-Length"));
  4870. }
  4871. }
  4872. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4873. Server svr;
  4874. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4875. res.set_header("Content-Length", "5");
  4876. res.set_content("hello world", "text/plain");
  4877. });
  4878. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4879. // A body that reads as the last chunk, were it taken as chunked
  4880. res.set_header("Transfer-Encoding", "chunked");
  4881. res.set_content("0\r\n\r\n", "text/plain");
  4882. });
  4883. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4884. res.set_header("Content-Length", "2");
  4885. res.set_content_provider(5, "text/plain",
  4886. [](size_t offset, size_t length, DataSink &sink) {
  4887. sink.write(&"hello"[offset], length);
  4888. return true;
  4889. });
  4890. });
  4891. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4892. res.set_header("Content-Length", "1234");
  4893. });
  4894. thread t = thread([&] { svr.listen(HOST, PORT); });
  4895. auto se = detail::scope_exit([&] {
  4896. svr.stop();
  4897. t.join();
  4898. ASSERT_FALSE(svr.is_running());
  4899. });
  4900. svr.wait_until_ready();
  4901. Client cli(HOST, PORT);
  4902. cli.set_read_timeout(1, 0);
  4903. auto expect_body = [&](const Result &res, const std::string &body) {
  4904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4905. EXPECT_EQ(body, res->body);
  4906. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4907. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4908. };
  4909. Headers identity{{"Accept-Encoding", ""}};
  4910. expect_body(cli.Get("/body", identity), "hello world");
  4911. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4912. expect_body(cli.Get("/body",
  4913. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4914. "he");
  4915. expect_body(cli.Get("/provider", identity), "hello");
  4916. expect_body(cli.Get("/empty", identity), "");
  4917. // A HEAD response may give the length of the body a GET would get.
  4918. auto res = cli.Head("/empty");
  4919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4920. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4921. }
  4922. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4923. Server svr;
  4924. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4925. res.set_content("short", "text/plain");
  4926. });
  4927. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4928. res.body += " with a footer";
  4929. res.set_header("Transfer-Encoding", "chunked");
  4930. });
  4931. thread t = thread([&] { svr.listen(HOST, PORT); });
  4932. auto se = detail::scope_exit([&] {
  4933. svr.stop();
  4934. t.join();
  4935. ASSERT_FALSE(svr.is_running());
  4936. });
  4937. svr.wait_until_ready();
  4938. Client cli(HOST, PORT);
  4939. cli.set_read_timeout(1, 0);
  4940. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4942. EXPECT_EQ("short with a footer", res->body);
  4943. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4944. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4945. }
  4946. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4947. Server svr;
  4948. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4949. res.set_header("Content-Length", "3");
  4950. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4951. sink.write("abc", 3);
  4952. sink.done();
  4953. return true;
  4954. });
  4955. });
  4956. thread t = thread([&] { svr.listen(HOST, PORT); });
  4957. auto se = detail::scope_exit([&] {
  4958. svr.stop();
  4959. t.join();
  4960. ASSERT_FALSE(svr.is_running());
  4961. });
  4962. svr.wait_until_ready();
  4963. Client cli(HOST, PORT);
  4964. cli.set_keep_alive(true);
  4965. auto res = cli.Get("/");
  4966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4967. EXPECT_EQ("abc", res->body);
  4968. EXPECT_FALSE(res->has_header("Content-Length"));
  4969. EXPECT_EQ("close", res->get_header_value("Connection"));
  4970. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4971. // No body to delimit
  4972. auto head = cli.Head("/");
  4973. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4974. EXPECT_FALSE(head->has_header("Connection"));
  4975. }
  4976. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4977. #ifdef CPPHTTPLIB_SSL_ENABLED
  4978. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4979. ASSERT_TRUE(svr.is_valid());
  4980. #else
  4981. Server svr;
  4982. #endif
  4983. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4984. if (req.path == "/routing_handler") {
  4985. res.set_header("PRE_ROUTING", "on");
  4986. res.set_content("Routing Handler", "text/plain");
  4987. return httplib::Server::HandlerResponse::Handled;
  4988. }
  4989. return httplib::Server::HandlerResponse::Unhandled;
  4990. });
  4991. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4992. res.set_content("Error", "text/html");
  4993. });
  4994. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4995. if (req.path == "/routing_handler") {
  4996. res.set_header("POST_ROUTING", "on");
  4997. }
  4998. });
  4999. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5000. res.set_content("Hello World!\n", "text/plain");
  5001. });
  5002. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5003. auto se = detail::scope_exit([&] {
  5004. svr.stop();
  5005. thread.join();
  5006. ASSERT_FALSE(svr.is_running());
  5007. });
  5008. svr.wait_until_ready();
  5009. {
  5010. #ifdef CPPHTTPLIB_SSL_ENABLED
  5011. SSLClient cli(HOST, PORT);
  5012. cli.enable_server_certificate_verification(false);
  5013. #else
  5014. Client cli(HOST, PORT);
  5015. #endif
  5016. auto res = cli.Get("/routing_handler");
  5017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5018. EXPECT_EQ(StatusCode::OK_200, res->status);
  5019. EXPECT_EQ("Routing Handler", res->body);
  5020. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5021. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5022. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5023. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5024. }
  5025. {
  5026. #ifdef CPPHTTPLIB_SSL_ENABLED
  5027. SSLClient cli(HOST, PORT);
  5028. cli.enable_server_certificate_verification(false);
  5029. #else
  5030. Client cli(HOST, PORT);
  5031. #endif
  5032. auto res = cli.Get("/hi");
  5033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5034. EXPECT_EQ(StatusCode::OK_200, res->status);
  5035. EXPECT_EQ("Hello World!\n", res->body);
  5036. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5037. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5038. }
  5039. {
  5040. #ifdef CPPHTTPLIB_SSL_ENABLED
  5041. SSLClient cli(HOST, PORT);
  5042. cli.enable_server_certificate_verification(false);
  5043. #else
  5044. Client cli(HOST, PORT);
  5045. #endif
  5046. auto res = cli.Get("/aaa");
  5047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5048. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5049. EXPECT_EQ("Error", res->body);
  5050. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5051. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5052. }
  5053. }
  5054. TEST(RequestHandlerTest, PreRequestHandler) {
  5055. auto route_path = "/user/:user";
  5056. Server svr;
  5057. svr.Get("/hi", [](const Request &, Response &res) {
  5058. res.set_content("hi", "text/plain");
  5059. });
  5060. svr.Get(route_path, [](const Request &req, Response &res) {
  5061. res.set_content(req.path_params.at("user"), "text/plain");
  5062. });
  5063. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5064. if (req.matched_route == route_path) {
  5065. auto user = req.path_params.at("user");
  5066. if (user != "john") {
  5067. res.status = StatusCode::Forbidden_403;
  5068. res.set_content("error", "text/html");
  5069. return Server::HandlerResponse::Handled;
  5070. }
  5071. }
  5072. return Server::HandlerResponse::Unhandled;
  5073. });
  5074. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5075. auto se = detail::scope_exit([&] {
  5076. svr.stop();
  5077. thread.join();
  5078. ASSERT_FALSE(svr.is_running());
  5079. });
  5080. svr.wait_until_ready();
  5081. Client cli(HOST, PORT);
  5082. {
  5083. auto res = cli.Get("/hi");
  5084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5085. EXPECT_EQ(StatusCode::OK_200, res->status);
  5086. EXPECT_EQ("hi", res->body);
  5087. }
  5088. {
  5089. auto res = cli.Get("/user/john");
  5090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5091. EXPECT_EQ(StatusCode::OK_200, res->status);
  5092. EXPECT_EQ("john", res->body);
  5093. }
  5094. {
  5095. auto res = cli.Get("/user/invalid-user");
  5096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5097. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5098. EXPECT_EQ("error", res->body);
  5099. }
  5100. }
  5101. // The pre-request handler must run before the request body is read, so a
  5102. // rejected request never forces the server to buffer a (potentially large)
  5103. // body. Here the posted body is larger than the payload limit: if the body
  5104. // were read first the server would answer 413, but because the pre-request
  5105. // handler runs first it answers 403 and the body is never read.
  5106. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5107. Server svr;
  5108. svr.set_payload_max_length(8);
  5109. auto handler_ran = false;
  5110. svr.Post("/reject", [&](const Request &req, Response &res) {
  5111. handler_ran = true;
  5112. res.set_content(req.body, "text/plain");
  5113. });
  5114. svr.Post("/accept", [](const Request &req, Response &res) {
  5115. res.set_content(req.body, "text/plain");
  5116. });
  5117. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5118. if (req.matched_route == "/reject") {
  5119. res.status = StatusCode::Forbidden_403;
  5120. res.set_content("denied", "text/plain");
  5121. return Server::HandlerResponse::Handled;
  5122. }
  5123. return Server::HandlerResponse::Unhandled;
  5124. });
  5125. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5126. auto se = detail::scope_exit([&] {
  5127. svr.stop();
  5128. thread.join();
  5129. ASSERT_FALSE(svr.is_running());
  5130. });
  5131. svr.wait_until_ready();
  5132. Client cli(HOST, PORT);
  5133. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5134. // rejects with 403 before the body is read, so 413 is never reached.
  5135. {
  5136. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5138. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5139. EXPECT_EQ("denied", res->body);
  5140. EXPECT_FALSE(handler_ran);
  5141. }
  5142. // An approved route still reads the body and enforces the payload limit.
  5143. {
  5144. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5146. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5147. }
  5148. }
  5149. TEST(UserDataTest, BasicOperations) {
  5150. httplib::UserData ud;
  5151. // Initially empty
  5152. EXPECT_FALSE(ud.has("key"));
  5153. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5154. // set and get
  5155. ud.set("key", 42);
  5156. EXPECT_TRUE(ud.has("key"));
  5157. auto *p = ud.get<int>("key");
  5158. ASSERT_NE(nullptr, p);
  5159. EXPECT_EQ(42, *p);
  5160. // Type mismatch → nullptr
  5161. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5162. // Overwrite with different type
  5163. ud.set("key", std::string("hello"));
  5164. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5165. auto *s = ud.get<std::string>("key");
  5166. ASSERT_NE(nullptr, s);
  5167. EXPECT_EQ("hello", *s);
  5168. // erase
  5169. ud.erase("key");
  5170. EXPECT_FALSE(ud.has("key"));
  5171. // clear
  5172. ud.set("a", 1);
  5173. ud.set("b", 2);
  5174. ud.clear();
  5175. EXPECT_FALSE(ud.has("a"));
  5176. EXPECT_FALSE(ud.has("b"));
  5177. }
  5178. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5179. struct AuthCtx {
  5180. std::string user_id;
  5181. };
  5182. Server svr;
  5183. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5184. res.user_data.set("auth", AuthCtx{"alice"});
  5185. return Server::HandlerResponse::Unhandled;
  5186. });
  5187. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5188. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5189. ASSERT_NE(nullptr, ctx);
  5190. res.set_content("Hello " + ctx->user_id, "text/plain");
  5191. });
  5192. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5193. auto se = detail::scope_exit([&] {
  5194. svr.stop();
  5195. thread.join();
  5196. ASSERT_FALSE(svr.is_running());
  5197. });
  5198. svr.wait_until_ready();
  5199. Client cli(HOST, PORT);
  5200. auto res = cli.Get("/me");
  5201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5202. EXPECT_EQ(StatusCode::OK_200, res->status);
  5203. EXPECT_EQ("Hello alice", res->body);
  5204. }
  5205. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5206. struct RoleCtx {
  5207. std::string role;
  5208. };
  5209. Server svr;
  5210. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5211. res.user_data.set("role", RoleCtx{"admin"});
  5212. return Server::HandlerResponse::Unhandled;
  5213. });
  5214. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5215. auto *ctx = res.user_data.get<RoleCtx>("role");
  5216. ASSERT_NE(nullptr, ctx);
  5217. res.set_content(ctx->role, "text/plain");
  5218. });
  5219. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5220. auto se = detail::scope_exit([&] {
  5221. svr.stop();
  5222. thread.join();
  5223. ASSERT_FALSE(svr.is_running());
  5224. });
  5225. svr.wait_until_ready();
  5226. Client cli(HOST, PORT);
  5227. auto res = cli.Get("/role");
  5228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5229. EXPECT_EQ(StatusCode::OK_200, res->status);
  5230. EXPECT_EQ("admin", res->body);
  5231. }
  5232. TEST(InvalidFormatTest, StatusCode) {
  5233. Server svr;
  5234. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5235. res.set_content("Hello World!\n", "text/plain");
  5236. res.status = 9999; // Status should be a three-digit code...
  5237. });
  5238. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5239. auto se = detail::scope_exit([&] {
  5240. svr.stop();
  5241. thread.join();
  5242. ASSERT_FALSE(svr.is_running());
  5243. });
  5244. svr.wait_until_ready();
  5245. {
  5246. Client cli(HOST, PORT);
  5247. auto res = cli.Get("/hi");
  5248. ASSERT_FALSE(res);
  5249. }
  5250. }
  5251. TEST(URLFragmentTest, WithFragment) {
  5252. Server svr;
  5253. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5254. EXPECT_TRUE(req.target == "/hi");
  5255. });
  5256. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5257. auto se = detail::scope_exit([&] {
  5258. svr.stop();
  5259. thread.join();
  5260. ASSERT_FALSE(svr.is_running());
  5261. });
  5262. svr.wait_until_ready();
  5263. {
  5264. Client cli(HOST, PORT);
  5265. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5266. EXPECT_TRUE(res);
  5267. EXPECT_EQ(StatusCode::OK_200, res->status);
  5268. res = cli.Get("/hi%23key1=val1=key2=val2");
  5269. EXPECT_TRUE(res);
  5270. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5271. }
  5272. }
  5273. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5274. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5275. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5276. Server svr;
  5277. std::vector<std::string> targets;
  5278. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5279. targets.push_back(req.target);
  5280. });
  5281. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5282. auto se = detail::scope_exit([&] {
  5283. svr.stop();
  5284. thread.join();
  5285. ASSERT_FALSE(svr.is_running());
  5286. });
  5287. svr.wait_until_ready();
  5288. Client cli(HOST, PORT);
  5289. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5290. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5291. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5292. // A '?' after the '#' belongs to the fragment, not to the query.
  5293. Request req;
  5294. req.method = "GET";
  5295. req.path = "/hi#f?x=1";
  5296. req.params.emplace("a", "1");
  5297. Response res;
  5298. auto error = Error::Success;
  5299. EXPECT_TRUE(cli.send(req, res, error));
  5300. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5301. "/hi?a=1"}),
  5302. targets);
  5303. }
  5304. TEST(HeaderWriter, SetHeaderWriter) {
  5305. Server svr;
  5306. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5307. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5308. return detail::write_headers(strm, hdrs);
  5309. });
  5310. svr.Get("/hi", [](const Request &req, Response &res) {
  5311. auto it = req.headers.find("CustomClientHeader");
  5312. EXPECT_TRUE(it != req.headers.end());
  5313. EXPECT_EQ(it->second, "CustomClientValue");
  5314. res.set_content("Hello World!\n", "text/plain");
  5315. });
  5316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5317. auto se = detail::scope_exit([&] {
  5318. svr.stop();
  5319. thread.join();
  5320. ASSERT_FALSE(svr.is_running());
  5321. });
  5322. svr.wait_until_ready();
  5323. {
  5324. Client cli(HOST, PORT);
  5325. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5326. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5327. return detail::write_headers(strm, hdrs);
  5328. });
  5329. auto res = cli.Get("/hi");
  5330. EXPECT_TRUE(res);
  5331. EXPECT_EQ(StatusCode::OK_200, res->status);
  5332. auto it = res->headers.find("CustomServerHeader");
  5333. EXPECT_TRUE(it != res->headers.end());
  5334. EXPECT_EQ(it->second, "CustomServerValue");
  5335. }
  5336. }
  5337. class ServerTest : public ::testing::Test {
  5338. protected:
  5339. ServerTest()
  5340. : cli_(HOST, PORT)
  5341. #ifdef CPPHTTPLIB_SSL_ENABLED
  5342. ,
  5343. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5344. #endif
  5345. {
  5346. #ifdef CPPHTTPLIB_SSL_ENABLED
  5347. cli_.enable_server_certificate_verification(false);
  5348. #endif
  5349. // Allow LARGE_DATA (100MB) responses
  5350. cli_.set_payload_max_length(200 * 1024 * 1024);
  5351. }
  5352. virtual void SetUp() {
  5353. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5354. svr_.set_payload_max_length(200 * 1024 * 1024);
  5355. svr_.set_mount_point("/", "./www");
  5356. svr_.set_mount_point("/mount", "./www2");
  5357. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5358. svr_.Get("/hi",
  5359. [&](const Request & /*req*/, Response &res) {
  5360. res.set_content("Hello World!", "text/plain");
  5361. })
  5362. .Get("/file_content",
  5363. [&](const Request & /*req*/, Response &res) {
  5364. res.set_file_content("./www/dir/test.html");
  5365. })
  5366. .Get("/file_content_with_content_type",
  5367. [&](const Request & /*req*/, Response &res) {
  5368. res.set_file_content("./www/file", "text/plain");
  5369. })
  5370. .Get("/invalid_file_content",
  5371. [&](const Request & /*req*/, Response &res) {
  5372. res.set_file_content("./www/dir/invalid_file_path");
  5373. })
  5374. .Get("/http_response_splitting",
  5375. [&](const Request & /*req*/, Response &res) {
  5376. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5377. EXPECT_EQ(0U, res.headers.size());
  5378. EXPECT_FALSE(res.has_header("a"));
  5379. res.set_header("a", "1\nSet-Cookie: a=1");
  5380. EXPECT_EQ(0U, res.headers.size());
  5381. EXPECT_FALSE(res.has_header("a"));
  5382. res.set_header("a", "1\rSet-Cookie: a=1");
  5383. EXPECT_EQ(0U, res.headers.size());
  5384. EXPECT_FALSE(res.has_header("a"));
  5385. res.set_header("a\r\nb", "0");
  5386. EXPECT_EQ(0U, res.headers.size());
  5387. EXPECT_FALSE(res.has_header("a"));
  5388. res.set_header("a\rb", "0");
  5389. EXPECT_EQ(0U, res.headers.size());
  5390. EXPECT_FALSE(res.has_header("a"));
  5391. res.set_header("a\nb", "0");
  5392. EXPECT_EQ(0U, res.headers.size());
  5393. EXPECT_FALSE(res.has_header("a"));
  5394. res.set_redirect("1\r\nSet-Cookie: a=1");
  5395. EXPECT_EQ(0U, res.headers.size());
  5396. EXPECT_FALSE(res.has_header("Location"));
  5397. })
  5398. .Get("/slow",
  5399. [&](const Request & /*req*/, Response &res) {
  5400. std::this_thread::sleep_for(std::chrono::seconds(4));
  5401. res.set_content("slow", "text/plain");
  5402. })
  5403. #if 0
  5404. .Post("/slowpost",
  5405. [&](const Request & /*req*/, Response &res) {
  5406. std::this_thread::sleep_for(std::chrono::seconds(2));
  5407. res.set_content("slow", "text/plain");
  5408. })
  5409. #endif
  5410. .Get("/remote_addr",
  5411. [&](const Request &req, Response &res) {
  5412. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5413. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5414. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5415. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5416. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5417. #endif
  5418. res.set_content(req.remote_addr, "text/plain");
  5419. })
  5420. .Get("/local_addr",
  5421. [&](const Request &req, Response &res) {
  5422. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5423. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5424. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5425. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5426. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5427. #endif
  5428. auto local_addr = req.local_addr;
  5429. auto local_port = std::to_string(req.local_port);
  5430. res.set_content(local_addr.append(":").append(local_port),
  5431. "text/plain");
  5432. })
  5433. .Get("/endwith%",
  5434. [&](const Request & /*req*/, Response &res) {
  5435. res.set_content("Hello World!", "text/plain");
  5436. })
  5437. .Get("/a\\+\\+b",
  5438. [&](const Request &req, Response &res) {
  5439. ASSERT_TRUE(req.has_param("a +b"));
  5440. auto val = req.get_param_value("a +b");
  5441. res.set_content(val, "text/plain");
  5442. })
  5443. .Get("/", [&](const Request & /*req*/,
  5444. Response &res) { res.set_redirect("/hi"); })
  5445. .Post("/1",
  5446. [](const Request & /*req*/, Response &res) {
  5447. res.set_redirect("/2", StatusCode::SeeOther_303);
  5448. })
  5449. .Get("/2",
  5450. [](const Request & /*req*/, Response &res) {
  5451. res.set_content("redirected.", "text/plain");
  5452. res.status = StatusCode::OK_200;
  5453. })
  5454. .Post("/person",
  5455. [&](const Request &req, Response &res) {
  5456. if (req.has_param("name") && req.has_param("note")) {
  5457. persons_[req.get_param_value("name")] =
  5458. req.get_param_value("note");
  5459. } else {
  5460. res.status = StatusCode::BadRequest_400;
  5461. }
  5462. })
  5463. .Put("/person",
  5464. [&](const Request &req, Response &res) {
  5465. if (req.has_param("name") && req.has_param("note")) {
  5466. persons_[req.get_param_value("name")] =
  5467. req.get_param_value("note");
  5468. } else {
  5469. res.status = StatusCode::BadRequest_400;
  5470. }
  5471. })
  5472. .Get("/person/(.*)",
  5473. [&](const Request &req, Response &res) {
  5474. string name = req.matches[1];
  5475. if (persons_.find(name) != persons_.end()) {
  5476. auto note = persons_[name];
  5477. res.set_content(note, "text/plain");
  5478. } else {
  5479. res.status = StatusCode::NotFound_404;
  5480. }
  5481. })
  5482. .Delete("/person",
  5483. [&](const Request &req, Response &res) {
  5484. if (req.has_param("name")) {
  5485. string name = req.get_param_value("name");
  5486. if (persons_.find(name) != persons_.end()) {
  5487. persons_.erase(name);
  5488. res.set_content("DELETED", "text/plain");
  5489. } else {
  5490. res.status = StatusCode::NotFound_404;
  5491. }
  5492. } else {
  5493. res.status = StatusCode::BadRequest_400;
  5494. }
  5495. })
  5496. .Post("/x-www-form-urlencoded-json",
  5497. [&](const Request &req, Response &res) {
  5498. auto json = req.get_param_value("json");
  5499. ASSERT_EQ(JSON_DATA, json);
  5500. res.set_content(json, "appliation/json");
  5501. res.status = StatusCode::OK_200;
  5502. })
  5503. .Get("/streamed-chunked",
  5504. [&](const Request & /*req*/, Response &res) {
  5505. res.set_chunked_content_provider(
  5506. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5507. sink.os << "123";
  5508. sink.os << "456";
  5509. sink.os << "789";
  5510. sink.done();
  5511. return true;
  5512. });
  5513. })
  5514. .Get("/streamed-chunked-with-prohibited-trailer",
  5515. [&](const Request & /*req*/, Response &res) {
  5516. auto i = new int(0);
  5517. // Declare both a prohibited trailer (Content-Length) and an
  5518. // allowed one
  5519. res.set_header("Trailer", "Content-Length, X-Allowed");
  5520. res.set_chunked_content_provider(
  5521. "text/plain",
  5522. [i](size_t /*offset*/, DataSink &sink) {
  5523. switch (*i) {
  5524. case 0: sink.os << "123"; break;
  5525. case 1: sink.os << "456"; break;
  5526. case 2: sink.os << "789"; break;
  5527. case 3: {
  5528. sink.done_with_trailer(
  5529. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5530. } break;
  5531. }
  5532. (*i)++;
  5533. return true;
  5534. },
  5535. [i](bool success) {
  5536. EXPECT_TRUE(success);
  5537. delete i;
  5538. });
  5539. })
  5540. .Get("/streamed-chunked2",
  5541. [&](const Request & /*req*/, Response &res) {
  5542. auto i = new int(0);
  5543. res.set_chunked_content_provider(
  5544. "text/plain",
  5545. [i](size_t /*offset*/, DataSink &sink) {
  5546. switch (*i) {
  5547. case 0: sink.os << "123"; break;
  5548. case 1: sink.os << "456"; break;
  5549. case 2: sink.os << "789"; break;
  5550. case 3: sink.done(); break;
  5551. }
  5552. (*i)++;
  5553. return true;
  5554. },
  5555. [i](bool success) {
  5556. EXPECT_TRUE(success);
  5557. delete i;
  5558. });
  5559. })
  5560. .Get("/streamed-chunked-with-trailer",
  5561. [&](const Request & /*req*/, Response &res) {
  5562. auto i = new int(0);
  5563. res.set_header("Trailer", "Dummy1, Dummy2");
  5564. res.set_chunked_content_provider(
  5565. "text/plain",
  5566. [i](size_t /*offset*/, DataSink &sink) {
  5567. switch (*i) {
  5568. case 0: sink.os << "123"; break;
  5569. case 1: sink.os << "456"; break;
  5570. case 2: sink.os << "789"; break;
  5571. case 3: {
  5572. sink.done_with_trailer(
  5573. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5574. } break;
  5575. }
  5576. (*i)++;
  5577. return true;
  5578. },
  5579. [i](bool success) {
  5580. EXPECT_TRUE(success);
  5581. delete i;
  5582. });
  5583. })
  5584. .Get("/streamed",
  5585. [&](const Request & /*req*/, Response &res) {
  5586. res.set_content_provider(
  5587. 6, "text/plain",
  5588. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5589. sink.os << (offset < 3 ? "a" : "b");
  5590. return true;
  5591. });
  5592. })
  5593. .Get("/streamed-without-length",
  5594. [&](const Request & /*req*/, Response &res) {
  5595. auto data = new std::string("abcdefg");
  5596. res.set_content_provider(
  5597. "text/plain",
  5598. [data](size_t offset, DataSink &sink) {
  5599. if (offset < data->size()) {
  5600. sink.os << data->substr(offset);
  5601. }
  5602. sink.done();
  5603. return true;
  5604. },
  5605. [data](bool success) {
  5606. EXPECT_TRUE(success);
  5607. delete data;
  5608. });
  5609. })
  5610. .Get("/streamed-with-range",
  5611. [&](const Request &req, Response &res) {
  5612. auto data = new std::string("abcdefg");
  5613. // An explicit status keeps the server from picking the 206 it
  5614. // would otherwise choose for a ranged request, so the response
  5615. // is not a partial representation.
  5616. auto status = req.get_param_value("status");
  5617. if (status == "200") {
  5618. res.status = StatusCode::OK_200;
  5619. } else if (status == "403") {
  5620. res.status = StatusCode::Forbidden_403;
  5621. }
  5622. res.set_content_provider(
  5623. data->size(), "text/plain",
  5624. [data](size_t offset, size_t length, DataSink &sink) {
  5625. size_t DATA_CHUNK_SIZE = 4;
  5626. const auto &d = *data;
  5627. auto out_len =
  5628. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5629. auto ret =
  5630. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5631. EXPECT_TRUE(ret);
  5632. return true;
  5633. },
  5634. [data, &req](bool success) {
  5635. EXPECT_EQ(success, !req.has_param("error"));
  5636. delete data;
  5637. });
  5638. })
  5639. .Get("/streamed-cancel",
  5640. [&](const Request & /*req*/, Response &res) {
  5641. res.set_content_provider(
  5642. size_t(-1), "text/plain",
  5643. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5644. sink.os << "data_chunk";
  5645. return true;
  5646. });
  5647. })
  5648. .Get("/regex-with-delimiter",
  5649. [&](const Request &req, Response & /*res*/) {
  5650. ASSERT_TRUE(req.has_param("key"));
  5651. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5652. })
  5653. .Get("/with-range",
  5654. [&](const Request & /*req*/, Response &res) {
  5655. res.set_content("abcdefg", "text/plain");
  5656. })
  5657. .Get("/test-start-time",
  5658. [&](const Request &req, Response & /*res*/) {
  5659. EXPECT_NE(req.start_time_,
  5660. std::chrono::steady_clock::time_point::min());
  5661. })
  5662. .Get("/with-range-customized-response",
  5663. [&](const Request & /*req*/, Response &res) {
  5664. res.status = StatusCode::BadRequest_400;
  5665. res.set_content(JSON_DATA, "application/json");
  5666. })
  5667. .Post("/chunked",
  5668. [&](const Request &req, Response & /*res*/) {
  5669. EXPECT_EQ(req.body, "dechunked post body");
  5670. })
  5671. .Post("/large-chunked",
  5672. [&](const Request &req, Response & /*res*/) {
  5673. std::string expected(6 * 30 * 1024u, 'a');
  5674. EXPECT_EQ(req.body, expected);
  5675. })
  5676. .Post("/multipart",
  5677. [&](const Request &req, Response & /*res*/) {
  5678. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5679. req.form.get_field_count("text2") +
  5680. req.form.get_field_count("file3") +
  5681. req.form.get_field_count("file4"));
  5682. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5683. req.form.get_file_count("file2"));
  5684. ASSERT_TRUE(!req.form.has_file("???"));
  5685. ASSERT_TRUE(!req.form.has_field("???"));
  5686. ASSERT_TRUE(req.body.empty());
  5687. {
  5688. const auto &text = req.form.get_field("text1");
  5689. EXPECT_EQ("text default", text);
  5690. }
  5691. {
  5692. const auto &text = req.form.get_field("text2");
  5693. EXPECT_EQ("aωb", text);
  5694. }
  5695. {
  5696. const auto &file = req.form.get_file("file1");
  5697. EXPECT_EQ("hello.txt", file.filename);
  5698. EXPECT_EQ("text/plain", file.content_type);
  5699. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5700. }
  5701. {
  5702. const auto &file = req.form.get_file("file2");
  5703. EXPECT_EQ("world.json", file.filename);
  5704. EXPECT_EQ("application/json", file.content_type);
  5705. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5706. }
  5707. {
  5708. const auto &text = req.form.get_field("file3");
  5709. EXPECT_EQ(0u, text.size());
  5710. }
  5711. {
  5712. const auto &text = req.form.get_field("file4");
  5713. EXPECT_EQ(0u, text.size());
  5714. }
  5715. })
  5716. .Post("/multipart/multi_file_values",
  5717. [&](const Request &req, Response & /*res*/) {
  5718. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5719. req.form.get_field_count("multi_text1"));
  5720. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5721. ASSERT_TRUE(!req.form.has_file("???"));
  5722. ASSERT_TRUE(!req.form.has_field("???"));
  5723. ASSERT_TRUE(req.body.empty());
  5724. {
  5725. const auto &text = req.form.get_field("text");
  5726. EXPECT_EQ("default text", text);
  5727. }
  5728. {
  5729. const auto &text1_values = req.form.get_fields("multi_text1");
  5730. EXPECT_EQ(2u, text1_values.size());
  5731. EXPECT_EQ("aaaaa", text1_values[0]);
  5732. EXPECT_EQ("bbbbb", text1_values[1]);
  5733. }
  5734. {
  5735. const auto &file1_values = req.form.get_files("multi_file1");
  5736. EXPECT_EQ(2u, file1_values.size());
  5737. auto file1 = file1_values[0];
  5738. EXPECT_EQ(file1.filename, "hello.txt");
  5739. EXPECT_EQ(file1.content_type, "text/plain");
  5740. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5741. auto file2 = file1_values[1];
  5742. EXPECT_EQ(file2.filename, "world.json");
  5743. EXPECT_EQ(file2.content_type, "application/json");
  5744. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5745. }
  5746. })
  5747. .Post("/empty",
  5748. [&](const Request &req, Response &res) {
  5749. EXPECT_EQ(req.body, "");
  5750. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5751. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5752. res.set_content("empty", "text/plain");
  5753. })
  5754. .Post("/empty-no-content-type",
  5755. [&](const Request &req, Response &res) {
  5756. EXPECT_EQ(req.body, "");
  5757. EXPECT_FALSE(req.has_header("Content-Type"));
  5758. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5759. res.set_content("empty-no-content-type", "text/plain");
  5760. })
  5761. .Post("/path-only",
  5762. [&](const Request &req, Response &res) {
  5763. EXPECT_EQ(req.body, "");
  5764. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5765. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5766. res.set_content("path-only", "text/plain");
  5767. })
  5768. .Post("/path-headers-only",
  5769. [&](const Request &req, Response &res) {
  5770. EXPECT_EQ(req.body, "");
  5771. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5772. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5773. EXPECT_EQ("world", req.get_header_value("hello"));
  5774. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5775. res.set_content("path-headers-only", "text/plain");
  5776. })
  5777. .Post("/post-large",
  5778. [&](const Request &req, Response &res) {
  5779. EXPECT_EQ(req.body, LARGE_DATA);
  5780. res.set_content(req.body, "text/plain");
  5781. })
  5782. .Post("/post-loopback",
  5783. [&](const Request &, Response &res,
  5784. ContentReader const &content_reader) {
  5785. std::string body;
  5786. content_reader([&](const char *data, size_t data_length) {
  5787. body.append(data, data_length);
  5788. return true;
  5789. });
  5790. res.set_content(body, "text/plain");
  5791. })
  5792. .Put("/put-loopback",
  5793. [&](const Request &, Response &res,
  5794. ContentReader const &content_reader) {
  5795. std::string body;
  5796. content_reader([&](const char *data, size_t data_length) {
  5797. body.append(data, data_length);
  5798. return true;
  5799. });
  5800. res.set_content(body, "text/plain");
  5801. })
  5802. .Patch("/patch-loopback",
  5803. [&](const Request &, Response &res,
  5804. ContentReader const &content_reader) {
  5805. std::string body;
  5806. content_reader([&](const char *data, size_t data_length) {
  5807. body.append(data, data_length);
  5808. return true;
  5809. });
  5810. res.set_content(body, "text/plain");
  5811. })
  5812. .Put("/empty-no-content-type",
  5813. [&](const Request &req, Response &res) {
  5814. EXPECT_EQ(req.body, "");
  5815. EXPECT_FALSE(req.has_header("Content-Type"));
  5816. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5817. res.set_content("empty-no-content-type", "text/plain");
  5818. })
  5819. .Put("/put",
  5820. [&](const Request &req, Response &res) {
  5821. EXPECT_EQ(req.body, "PUT");
  5822. res.set_content(req.body, "text/plain");
  5823. })
  5824. .Put("/put-large",
  5825. [&](const Request &req, Response &res) {
  5826. EXPECT_EQ(req.body, LARGE_DATA);
  5827. res.set_content(req.body, "text/plain");
  5828. })
  5829. .Patch("/patch",
  5830. [&](const Request &req, Response &res) {
  5831. EXPECT_EQ(req.body, "PATCH");
  5832. res.set_content(req.body, "text/plain");
  5833. })
  5834. .Delete("/delete",
  5835. [&](const Request & /*req*/, Response &res) {
  5836. res.set_content("DELETE", "text/plain");
  5837. })
  5838. .Delete("/delete-body",
  5839. [&](const Request &req, Response &res) {
  5840. EXPECT_EQ(req.body, "content");
  5841. res.set_content(req.body, "text/plain");
  5842. })
  5843. .Options(R"(\*)",
  5844. [&](const Request & /*req*/, Response &res) {
  5845. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5846. })
  5847. .CustomRoute("PROPFIND", "/dav/:id",
  5848. [&](const Request &req, Response &res) {
  5849. res.set_header("x-body-size",
  5850. std::to_string(req.body.size()));
  5851. res.set_header("x-matched-route", req.matched_route);
  5852. res.set_header("x-dav-id", req.path_params.at("id"));
  5853. res.status = StatusCode::MultiStatus_207;
  5854. res.set_content(req.body, "application/xml");
  5855. })
  5856. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5857. [&](const Request &req, Response &res) {
  5858. res.set_header("x-dav-match", req.matches[1]);
  5859. res.status = StatusCode::MultiStatus_207;
  5860. })
  5861. .CustomRoute("MKCOL", "/dav-mkcol",
  5862. [&](const Request &req, Response &res) {
  5863. EXPECT_TRUE(req.body.empty());
  5864. res.status = StatusCode::Created_201;
  5865. })
  5866. .CustomRoute(
  5867. "REPORT", "/dav-report",
  5868. [&](const Request & /*req*/, Response &res,
  5869. const ContentReader &content_reader) {
  5870. std::string body;
  5871. content_reader([&](const char *data, size_t data_length) {
  5872. body.append(data, data_length);
  5873. return true;
  5874. });
  5875. res.set_header("x-body-size", std::to_string(body.size()));
  5876. res.status = StatusCode::MultiStatus_207;
  5877. res.set_content(body, "application/xml");
  5878. })
  5879. .Get("/request-target",
  5880. [&](const Request &req, Response & /*res*/) {
  5881. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5882. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5883. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5884. })
  5885. .Get("/long-query-value",
  5886. [&](const Request &req, Response & /*res*/) {
  5887. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5888. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5889. })
  5890. .Get("/too-long-query-value",
  5891. [&](const Request &req, Response & /*res*/) {
  5892. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5893. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5894. })
  5895. .Get("/array-param",
  5896. [&](const Request &req, Response & /*res*/) {
  5897. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5898. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5899. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5900. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5901. })
  5902. .Get("/array-param-values",
  5903. [&](const Request &req, Response & /*res*/) {
  5904. auto values = req.get_param_values("array");
  5905. EXPECT_EQ(3u, values.size());
  5906. EXPECT_EQ("value1", values[0]);
  5907. EXPECT_EQ("value2", values[1]);
  5908. EXPECT_EQ("value3", values[2]);
  5909. auto empty = req.get_param_values("nonexistent");
  5910. EXPECT_TRUE(empty.empty());
  5911. })
  5912. .Post("/validate-no-multiple-headers",
  5913. [&](const Request &req, Response & /*res*/) {
  5914. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5915. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5916. })
  5917. .Post("/content_receiver",
  5918. [&](const Request &req, Response &res,
  5919. const ContentReader &content_reader) {
  5920. if (req.is_multipart_form_data()) {
  5921. std::vector<FormData> items;
  5922. content_reader(
  5923. [&](const FormData &file) {
  5924. items.push_back(file);
  5925. return true;
  5926. },
  5927. [&](const char *data, size_t data_length) {
  5928. items.back().content.append(data, data_length);
  5929. return true;
  5930. });
  5931. EXPECT_EQ(5u, items.size());
  5932. {
  5933. const auto &file = get_file_value(items, "text1");
  5934. EXPECT_TRUE(file.filename.empty());
  5935. EXPECT_EQ("text default", file.content);
  5936. }
  5937. {
  5938. const auto &file = get_file_value(items, "text2");
  5939. EXPECT_TRUE(file.filename.empty());
  5940. EXPECT_EQ("aωb", file.content);
  5941. }
  5942. {
  5943. const auto &file = get_file_value(items, "file1");
  5944. EXPECT_EQ("hello.txt", file.filename);
  5945. EXPECT_EQ("text/plain", file.content_type);
  5946. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5947. }
  5948. {
  5949. const auto &file = get_file_value(items, "file2");
  5950. EXPECT_EQ("world.json", file.filename);
  5951. EXPECT_EQ("application/json", file.content_type);
  5952. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5953. }
  5954. {
  5955. const auto &file = get_file_value(items, "file3");
  5956. EXPECT_TRUE(file.filename.empty());
  5957. EXPECT_EQ("application/octet-stream", file.content_type);
  5958. EXPECT_EQ(0u, file.content.size());
  5959. }
  5960. } else {
  5961. std::string body;
  5962. content_reader([&](const char *data, size_t data_length) {
  5963. EXPECT_EQ(7U, data_length);
  5964. body.append(data, data_length);
  5965. return true;
  5966. });
  5967. EXPECT_EQ(body, "content");
  5968. res.set_content(body, "text/plain");
  5969. }
  5970. })
  5971. .Put("/content_receiver",
  5972. [&](const Request & /*req*/, Response &res,
  5973. const ContentReader &content_reader) {
  5974. std::string body;
  5975. content_reader([&](const char *data, size_t data_length) {
  5976. body.append(data, data_length);
  5977. return true;
  5978. });
  5979. EXPECT_EQ(body, "content");
  5980. res.set_content(body, "text/plain");
  5981. })
  5982. .Patch("/content_receiver",
  5983. [&](const Request & /*req*/, Response &res,
  5984. const ContentReader &content_reader) {
  5985. std::string body;
  5986. content_reader([&](const char *data, size_t data_length) {
  5987. body.append(data, data_length);
  5988. return true;
  5989. });
  5990. EXPECT_EQ(body, "content");
  5991. res.set_content(body, "text/plain");
  5992. })
  5993. .Post("/query-string-and-body",
  5994. [&](const Request &req, Response & /*res*/) {
  5995. ASSERT_TRUE(req.has_param("key"));
  5996. EXPECT_EQ(req.get_param_value("key"), "value");
  5997. EXPECT_EQ(req.body, "content");
  5998. })
  5999. .Get("/last-request",
  6000. [&](const Request &req, Response & /*res*/) {
  6001. EXPECT_EQ("close", req.get_header_value("Connection"));
  6002. })
  6003. .Get(R"(/redirect/(\d+))",
  6004. [&](const Request &req, Response &res) {
  6005. auto num = std::stoi(req.matches[1]) + 1;
  6006. std::string url = "/redirect/" + std::to_string(num);
  6007. res.set_redirect(url);
  6008. })
  6009. .Post("/binary",
  6010. [&](const Request &req, Response &res) {
  6011. EXPECT_EQ(4U, req.body.size());
  6012. EXPECT_EQ("application/octet-stream",
  6013. req.get_header_value("Content-Type"));
  6014. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6015. res.set_content(req.body, "application/octet-stream");
  6016. })
  6017. .Put("/binary",
  6018. [&](const Request &req, Response &res) {
  6019. EXPECT_EQ(4U, req.body.size());
  6020. EXPECT_EQ("application/octet-stream",
  6021. req.get_header_value("Content-Type"));
  6022. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6023. res.set_content(req.body, "application/octet-stream");
  6024. })
  6025. .Patch("/binary",
  6026. [&](const Request &req, Response &res) {
  6027. EXPECT_EQ(4U, req.body.size());
  6028. EXPECT_EQ("application/octet-stream",
  6029. req.get_header_value("Content-Type"));
  6030. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6031. res.set_content(req.body, "application/octet-stream");
  6032. })
  6033. .Delete("/binary",
  6034. [&](const Request &req, Response &res) {
  6035. EXPECT_EQ(4U, req.body.size());
  6036. EXPECT_EQ("application/octet-stream",
  6037. req.get_header_value("Content-Type"));
  6038. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6039. res.set_content(req.body, "application/octet-stream");
  6040. })
  6041. .Get("/issue1772",
  6042. [&](const Request & /*req*/, Response &res) {
  6043. res.status = 401;
  6044. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6045. })
  6046. .Delete("/issue609",
  6047. [](const httplib::Request &, httplib::Response &res,
  6048. const httplib::ContentReader &) {
  6049. res.set_content("ok", "text/plain");
  6050. })
  6051. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6052. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6053. .Get("/compress",
  6054. [&](const Request & /*req*/, Response &res) {
  6055. res.set_content(
  6056. "12345678901234567890123456789012345678901234567890123456789"
  6057. "01234567890123456789012345678901234567890",
  6058. "text/plain");
  6059. })
  6060. .Get("/compress-with-charset",
  6061. [&](const Request & /*req*/, Response &res) {
  6062. res.set_content(
  6063. "12345678901234567890123456789012345678901234567890123456789"
  6064. "01234567890123456789012345678901234567890",
  6065. "application/json; charset=utf-8");
  6066. })
  6067. .Get("/nocompress",
  6068. [&](const Request & /*req*/, Response &res) {
  6069. res.set_content(
  6070. "12345678901234567890123456789012345678901234567890123456789"
  6071. "01234567890123456789012345678901234567890",
  6072. "application/octet-stream");
  6073. })
  6074. .Post("/compress-multipart",
  6075. [&](const Request &req, Response & /*res*/) {
  6076. EXPECT_EQ(2u, req.form.fields.size());
  6077. ASSERT_TRUE(!req.form.has_field("???"));
  6078. {
  6079. const auto &text = req.form.get_field("key1");
  6080. EXPECT_EQ("test", text);
  6081. }
  6082. {
  6083. const auto &text = req.form.get_field("key2");
  6084. EXPECT_EQ("--abcdefg123", text);
  6085. }
  6086. })
  6087. #endif
  6088. ;
  6089. persons_["john"] = "programmer";
  6090. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6091. svr_.wait_until_ready();
  6092. }
  6093. virtual void TearDown() {
  6094. svr_.stop();
  6095. if (!request_threads_.empty()) {
  6096. std::this_thread::sleep_for(std::chrono::seconds(1));
  6097. for (auto &t : request_threads_) {
  6098. t.join();
  6099. }
  6100. }
  6101. t_.join();
  6102. }
  6103. map<string, string> persons_;
  6104. #ifdef CPPHTTPLIB_SSL_ENABLED
  6105. SSLClient cli_;
  6106. SSLServer svr_;
  6107. #else
  6108. Client cli_;
  6109. Server svr_;
  6110. #endif
  6111. thread t_;
  6112. std::vector<thread> request_threads_;
  6113. };
  6114. TEST_F(ServerTest, GetMethod200) {
  6115. auto res = cli_.Get("/hi");
  6116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6117. EXPECT_EQ("HTTP/1.1", res->version);
  6118. EXPECT_EQ(StatusCode::OK_200, res->status);
  6119. EXPECT_EQ("OK", res->reason);
  6120. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6121. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6122. EXPECT_EQ("Hello World!", res->body);
  6123. }
  6124. TEST_F(ServerTest, GetEmptyFile) {
  6125. auto res = cli_.Get("/empty_file");
  6126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6127. EXPECT_EQ(StatusCode::OK_200, res->status);
  6128. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6129. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6130. EXPECT_EQ("", res->body);
  6131. }
  6132. TEST_F(ServerTest, GetFileContent) {
  6133. auto res = cli_.Get("/file_content");
  6134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6135. EXPECT_EQ(StatusCode::OK_200, res->status);
  6136. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6137. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6138. EXPECT_EQ("test.html", res->body);
  6139. }
  6140. TEST_F(ServerTest, GetFileContentWithRange) {
  6141. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6143. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6144. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6145. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6146. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6147. EXPECT_EQ("est", res->body);
  6148. }
  6149. TEST_F(ServerTest, GetFileContentWithContentType) {
  6150. auto res = cli_.Get("/file_content_with_content_type");
  6151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6152. EXPECT_EQ(StatusCode::OK_200, res->status);
  6153. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6154. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6155. EXPECT_EQ("file\n", res->body);
  6156. }
  6157. TEST_F(ServerTest, GetInvalidFileContent) {
  6158. auto res = cli_.Get("/invalid_file_content");
  6159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6160. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6161. }
  6162. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6163. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6165. EXPECT_EQ("HTTP/1.1", res->version);
  6166. EXPECT_EQ(StatusCode::OK_200, res->status);
  6167. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6168. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6169. EXPECT_EQ("Hello World!", res->body);
  6170. }
  6171. TEST_F(ServerTest, GetMethod302) {
  6172. auto res = cli_.Get("/");
  6173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6174. EXPECT_EQ(StatusCode::Found_302, res->status);
  6175. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6176. }
  6177. TEST_F(ServerTest, GetMethod302Redirect) {
  6178. cli_.set_follow_location(true);
  6179. auto res = cli_.Get("/");
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. EXPECT_EQ(StatusCode::OK_200, res->status);
  6182. EXPECT_EQ("Hello World!", res->body);
  6183. EXPECT_EQ("/hi", res->location);
  6184. }
  6185. TEST_F(ServerTest, GetMethod404) {
  6186. auto res = cli_.Get("/invalid");
  6187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6188. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6189. }
  6190. TEST_F(ServerTest, HeadMethod200) {
  6191. auto res = cli_.Head("/hi");
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. EXPECT_EQ(StatusCode::OK_200, res->status);
  6194. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6195. EXPECT_TRUE(res->body.empty());
  6196. }
  6197. TEST_F(ServerTest, HeadMethod200Static) {
  6198. auto res = cli_.Head("/mount/dir/index.html");
  6199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6200. EXPECT_EQ(StatusCode::OK_200, res->status);
  6201. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6202. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6203. EXPECT_TRUE(res->body.empty());
  6204. }
  6205. TEST_F(ServerTest, HeadMethod404) {
  6206. auto res = cli_.Head("/invalid");
  6207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6208. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6209. EXPECT_TRUE(res->body.empty());
  6210. }
  6211. TEST_F(ServerTest, GetMethodPersonJohn) {
  6212. auto res = cli_.Get("/person/john");
  6213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6214. EXPECT_EQ(StatusCode::OK_200, res->status);
  6215. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6216. EXPECT_EQ("programmer", res->body);
  6217. }
  6218. TEST_F(ServerTest, PostMethod1) {
  6219. auto res = cli_.Get("/person/john1");
  6220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6221. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6222. res = cli_.Post("/person", "name=john1&note=coder",
  6223. "application/x-www-form-urlencoded");
  6224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6225. ASSERT_EQ(StatusCode::OK_200, res->status);
  6226. res = cli_.Get("/person/john1");
  6227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6228. ASSERT_EQ(StatusCode::OK_200, res->status);
  6229. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6230. ASSERT_EQ("coder", res->body);
  6231. }
  6232. TEST_F(ServerTest, PostMethod2) {
  6233. auto res = cli_.Get("/person/john2");
  6234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6235. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6236. Params params;
  6237. params.emplace("name", "john2");
  6238. params.emplace("note", "coder");
  6239. res = cli_.Post("/person", params);
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. ASSERT_EQ(StatusCode::OK_200, res->status);
  6242. res = cli_.Get("/person/john2");
  6243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6244. ASSERT_EQ(StatusCode::OK_200, res->status);
  6245. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6246. ASSERT_EQ("coder", res->body);
  6247. }
  6248. TEST_F(ServerTest, PutMethod3) {
  6249. auto res = cli_.Get("/person/john3");
  6250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6251. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6252. Params params;
  6253. params.emplace("name", "john3");
  6254. params.emplace("note", "coder");
  6255. res = cli_.Put("/person", params);
  6256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6257. ASSERT_EQ(StatusCode::OK_200, res->status);
  6258. res = cli_.Get("/person/john3");
  6259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6260. ASSERT_EQ(StatusCode::OK_200, res->status);
  6261. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6262. ASSERT_EQ("coder", res->body);
  6263. }
  6264. TEST_F(ServerTest, DeleteMethod1) {
  6265. auto res = cli_.Get("/person/john4");
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6268. Params params;
  6269. params.emplace("name", "john4");
  6270. params.emplace("note", "coder");
  6271. res = cli_.Post("/person", params);
  6272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6273. ASSERT_EQ(StatusCode::OK_200, res->status);
  6274. res = cli_.Get("/person/john4");
  6275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6276. ASSERT_EQ(StatusCode::OK_200, res->status);
  6277. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6278. ASSERT_EQ("coder", res->body);
  6279. Params delete_params;
  6280. delete_params.emplace("name", "john4");
  6281. res = cli_.Delete("/person", delete_params);
  6282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6283. ASSERT_EQ(StatusCode::OK_200, res->status);
  6284. ASSERT_EQ("DELETED", res->body);
  6285. res = cli_.Get("/person/john4");
  6286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6287. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6288. }
  6289. TEST_F(ServerTest, DeleteMethod2) {
  6290. auto res = cli_.Get("/person/john5");
  6291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6292. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6293. Params params;
  6294. params.emplace("name", "john5");
  6295. params.emplace("note", "developer");
  6296. res = cli_.Post("/person", params);
  6297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6298. ASSERT_EQ(StatusCode::OK_200, res->status);
  6299. res = cli_.Get("/person/john5");
  6300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6301. ASSERT_EQ(StatusCode::OK_200, res->status);
  6302. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6303. ASSERT_EQ("developer", res->body);
  6304. Params delete_params;
  6305. delete_params.emplace("name", "john5");
  6306. Headers headers;
  6307. headers.emplace("Custom-Header", "test-value");
  6308. res = cli_.Delete("/person", headers, delete_params);
  6309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6310. ASSERT_EQ(StatusCode::OK_200, res->status);
  6311. ASSERT_EQ("DELETED", res->body);
  6312. res = cli_.Get("/person/john5");
  6313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6314. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6315. }
  6316. TEST_F(ServerTest, DeleteMethod3) {
  6317. auto res = cli_.Get("/person/john6");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6320. Params params;
  6321. params.emplace("name", "john6");
  6322. params.emplace("note", "tester");
  6323. res = cli_.Post("/person", params);
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. ASSERT_EQ(StatusCode::OK_200, res->status);
  6326. res = cli_.Get("/person/john6");
  6327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6328. ASSERT_EQ(StatusCode::OK_200, res->status);
  6329. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6330. ASSERT_EQ("tester", res->body);
  6331. Params delete_params;
  6332. delete_params.emplace("name", "john6");
  6333. Headers headers;
  6334. headers.emplace("Custom-Header", "test-value");
  6335. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6337. ASSERT_EQ(StatusCode::OK_200, res->status);
  6338. ASSERT_EQ("DELETED", res->body);
  6339. res = cli_.Get("/person/john6");
  6340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6341. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6342. }
  6343. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6344. Params params;
  6345. params.emplace("json", JSON_DATA);
  6346. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. ASSERT_EQ(StatusCode::OK_200, res->status);
  6349. ASSERT_EQ(JSON_DATA, res->body);
  6350. }
  6351. TEST_F(ServerTest, PostEmptyContent) {
  6352. auto res = cli_.Post("/empty", "", "text/plain");
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. ASSERT_EQ(StatusCode::OK_200, res->status);
  6355. ASSERT_EQ("empty", res->body);
  6356. }
  6357. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6358. auto res = cli_.Post("/empty-no-content-type");
  6359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6360. ASSERT_EQ(StatusCode::OK_200, res->status);
  6361. ASSERT_EQ("empty-no-content-type", res->body);
  6362. }
  6363. TEST_F(ServerTest, PostPathOnly) {
  6364. auto res = cli_.Post("/path-only");
  6365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6366. ASSERT_EQ(StatusCode::OK_200, res->status);
  6367. ASSERT_EQ("path-only", res->body);
  6368. }
  6369. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6370. auto res = cli_.Post("/path-headers-only",
  6371. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6373. ASSERT_EQ(StatusCode::OK_200, res->status);
  6374. ASSERT_EQ("path-headers-only", res->body);
  6375. }
  6376. TEST_F(ServerTest, PostLarge) {
  6377. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6379. ASSERT_EQ(StatusCode::OK_200, res->status);
  6380. EXPECT_EQ(LARGE_DATA, res->body);
  6381. }
  6382. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6383. auto res = cli_.Put("/empty-no-content-type");
  6384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6385. ASSERT_EQ(StatusCode::OK_200, res->status);
  6386. ASSERT_EQ("empty-no-content-type", res->body);
  6387. }
  6388. TEST_F(ServerTest, GetMethodDir) {
  6389. auto res = cli_.Get("/dir/");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6393. auto body = R"(<html>
  6394. <head>
  6395. </head>
  6396. <body>
  6397. <a href="/dir/test.html">Test</a>
  6398. <a href="/hi">hi</a>
  6399. </body>
  6400. </html>
  6401. )";
  6402. EXPECT_EQ(body, res->body);
  6403. }
  6404. TEST_F(ServerTest, GetMethodDirTest) {
  6405. auto res = cli_.Get("/dir/test.html");
  6406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6407. EXPECT_EQ(StatusCode::OK_200, res->status);
  6408. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6409. EXPECT_EQ("test.html", res->body);
  6410. }
  6411. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6412. auto res = cli_.Get("/dir/../dir/test.html");
  6413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6414. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6415. }
  6416. TEST_F(ServerTest, GetMethodInvalidPath) {
  6417. auto res = cli_.Get("/dir/../test.html");
  6418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6420. }
  6421. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6422. auto res = cli_.Get("/../www/dir/test.html");
  6423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6425. }
  6426. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6427. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6430. }
  6431. TEST_F(ServerTest, GetMethodDirMountTest) {
  6432. auto res = cli_.Get("/mount/dir/test.html");
  6433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6434. EXPECT_EQ(StatusCode::OK_200, res->status);
  6435. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6436. EXPECT_EQ("test.html", res->body);
  6437. }
  6438. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6439. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6442. }
  6443. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6444. auto res = cli_.Get("/mount/dir/../test.html");
  6445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6446. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6447. }
  6448. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6449. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6451. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6452. }
  6453. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6454. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6457. }
  6458. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6459. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6462. }
  6463. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6464. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6466. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6467. }
  6468. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6469. auto res = cli_.Get("/mount/dir");
  6470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6471. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6472. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6473. }
  6474. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6475. auto res = cli_.Get("//dir");
  6476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6477. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6478. EXPECT_FALSE(res->has_header("Location"));
  6479. }
  6480. TEST_F(ServerTest, PostMethod303) {
  6481. auto res = cli_.Post("/1", "body", "text/plain");
  6482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6483. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6484. EXPECT_EQ("/2", res->get_header_value("Location"));
  6485. }
  6486. TEST_F(ServerTest, PostMethod303Redirect) {
  6487. cli_.set_follow_location(true);
  6488. auto res = cli_.Post("/1", "body", "text/plain");
  6489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6490. EXPECT_EQ(StatusCode::OK_200, res->status);
  6491. EXPECT_EQ("redirected.", res->body);
  6492. EXPECT_EQ("/2", res->location);
  6493. }
  6494. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6495. auto res = cli_.Get("/dir/test.abcde");
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6499. EXPECT_EQ("abcde", res->body);
  6500. }
  6501. TEST_F(ServerTest, StaticFileRange) {
  6502. auto res =
  6503. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6505. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6506. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6507. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6508. EXPECT_EQ(true, res->has_header("Content-Range"));
  6509. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6510. EXPECT_EQ(std::string("cd"), res->body);
  6511. }
  6512. TEST_F(ServerTest, StaticFileRanges) {
  6513. auto res = cli_.Get("/dir/test.abcde",
  6514. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6517. EXPECT_TRUE(
  6518. res->get_header_value("Content-Type")
  6519. .find(
  6520. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6521. 0);
  6522. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6523. }
  6524. TEST_F(ServerTest, StaticFileRangeHead) {
  6525. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6528. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6529. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6530. EXPECT_EQ(true, res->has_header("Content-Range"));
  6531. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6532. }
  6533. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6534. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6536. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6537. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6538. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6539. EXPECT_EQ(true, res->has_header("Content-Range"));
  6540. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6541. res->get_header_value("Content-Range"));
  6542. EXPECT_EQ("LAST\n", res->body);
  6543. }
  6544. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6545. auto res =
  6546. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6548. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6550. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6551. EXPECT_EQ(true, res->has_header("Content-Range"));
  6552. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6553. }
  6554. TEST_F(ServerTest, StaticFileBigFile) {
  6555. auto res = cli_.Get("/dir/1MB.txt");
  6556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6557. EXPECT_EQ(StatusCode::OK_200, res->status);
  6558. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6559. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6560. }
  6561. TEST_F(ServerTest, InvalidBaseDirMount) {
  6562. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6563. }
  6564. TEST_F(ServerTest, Binary) {
  6565. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6566. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6567. "application/octet-stream");
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. ASSERT_EQ(StatusCode::OK_200, res->status);
  6570. ASSERT_EQ(4U, res->body.size());
  6571. res = cli_.Put("/binary", binary.data(), binary.size(),
  6572. "application/octet-stream");
  6573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6574. ASSERT_EQ(StatusCode::OK_200, res->status);
  6575. ASSERT_EQ(4U, res->body.size());
  6576. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6577. "application/octet-stream");
  6578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6579. ASSERT_EQ(StatusCode::OK_200, res->status);
  6580. ASSERT_EQ(4U, res->body.size());
  6581. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6582. "application/octet-stream");
  6583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6584. ASSERT_EQ(StatusCode::OK_200, res->status);
  6585. ASSERT_EQ(4U, res->body.size());
  6586. }
  6587. TEST_F(ServerTest, BinaryString) {
  6588. auto binary = std::string("\x00\x01\x02\x03", 4);
  6589. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6591. ASSERT_EQ(StatusCode::OK_200, res->status);
  6592. ASSERT_EQ(4U, res->body.size());
  6593. res = cli_.Put("/binary", binary, "application/octet-stream");
  6594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6595. ASSERT_EQ(StatusCode::OK_200, res->status);
  6596. ASSERT_EQ(4U, res->body.size());
  6597. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6599. ASSERT_EQ(StatusCode::OK_200, res->status);
  6600. ASSERT_EQ(4U, res->body.size());
  6601. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. ASSERT_EQ(StatusCode::OK_200, res->status);
  6604. ASSERT_EQ(4U, res->body.size());
  6605. }
  6606. TEST_F(ServerTest, EmptyRequest) {
  6607. auto res = cli_.Get("");
  6608. ASSERT_TRUE(!res);
  6609. EXPECT_EQ(Error::Connection, res.error());
  6610. }
  6611. TEST_F(ServerTest, LongRequest) {
  6612. std::string request;
  6613. for (size_t i = 0; i < 545; i++) {
  6614. request += "/TooLongRequest";
  6615. }
  6616. request += "OK";
  6617. auto res = cli_.Get(request.c_str());
  6618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6619. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6620. }
  6621. TEST_F(ServerTest, TooLongRequest) {
  6622. std::string request;
  6623. for (size_t i = 0; i < 546; i++) {
  6624. request += "/TooLongRequest";
  6625. }
  6626. request += "_NG";
  6627. auto start = std::chrono::high_resolution_clock::now();
  6628. cli_.set_keep_alive(true);
  6629. auto res = cli_.Get(request.c_str());
  6630. auto end = std::chrono::high_resolution_clock::now();
  6631. auto elapsed =
  6632. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6633. .count();
  6634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6635. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6636. EXPECT_LE(elapsed, 1000);
  6637. EXPECT_EQ("close", res->get_header_value("Connection"));
  6638. EXPECT_FALSE(cli_.is_socket_open());
  6639. }
  6640. TEST_F(ServerTest, AlmostTooLongRequest) {
  6641. // test for #2046 - URI length check shouldn't include other content on req
  6642. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6643. // leading /, space, HTTP/1.1)
  6644. std::string request =
  6645. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6646. auto res = cli_.Get(request.c_str());
  6647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6648. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6649. }
  6650. TEST_F(ServerTest, LongHeader) {
  6651. Request req;
  6652. req.method = "GET";
  6653. req.path = "/hi";
  6654. std::string host_and_port;
  6655. host_and_port += HOST;
  6656. host_and_port += ":";
  6657. host_and_port += std::to_string(PORT);
  6658. req.headers.emplace("Host", host_and_port.c_str());
  6659. req.headers.emplace("Accept", "*/*");
  6660. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6661. req.headers.emplace(
  6662. "Header-Name",
  6663. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6664. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6665. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6666. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6667. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6691. "@@@@@@@@@@@@@@@@");
  6692. auto res = std::make_shared<Response>();
  6693. auto error = Error::Success;
  6694. auto ret = cli_.send(req, *res, error);
  6695. ASSERT_TRUE(ret);
  6696. EXPECT_EQ(StatusCode::OK_200, res->status);
  6697. }
  6698. TEST_F(ServerTest, LongQueryValue) {
  6699. auto start = std::chrono::high_resolution_clock::now();
  6700. cli_.set_keep_alive(true);
  6701. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6702. auto end = std::chrono::high_resolution_clock::now();
  6703. auto elapsed =
  6704. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6705. .count();
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6708. EXPECT_LE(elapsed, 1000);
  6709. EXPECT_EQ("close", res->get_header_value("Connection"));
  6710. EXPECT_FALSE(cli_.is_socket_open());
  6711. }
  6712. TEST_F(ServerTest, TooLongQueryValue) {
  6713. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6714. ASSERT_FALSE(res);
  6715. EXPECT_EQ(Error::Read, res.error());
  6716. }
  6717. TEST_F(ServerTest, TooLongHeader) {
  6718. Request req;
  6719. req.method = "GET";
  6720. req.path = "/hi";
  6721. std::string host_and_port;
  6722. host_and_port += HOST;
  6723. host_and_port += ":";
  6724. host_and_port += std::to_string(PORT);
  6725. req.headers.emplace("Host", host_and_port.c_str());
  6726. req.headers.emplace("Accept", "*/*");
  6727. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6728. req.headers.emplace(
  6729. "Header-Name",
  6730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6758. "@@@@@@@@@@@@@@@@@");
  6759. auto res = std::make_shared<Response>();
  6760. auto error = Error::Success;
  6761. auto ret = cli_.send(req, *res, error);
  6762. ASSERT_TRUE(ret);
  6763. EXPECT_EQ(StatusCode::OK_200, res->status);
  6764. }
  6765. TEST_F(ServerTest, HeaderCountAtLimit) {
  6766. // Test with headers just under the 100 limit
  6767. httplib::Headers headers;
  6768. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6769. // This should keep us just under the 100 header limit
  6770. for (int i = 0; i < 95; i++) {
  6771. std::string name = "X-Test-Header-" + std::to_string(i);
  6772. std::string value = "value" + std::to_string(i);
  6773. headers.emplace(name, value);
  6774. }
  6775. // This should work fine as we're under the limit
  6776. auto res = cli_.Get("/hi", headers);
  6777. EXPECT_TRUE(res);
  6778. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6779. }
  6780. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6781. // Test with many headers to exceed the 100 limit
  6782. httplib::Headers headers;
  6783. // Add 150 headers to definitely exceed the 100 limit
  6784. for (int i = 0; i < 150; i++) {
  6785. std::string name = "X-Test-Header-" + std::to_string(i);
  6786. std::string value = "value" + std::to_string(i);
  6787. headers.emplace(name, value);
  6788. }
  6789. // This should fail due to exceeding header count limit
  6790. cli_.set_keep_alive(true);
  6791. auto res = cli_.Get("/hi", headers);
  6792. // The server should respond with 400 Bad Request
  6793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6794. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6795. EXPECT_EQ("close", res->get_header_value("Connection"));
  6796. EXPECT_FALSE(cli_.is_socket_open());
  6797. }
  6798. TEST_F(ServerTest, PercentEncoding) {
  6799. auto res = cli_.Get("/e%6edwith%");
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, PercentEncodingUnicode) {
  6804. auto res = cli_.Get("/e%u006edwith%");
  6805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6806. EXPECT_EQ(StatusCode::OK_200, res->status);
  6807. }
  6808. TEST_F(ServerTest, InvalidPercentEncoding) {
  6809. auto res = cli_.Get("/%endwith%");
  6810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6811. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6812. }
  6813. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6814. auto res = cli_.Get("/%uendwith%");
  6815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6817. }
  6818. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6819. auto res = cli_.Get("/hello?aaa=bbb%");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6822. }
  6823. TEST_F(ServerTest, PlusSignEncoding) {
  6824. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ(StatusCode::OK_200, res->status);
  6827. EXPECT_EQ("a +b", res->body);
  6828. }
  6829. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6830. // This test simulates a potential DoS attack using many headers
  6831. // to verify our security fix prevents memory exhaustion
  6832. httplib::Headers attack_headers;
  6833. // Attempt to add many headers like an attacker would (200 headers to far
  6834. // exceed limit)
  6835. for (int i = 0; i < 200; i++) {
  6836. std::string name = "X-Attack-Header-" + std::to_string(i);
  6837. std::string value = "attack_payload_" + std::to_string(i);
  6838. attack_headers.emplace(name, value);
  6839. }
  6840. // Try to POST with excessive headers
  6841. cli_.set_keep_alive(true);
  6842. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6843. // Should either fail or return 400 Bad Request due to security limit
  6844. if (res) {
  6845. // If we get a response, it should be 400 Bad Request
  6846. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6847. EXPECT_EQ("close", res->get_header_value("Connection"));
  6848. }
  6849. EXPECT_FALSE(cli_.is_socket_open());
  6850. }
  6851. TEST_F(ServerTest, MultipartFormData) {
  6852. UploadFormDataItems items = {
  6853. {"text1", "text default", "", ""},
  6854. {"text2", "aωb", "", ""},
  6855. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6856. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6857. {"file3", "", "", "application/octet-stream"},
  6858. {"file4", "", "", " application/json tmp-string "}};
  6859. auto res = cli_.Post("/multipart", items);
  6860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6861. EXPECT_EQ(StatusCode::OK_200, res->status);
  6862. }
  6863. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6864. UploadFormDataItems items = {
  6865. {"text", "default text", "", ""},
  6866. {"multi_text1", "aaaaa", "", ""},
  6867. {"multi_text1", "bbbbb", "", ""},
  6868. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6869. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6870. "application/json"},
  6871. };
  6872. auto res = cli_.Post("/multipart/multi_file_values", items);
  6873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6874. EXPECT_EQ(StatusCode::OK_200, res->status);
  6875. }
  6876. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6877. auto res = cli_.Get("/hi");
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::OK_200, res->status);
  6880. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6881. EXPECT_EQ("Hello World!", res->body);
  6882. }
  6883. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6884. Request req;
  6885. req.method = "POST";
  6886. req.path = "/chunked";
  6887. std::string host_and_port;
  6888. host_and_port += HOST;
  6889. host_and_port += ":";
  6890. host_and_port += std::to_string(PORT);
  6891. req.headers.emplace("Host", host_and_port.c_str());
  6892. req.headers.emplace("Accept", "*/*");
  6893. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6894. req.headers.emplace("Content-Type", "text/plain");
  6895. req.headers.emplace("Content-Length", "0");
  6896. req.headers.emplace(
  6897. "Transfer-Encoding",
  6898. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6899. // Client does not chunk, so make a chunked body manually.
  6900. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6901. auto res = std::make_shared<Response>();
  6902. auto error = Error::Success;
  6903. auto ret = cli_.send(req, *res, error);
  6904. ASSERT_TRUE(ret);
  6905. EXPECT_EQ(StatusCode::OK_200, res->status);
  6906. }
  6907. template <typename ClientT>
  6908. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6909. int expected_status) {
  6910. Request req;
  6911. req.method = "POST";
  6912. req.path = "/chunked";
  6913. std::string host_and_port;
  6914. host_and_port += HOST;
  6915. host_and_port += ":";
  6916. host_and_port += std::to_string(PORT);
  6917. req.headers.emplace("Host", host_and_port.c_str());
  6918. req.headers.emplace("Content-Length", "0");
  6919. req.headers.emplace("Transfer-Encoding", "chunked");
  6920. req.body = body;
  6921. auto res = std::make_shared<Response>();
  6922. auto error = Error::Success;
  6923. ASSERT_TRUE(cli.send(req, *res, error));
  6924. EXPECT_EQ(expected_status, res->status);
  6925. }
  6926. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6927. // rather than treat them as valid lengths.
  6928. template <typename ClientT>
  6929. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6930. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6931. }
  6932. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6933. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6934. }
  6935. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6936. expect_chunked_body_rejected(
  6937. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6938. }
  6939. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6940. // chunk-size line carries no CR, LF or other control character ahead of its
  6941. // terminator. Such a line must be refused rather than read as extension text.
  6942. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6943. expect_chunked_body_rejected(
  6944. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6945. }
  6946. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6947. expect_chunked_body_rejected(
  6948. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6949. }
  6950. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6951. expect_chunked_body_rejected(
  6952. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6953. }
  6954. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6955. // The literal stays split: a hex escape consumes every hex digit that
  6956. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6957. expect_chunked_body_rejected(
  6958. cli_, "4;a\x01"
  6959. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6960. }
  6961. // The bytes around chunk data are no payload, so they cannot ride on the
  6962. // payload limit
  6963. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6964. // Small enough that the whole request is sent before the server turns it
  6965. // down, yet past the limit by the last chunks
  6966. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6967. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6968. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6969. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6970. SCOPED_TRACE(size_line.substr(0, 2));
  6971. std::string body;
  6972. for (auto c : std::string("dechunked post body")) {
  6973. body += size_line + "\r\n" + c + "\r\n";
  6974. }
  6975. body += "0\r\n\r\n";
  6976. expect_chunked_body_rejected(cli_, body.c_str());
  6977. }
  6978. }
  6979. TEST_F(ServerTest, AcceptsChunkExtension) {
  6980. expect_chunked_body_status(cli_,
  6981. "4;name=value\r\ndech\r\n"
  6982. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6983. "0;last\r\n\r\n",
  6984. StatusCode::OK_200);
  6985. }
  6986. TEST_F(ServerTest, GetStreamed2) {
  6987. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6990. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6991. EXPECT_EQ(true, res->has_header("Content-Range"));
  6992. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6993. EXPECT_EQ(std::string("ab"), res->body);
  6994. }
  6995. TEST_F(ServerTest, GetStreamed) {
  6996. auto res = cli_.Get("/streamed");
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ(StatusCode::OK_200, res->status);
  6999. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7000. EXPECT_EQ(std::string("aaabbb"), res->body);
  7001. }
  7002. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7003. auto res = cli_.Get("/streamed-without-length",
  7004. Headers{make_range_header({{0, -1}})});
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. EXPECT_EQ(StatusCode::OK_200, res->status);
  7007. EXPECT_EQ(false, res->has_header("Content-Length"));
  7008. EXPECT_EQ(false, res->has_header("Content-Range"));
  7009. EXPECT_EQ(std::string("abcdefg"), res->body);
  7010. }
  7011. TEST_F(ServerTest, GetStreamedWithRange1) {
  7012. auto res =
  7013. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7016. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7017. EXPECT_EQ(true, res->has_header("Content-Range"));
  7018. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7019. EXPECT_EQ(std::string("def"), res->body);
  7020. }
  7021. TEST_F(ServerTest, GetStreamedWithRange2) {
  7022. auto res =
  7023. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7026. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7027. EXPECT_EQ(true, res->has_header("Content-Range"));
  7028. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7029. EXPECT_EQ(std::string("bcdefg"), res->body);
  7030. }
  7031. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7032. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7035. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7036. EXPECT_EQ(true, res->has_header("Content-Range"));
  7037. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7038. EXPECT_EQ(std::string("efg"), res->body);
  7039. }
  7040. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7041. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7042. // the entire representation.
  7043. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7044. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7046. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7047. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7048. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7049. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7050. }
  7051. }
  7052. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7053. auto res =
  7054. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7056. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7057. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7058. EXPECT_EQ(false, res->has_header("Content-Range"));
  7059. EXPECT_EQ(0U, res->body.size());
  7060. }
  7061. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7062. // Only a 206 is served as a partial representation. Under any other status
  7063. // `apply_ranges()` reported the full content length, so the body must match
  7064. // that header, and the content provider must never be asked for an offset
  7065. // outside the representation.
  7066. auto check = [&](int status, const char *range) {
  7067. auto path =
  7068. std::string("/streamed-with-range?status=") + std::to_string(status);
  7069. auto ctx = path + " Range: " + range;
  7070. auto res = cli_.Get(path, Headers{{"Range", range}});
  7071. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7072. EXPECT_EQ(status, res->status) << ctx;
  7073. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7075. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7076. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7077. };
  7078. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7079. check(403, "bytes=3-5");
  7080. // The offset is far past the representation.
  7081. check(403, "bytes=100000-100200");
  7082. // `first_pos` is still -1 here, and the bounds asserts in
  7083. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7084. check(403, "bytes=-3");
  7085. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7086. // multipart branch would have written one that is empty.
  7087. check(403, "bytes=1-2, 4-5");
  7088. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7089. // covers the whole representation.
  7090. check(200, "bytes=3-5");
  7091. check(200, "bytes=1-2, 4-5");
  7092. }
  7093. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7094. auto res =
  7095. cli_.Get("/streamed-with-range",
  7096. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7097. "92233720368547758079223372036854775807"}});
  7098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7099. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7100. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7101. EXPECT_EQ(false, res->has_header("Content-Range"));
  7102. EXPECT_EQ(0U, res->body.size());
  7103. }
  7104. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7105. auto res = cli_.Get(
  7106. "/with-range",
  7107. Headers{{"Range",
  7108. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7109. {"Accept-Encoding", ""}});
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7112. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7113. EXPECT_EQ(true, res->has_header("Content-Range"));
  7114. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7115. EXPECT_EQ(std::string("abcdefg"), res->body);
  7116. }
  7117. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7118. auto res = cli_.Get("/with-range", Headers{
  7119. {"Range", "bytes=0-"},
  7120. {"Accept-Encoding", ""},
  7121. });
  7122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7123. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7124. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7125. EXPECT_EQ(true, res->has_header("Content-Range"));
  7126. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7127. EXPECT_EQ(std::string("abcdefg"), res->body);
  7128. }
  7129. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7130. auto res = cli_.Get("/streamed-with-range",
  7131. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7133. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7134. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7135. EXPECT_EQ(false, res->has_header("Content-Range"));
  7136. EXPECT_EQ(267U, res->body.size());
  7137. // Check that both range contents are present
  7138. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7139. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7140. // Check that Content-Range headers are present for both ranges
  7141. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7142. std::string::npos);
  7143. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7144. std::string::npos);
  7145. }
  7146. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7147. Ranges ranges;
  7148. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7149. ranges.emplace_back(0, -1);
  7150. }
  7151. auto res = cli_.Get("/streamed-with-range?error",
  7152. Headers{{make_range_header(ranges)}});
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7155. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7156. EXPECT_EQ(false, res->has_header("Content-Range"));
  7157. EXPECT_EQ(0U, res->body.size());
  7158. }
  7159. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7160. auto res = cli_.Get("/streamed-with-range",
  7161. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7164. EXPECT_EQ(5U, res->body.size());
  7165. // Check that overlapping ranges are coalesced into a single range
  7166. EXPECT_EQ("bcdef", res->body);
  7167. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7168. // Should be single range, not multipart
  7169. EXPECT_TRUE(res->has_header("Content-Range"));
  7170. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7171. }
  7172. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7173. auto res = cli_.Get("/streamed-with-range",
  7174. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7176. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7177. EXPECT_EQ(268U, res->body.size());
  7178. // Check that both range contents are present
  7179. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7180. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7181. // Check that Content-Range headers are present for both ranges
  7182. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7183. std::string::npos);
  7184. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7185. std::string::npos);
  7186. }
  7187. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7188. auto res = cli_.Get("/streamed-with-range",
  7189. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7191. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7192. EXPECT_EQ(269U, res->body.size());
  7193. // Check that both duplicate range contents are present
  7194. size_t first_abc = res->body.find("abc\r\n");
  7195. EXPECT_TRUE(first_abc != std::string::npos);
  7196. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7197. EXPECT_TRUE(second_abc != std::string::npos);
  7198. // Check that Content-Range headers are present for both ranges
  7199. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7200. EXPECT_TRUE(first_range != std::string::npos);
  7201. size_t second_range =
  7202. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7203. EXPECT_TRUE(second_range != std::string::npos);
  7204. }
  7205. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7206. auto res =
  7207. cli_.Get("/streamed-with-range?error",
  7208. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7210. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7211. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7212. EXPECT_EQ(false, res->has_header("Content-Range"));
  7213. EXPECT_EQ(0U, res->body.size());
  7214. }
  7215. TEST_F(ServerTest, GetStreamedEndless) {
  7216. uint64_t offset = 0;
  7217. auto res = cli_.Get("/streamed-cancel",
  7218. [&](const char * /*data*/, uint64_t data_length) {
  7219. if (offset < 100) {
  7220. offset += data_length;
  7221. return true;
  7222. }
  7223. return false;
  7224. });
  7225. ASSERT_TRUE(!res);
  7226. EXPECT_EQ(Error::Canceled, res.error());
  7227. }
  7228. TEST_F(ServerTest, ClientStop) {
  7229. std::atomic_size_t count{4};
  7230. std::vector<std::thread> threads;
  7231. for (auto i = count.load(); i != 0; --i) {
  7232. threads.emplace_back([&]() {
  7233. auto res = cli_.Get("/streamed-cancel",
  7234. [&](const char *, uint64_t) { return true; });
  7235. --count;
  7236. ASSERT_TRUE(!res);
  7237. EXPECT_TRUE(res.error() == Error::Canceled ||
  7238. res.error() == Error::Read || res.error() == Error::Write);
  7239. });
  7240. }
  7241. std::this_thread::sleep_for(std::chrono::seconds(2));
  7242. while (count != 0) {
  7243. cli_.stop();
  7244. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7245. }
  7246. for (auto &t : threads) {
  7247. t.join();
  7248. }
  7249. }
  7250. TEST_F(ServerTest, GetWithRange1) {
  7251. auto res = cli_.Get("/with-range", Headers{
  7252. make_range_header({{3, 5}}),
  7253. {"Accept-Encoding", ""},
  7254. });
  7255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7256. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7257. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7258. EXPECT_EQ(true, res->has_header("Content-Range"));
  7259. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7260. EXPECT_EQ(std::string("def"), res->body);
  7261. }
  7262. TEST_F(ServerTest, GetWithRange2) {
  7263. auto res = cli_.Get("/with-range", Headers{
  7264. make_range_header({{1, -1}}),
  7265. {"Accept-Encoding", ""},
  7266. });
  7267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7268. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7269. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7270. EXPECT_EQ(true, res->has_header("Content-Range"));
  7271. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7272. EXPECT_EQ(std::string("bcdefg"), res->body);
  7273. }
  7274. TEST_F(ServerTest, GetWithRange3) {
  7275. auto res = cli_.Get("/with-range", Headers{
  7276. make_range_header({{0, 0}}),
  7277. {"Accept-Encoding", ""},
  7278. });
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7281. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7282. EXPECT_EQ(true, res->has_header("Content-Range"));
  7283. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7284. EXPECT_EQ(std::string("a"), res->body);
  7285. }
  7286. TEST_F(ServerTest, GetWithRange4) {
  7287. auto res = cli_.Get("/with-range", Headers{
  7288. make_range_header({{-1, 2}}),
  7289. {"Accept-Encoding", ""},
  7290. });
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7293. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7294. EXPECT_EQ(true, res->has_header("Content-Range"));
  7295. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7296. EXPECT_EQ(std::string("fg"), res->body);
  7297. }
  7298. TEST_F(ServerTest, GetWithRange5) {
  7299. auto res = cli_.Get("/with-range", Headers{
  7300. make_range_header({{0, 5}}),
  7301. {"Accept-Encoding", ""},
  7302. });
  7303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7305. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7306. EXPECT_EQ(true, res->has_header("Content-Range"));
  7307. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7308. EXPECT_EQ(std::string("abcdef"), res->body);
  7309. }
  7310. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7311. auto res =
  7312. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7314. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7315. }
  7316. TEST_F(ServerTest, GetWithRangeMultipart) {
  7317. auto res =
  7318. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7320. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7321. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7322. EXPECT_EQ(false, res->has_header("Content-Range"));
  7323. EXPECT_EQ(267U, res->body.size());
  7324. }
  7325. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7326. auto res = cli_.Get("/with-range",
  7327. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7329. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7330. }
  7331. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7332. auto res = cli_.Get("/with-range-customized-response",
  7333. Headers{{make_range_header({{1, 2}})}});
  7334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7335. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7336. EXPECT_EQ(true, res->has_header("Content-Length"));
  7337. EXPECT_EQ(false, res->has_header("Content-Range"));
  7338. EXPECT_EQ(JSON_DATA, res->body);
  7339. }
  7340. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7341. auto res = cli_.Get("/with-range-customized-response",
  7342. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7344. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7345. EXPECT_EQ(true, res->has_header("Content-Length"));
  7346. EXPECT_EQ(false, res->has_header("Content-Range"));
  7347. EXPECT_EQ(JSON_DATA, res->body);
  7348. }
  7349. TEST_F(ServerTest, Issue1772) {
  7350. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7352. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7353. }
  7354. TEST_F(ServerTest, Issue609) {
  7355. auto res = cli_.Delete("/issue609");
  7356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7357. EXPECT_EQ(StatusCode::OK_200, res->status);
  7358. EXPECT_EQ(std::string("ok"), res->body);
  7359. }
  7360. TEST_F(ServerTest, GetStreamedChunked) {
  7361. auto res = cli_.Get("/streamed-chunked");
  7362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7363. EXPECT_EQ(StatusCode::OK_200, res->status);
  7364. EXPECT_EQ(std::string("123456789"), res->body);
  7365. }
  7366. TEST_F(ServerTest, GetStreamedChunked2) {
  7367. auto res = cli_.Get("/streamed-chunked2");
  7368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7369. EXPECT_EQ(StatusCode::OK_200, res->status);
  7370. EXPECT_EQ(std::string("123456789"), res->body);
  7371. }
  7372. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7373. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7375. EXPECT_EQ(StatusCode::OK_200, res->status);
  7376. EXPECT_EQ(std::string("123456789"), res->body);
  7377. EXPECT_TRUE(res->has_header("Trailer"));
  7378. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7379. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7380. // Trailers are now stored separately from headers (security fix)
  7381. EXPECT_EQ(2U, res->trailers.size());
  7382. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7383. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7384. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7385. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7386. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7387. // Verify trailers are NOT in headers (security verification)
  7388. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7389. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7390. }
  7391. TEST_F(ServerTest, LargeChunkedPost) {
  7392. Request req;
  7393. req.method = "POST";
  7394. req.path = "/large-chunked";
  7395. std::string host_and_port;
  7396. host_and_port += HOST;
  7397. host_and_port += ":";
  7398. host_and_port += std::to_string(PORT);
  7399. req.headers.emplace("Host", host_and_port.c_str());
  7400. req.headers.emplace("Accept", "*/*");
  7401. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7402. req.headers.emplace("Content-Type", "text/plain");
  7403. req.headers.emplace("Content-Length", "0");
  7404. req.headers.emplace("Transfer-Encoding", "chunked");
  7405. std::string long_string(30 * 1024u, 'a');
  7406. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7407. // Attempt to make a large enough post to exceed OS buffers, to test that
  7408. // the server handles short reads if the full chunk data isn't available.
  7409. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7410. auto res = std::make_shared<Response>();
  7411. auto error = Error::Success;
  7412. auto ret = cli_.send(req, *res, error);
  7413. ASSERT_TRUE(ret);
  7414. EXPECT_EQ(StatusCode::OK_200, res->status);
  7415. }
  7416. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7417. auto res = cli_.Get("/remote_addr");
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ(StatusCode::OK_200, res->status);
  7420. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7421. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7422. }
  7423. TEST_F(ServerTest, GetMethodLocalAddr) {
  7424. auto res = cli_.Get("/local_addr");
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7428. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7429. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7430. }
  7431. TEST_F(ServerTest, HTTPResponseSplitting) {
  7432. auto res = cli_.Get("/http_response_splitting");
  7433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7434. EXPECT_EQ(StatusCode::OK_200, res->status);
  7435. }
  7436. TEST_F(ServerTest, SlowRequest) {
  7437. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7438. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7439. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7440. }
  7441. #if 0
  7442. TEST_F(ServerTest, SlowPost) {
  7443. char buffer[64 * 1024];
  7444. memset(buffer, 0x42, sizeof(buffer));
  7445. auto res = cli_.Post(
  7446. "/slowpost", 64 * 1024 * 1024,
  7447. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7448. auto ret = sink.write(buffer, sizeof(buffer));
  7449. EXPECT_TRUE(ret);
  7450. return true;
  7451. },
  7452. "text/plain");
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ(StatusCode::OK_200, res->status);
  7455. }
  7456. TEST_F(ServerTest, SlowPostFail) {
  7457. char buffer[64 * 1024];
  7458. memset(buffer, 0x42, sizeof(buffer));
  7459. cli_.set_write_timeout(std::chrono::seconds(0));
  7460. auto res = cli_.Post(
  7461. "/slowpost", 64 * 1024 * 1024,
  7462. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7463. sink.write(buffer, sizeof(buffer));
  7464. return true;
  7465. },
  7466. "text/plain");
  7467. ASSERT_TRUE(!res);
  7468. EXPECT_EQ(Error::Write, res.error());
  7469. }
  7470. #endif
  7471. TEST_F(ServerTest, Put) {
  7472. auto res = cli_.Put("/put", "PUT", "text/plain");
  7473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7474. EXPECT_EQ(StatusCode::OK_200, res->status);
  7475. EXPECT_EQ("PUT", res->body);
  7476. }
  7477. TEST_F(ServerTest, PutWithContentProvider) {
  7478. auto res = cli_.Put(
  7479. "/put", 3,
  7480. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7481. sink.os << "PUT";
  7482. return true;
  7483. },
  7484. "text/plain");
  7485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7486. EXPECT_EQ(StatusCode::OK_200, res->status);
  7487. EXPECT_EQ("PUT", res->body);
  7488. }
  7489. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7490. auto res = cli_.Post(
  7491. "/post", 42,
  7492. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7493. return false;
  7494. },
  7495. "text/plain");
  7496. ASSERT_TRUE(!res);
  7497. EXPECT_EQ(Error::Canceled, res.error());
  7498. }
  7499. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7500. auto res = cli_.Put(
  7501. "/put",
  7502. [](size_t /*offset*/, DataSink &sink) {
  7503. sink.os << "PUT";
  7504. sink.done();
  7505. return true;
  7506. },
  7507. "text/plain");
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ(StatusCode::OK_200, res->status);
  7510. EXPECT_EQ("PUT", res->body);
  7511. }
  7512. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7513. auto res = cli_.Post(
  7514. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7515. "text/plain");
  7516. ASSERT_TRUE(!res);
  7517. EXPECT_EQ(Error::Canceled, res.error());
  7518. }
  7519. TEST_F(ServerTest, PostLoopBack) {
  7520. std::string body;
  7521. auto res = cli_.Post(
  7522. "/post-loopback", 9,
  7523. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7524. EXPECT_EQ(9u, length);
  7525. sink.write("123", 3);
  7526. sink.write("456", 3);
  7527. sink.write("789", 3);
  7528. return true;
  7529. },
  7530. "text/plain",
  7531. [&body](const char *data, size_t data_length) {
  7532. body.append(data, data_length);
  7533. return true;
  7534. });
  7535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. EXPECT_EQ("123456789", body);
  7538. }
  7539. TEST_F(ServerTest, PutLoopBack) {
  7540. std::string body;
  7541. auto res = cli_.Put(
  7542. "/put-loopback", 9,
  7543. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7544. EXPECT_EQ(9u, length);
  7545. sink.write("123", 3);
  7546. sink.write("456", 3);
  7547. sink.write("789", 3);
  7548. return true;
  7549. },
  7550. "text/plain",
  7551. [&body](const char *data, size_t data_length) {
  7552. body.append(data, data_length);
  7553. return true;
  7554. });
  7555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7556. EXPECT_EQ(StatusCode::OK_200, res->status);
  7557. EXPECT_EQ("123456789", body);
  7558. }
  7559. TEST_F(ServerTest, PatchLoopBack) {
  7560. std::string body;
  7561. auto res = cli_.Patch(
  7562. "/patch-loopback", 9,
  7563. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7564. EXPECT_EQ(9u, length);
  7565. sink.write("123", 3);
  7566. sink.write("456", 3);
  7567. sink.write("789", 3);
  7568. return true;
  7569. },
  7570. "text/plain",
  7571. [&body](const char *data, size_t data_length) {
  7572. body.append(data, data_length);
  7573. return true;
  7574. });
  7575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7576. EXPECT_EQ(StatusCode::OK_200, res->status);
  7577. EXPECT_EQ("123456789", body);
  7578. }
  7579. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7580. std::string body;
  7581. auto res = cli_.Post(
  7582. "/post-loopback",
  7583. [](size_t /*offset*/, DataSink &sink) {
  7584. sink.write("123", 3);
  7585. sink.write("456", 3);
  7586. sink.write("789", 3);
  7587. sink.done();
  7588. return true;
  7589. },
  7590. "text/plain",
  7591. [&body](const char *data, size_t data_length) {
  7592. body.append(data, data_length);
  7593. return true;
  7594. });
  7595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7596. EXPECT_EQ(StatusCode::OK_200, res->status);
  7597. EXPECT_EQ("123456789", body);
  7598. }
  7599. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7600. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7601. cli_.set_compress(true);
  7602. auto res = cli_.Put(
  7603. "/put", 3,
  7604. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7605. sink.os << "PUT";
  7606. return true;
  7607. },
  7608. "text/plain");
  7609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7610. EXPECT_EQ(StatusCode::OK_200, res->status);
  7611. EXPECT_EQ("PUT", res->body);
  7612. }
  7613. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7614. cli_.set_compress(true);
  7615. auto res = cli_.Post(
  7616. "/post", 42,
  7617. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7618. return false;
  7619. },
  7620. "text/plain");
  7621. ASSERT_TRUE(!res);
  7622. EXPECT_EQ(Error::Canceled, res.error());
  7623. }
  7624. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7625. cli_.set_compress(true);
  7626. auto res = cli_.Put(
  7627. "/put",
  7628. [](size_t /*offset*/, DataSink &sink) {
  7629. sink.os << "PUT";
  7630. sink.done();
  7631. return true;
  7632. },
  7633. "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, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7639. cli_.set_compress(true);
  7640. auto res = cli_.Post(
  7641. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7642. "text/plain");
  7643. ASSERT_TRUE(!res);
  7644. EXPECT_EQ(Error::Canceled, res.error());
  7645. }
  7646. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7647. cli_.set_compress(true);
  7648. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. EXPECT_EQ(StatusCode::OK_200, res->status);
  7651. EXPECT_EQ(LARGE_DATA, res->body);
  7652. }
  7653. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7654. #ifdef CPPHTTPLIB_SSL_ENABLED
  7655. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7656. Client cli(s.c_str());
  7657. cli.enable_server_certificate_verification(false);
  7658. #else
  7659. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7660. Client cli(s.c_str());
  7661. #endif
  7662. cli.set_compress(true);
  7663. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7665. EXPECT_EQ(StatusCode::OK_200, res->status);
  7666. EXPECT_EQ(LARGE_DATA, res->body);
  7667. // The compressed size should be less than a 10th of the original. May vary
  7668. // depending on the zlib library.
  7669. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7670. static_cast<uint64_t>(10 * 1024 * 1024));
  7671. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7672. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7673. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7674. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7675. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7676. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7677. #endif
  7678. }
  7679. TEST_F(ServerTest, PutContentWithDeflate) {
  7680. cli_.set_compress(false);
  7681. Headers headers;
  7682. headers.emplace("Content-Encoding", "deflate");
  7683. // PUT in deflate format:
  7684. auto res = cli_.Put("/put", headers,
  7685. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7687. EXPECT_EQ(StatusCode::OK_200, res->status);
  7688. EXPECT_EQ("PUT", res->body);
  7689. }
  7690. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7691. Headers headers;
  7692. headers.emplace("Accept-Encoding", "gzip, deflate");
  7693. auto res = cli_.Get("/streamed-chunked", headers);
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::OK_200, res->status);
  7696. EXPECT_EQ(std::string("123456789"), res->body);
  7697. }
  7698. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7699. Headers headers;
  7700. headers.emplace("Accept-Encoding", "gzip, deflate");
  7701. auto res = cli_.Get("/streamed-chunked2", headers);
  7702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7703. EXPECT_EQ(StatusCode::OK_200, res->status);
  7704. EXPECT_EQ(std::string("123456789"), res->body);
  7705. }
  7706. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7707. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7709. EXPECT_EQ(StatusCode::OK_200, res->status);
  7710. }
  7711. TEST(GzipDecompressor, ChunkedDecompression) {
  7712. std::string data;
  7713. for (size_t i = 0; i < 32 * 1024; ++i) {
  7714. data.push_back(static_cast<char>('a' + i % 26));
  7715. }
  7716. std::string compressed_data;
  7717. {
  7718. httplib::detail::gzip_compressor compressor;
  7719. bool result = compressor.compress(
  7720. data.data(), data.size(),
  7721. /*last=*/true,
  7722. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7723. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7724. compressed_data_size);
  7725. return true;
  7726. });
  7727. ASSERT_TRUE(result);
  7728. }
  7729. std::string decompressed_data;
  7730. {
  7731. httplib::detail::gzip_decompressor decompressor;
  7732. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7733. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7734. size_t chunk_size = 130;
  7735. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7736. chunk_begin += chunk_size) {
  7737. size_t current_chunk_size =
  7738. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7739. bool result = decompressor.decompress(
  7740. compressed_data.data() + chunk_begin, current_chunk_size,
  7741. [&](const char *decompressed_data_chunk,
  7742. size_t decompressed_data_chunk_size) {
  7743. decompressed_data.insert(decompressed_data.size(),
  7744. decompressed_data_chunk,
  7745. decompressed_data_chunk_size);
  7746. return true;
  7747. });
  7748. ASSERT_TRUE(result);
  7749. }
  7750. }
  7751. ASSERT_EQ(data, decompressed_data);
  7752. }
  7753. TEST(GzipDecompressor, DeflateDecompression) {
  7754. std::string original_text = "Raw deflate without gzip";
  7755. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7756. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7757. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7758. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7759. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7760. std::string decompressed_data;
  7761. {
  7762. httplib::detail::gzip_decompressor decompressor;
  7763. bool result = decompressor.decompress(
  7764. compressed_data.data(), compressed_data.size(),
  7765. [&](const char *decompressed_data_chunk,
  7766. size_t decompressed_data_chunk_size) {
  7767. decompressed_data.insert(decompressed_data.size(),
  7768. decompressed_data_chunk,
  7769. decompressed_data_chunk_size);
  7770. return true;
  7771. });
  7772. ASSERT_TRUE(result);
  7773. }
  7774. ASSERT_EQ(original_text, decompressed_data);
  7775. }
  7776. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7777. std::string original_text = "Raw deflate without gzip";
  7778. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7779. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7780. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7781. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7782. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7783. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7784. std::string decompressed_data;
  7785. {
  7786. httplib::detail::gzip_decompressor decompressor;
  7787. bool result = decompressor.decompress(
  7788. compressed_data.data(), compressed_data.size(),
  7789. [&](const char *decompressed_data_chunk,
  7790. size_t decompressed_data_chunk_size) {
  7791. decompressed_data.insert(decompressed_data.size(),
  7792. decompressed_data_chunk,
  7793. decompressed_data_chunk_size);
  7794. return true;
  7795. });
  7796. ASSERT_TRUE(result);
  7797. }
  7798. ASSERT_EQ(original_text, decompressed_data);
  7799. }
  7800. #endif
  7801. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7802. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7803. Headers headers;
  7804. headers.emplace("Accept-Encoding", "br");
  7805. auto res = cli_.Get("/streamed-chunked", headers);
  7806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7807. EXPECT_EQ(StatusCode::OK_200, res->status);
  7808. EXPECT_EQ(std::string("123456789"), res->body);
  7809. }
  7810. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7811. Headers headers;
  7812. headers.emplace("Accept-Encoding", "br");
  7813. auto res = cli_.Get("/streamed-chunked2", headers);
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::OK_200, res->status);
  7816. EXPECT_EQ(std::string("123456789"), res->body);
  7817. }
  7818. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7819. cli_.set_compress(true);
  7820. auto res = cli_.Put(
  7821. "/put", 3,
  7822. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7823. sink.os << "PUT";
  7824. return true;
  7825. },
  7826. "text/plain");
  7827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7828. EXPECT_EQ(StatusCode::OK_200, res->status);
  7829. EXPECT_EQ("PUT", res->body);
  7830. }
  7831. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7832. cli_.set_compress(true);
  7833. auto res = cli_.Put(
  7834. "/put",
  7835. [](size_t /*offset*/, DataSink &sink) {
  7836. sink.os << "PUT";
  7837. sink.done();
  7838. return true;
  7839. },
  7840. "text/plain");
  7841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7842. EXPECT_EQ(StatusCode::OK_200, res->status);
  7843. EXPECT_EQ("PUT", res->body);
  7844. }
  7845. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7846. cli_.set_compress(true);
  7847. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7849. EXPECT_EQ(StatusCode::OK_200, res->status);
  7850. EXPECT_EQ(LARGE_DATA, res->body);
  7851. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7852. }
  7853. #endif
  7854. TEST_F(ServerTest, Patch) {
  7855. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7857. EXPECT_EQ(StatusCode::OK_200, res->status);
  7858. EXPECT_EQ("PATCH", res->body);
  7859. }
  7860. TEST_F(ServerTest, Delete) {
  7861. auto res = cli_.Delete("/delete");
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::OK_200, res->status);
  7864. EXPECT_EQ("DELETE", res->body);
  7865. }
  7866. TEST_F(ServerTest, DeleteContentReceiver) {
  7867. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7869. EXPECT_EQ(StatusCode::OK_200, res->status);
  7870. EXPECT_EQ("content", res->body);
  7871. }
  7872. TEST_F(ServerTest, Options) {
  7873. auto res = cli_.Options("*");
  7874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7875. EXPECT_EQ(StatusCode::OK_200, res->status);
  7876. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7877. EXPECT_TRUE(res->body.empty());
  7878. }
  7879. TEST_F(ServerTest, URL) {
  7880. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ(StatusCode::OK_200, res->status);
  7883. }
  7884. TEST_F(ServerTest, ArrayParam) {
  7885. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST_F(ServerTest, ArrayParamValues) {
  7890. auto res =
  7891. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7893. EXPECT_EQ(StatusCode::OK_200, res->status);
  7894. }
  7895. TEST_F(ServerTest, NoMultipleHeaders) {
  7896. Headers headers = {{"Content-Length", "5"}};
  7897. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7898. "text/plain");
  7899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7900. EXPECT_EQ(StatusCode::OK_200, res->status);
  7901. }
  7902. TEST_F(ServerTest, PostContentReceiver) {
  7903. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7905. ASSERT_EQ(StatusCode::OK_200, res->status);
  7906. ASSERT_EQ("content", res->body);
  7907. }
  7908. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7909. UploadFormDataItems items = {
  7910. {"text1", "text default", "", ""},
  7911. {"text2", "aωb", "", ""},
  7912. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7913. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7914. {"file3", "", "", "application/octet-stream"},
  7915. };
  7916. auto res = cli_.Post("/content_receiver", items);
  7917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7918. EXPECT_EQ(StatusCode::OK_200, res->status);
  7919. }
  7920. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7921. UploadFormDataItems items = {
  7922. {"text1", "text default", "", ""},
  7923. {"text2", "aωb", "", ""},
  7924. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7925. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7926. {"file3", "", "", "application/octet-stream"},
  7927. };
  7928. auto boundary = std::string("+++++");
  7929. std::string body;
  7930. for (const auto &item : items) {
  7931. body += "--" + boundary + "\r\n";
  7932. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7933. if (!item.filename.empty()) {
  7934. body += "; filename=\"" + item.filename + "\"";
  7935. }
  7936. body += "\r\n";
  7937. if (!item.content_type.empty()) {
  7938. body += "Content-Type: " + item.content_type + "\r\n";
  7939. }
  7940. body += "\r\n";
  7941. body += item.content + "\r\n";
  7942. }
  7943. body += "--" + boundary + "--\r\n";
  7944. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7945. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. }
  7949. TEST(MultipartFormDataTest, FieldEscaping) {
  7950. Server svr;
  7951. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7952. const ContentReader &content_reader) {
  7953. ASSERT_TRUE(req.is_multipart_form_data());
  7954. std::vector<FormData> received;
  7955. content_reader(
  7956. [&](const FormData &file) {
  7957. received.push_back(file);
  7958. return true;
  7959. },
  7960. [&](const char *data, size_t data_length) {
  7961. received.back().content.append(data, data_length);
  7962. return true;
  7963. });
  7964. // '"', CR and LF in names and filenames are escaped following the
  7965. // WHATWG HTML standard, so each part still parses as a single part
  7966. // with no injected headers. Content types get CR/LF escaped too,
  7967. // while '"' (legal there, e.g. quoted charset) is preserved.
  7968. ASSERT_EQ(4U, received.size());
  7969. EXPECT_EQ("na%22me", received[0].name);
  7970. EXPECT_EQ("quoted name", received[0].content);
  7971. EXPECT_EQ("file", received[1].name);
  7972. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7973. received[1].filename);
  7974. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7975. EXPECT_EQ("injected", received[1].content);
  7976. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7977. EXPECT_EQ("my%22file.txt", received[2].filename);
  7978. EXPECT_EQ("cr lf name", received[2].content);
  7979. EXPECT_EQ("typed", received[3].name);
  7980. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7981. received[3].content_type);
  7982. EXPECT_EQ("typed content", received[3].content);
  7983. });
  7984. auto port = svr.bind_to_any_port("localhost");
  7985. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7986. auto se = detail::scope_exit([&] {
  7987. svr.stop();
  7988. t.join();
  7989. ASSERT_FALSE(svr.is_running());
  7990. });
  7991. svr.wait_until_ready();
  7992. Client cli("localhost", port);
  7993. UploadFormDataItems items = {
  7994. {"na\"me", "quoted name", "", ""},
  7995. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7996. "application/octet-stream"},
  7997. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7998. {"typed", "typed content", "",
  7999. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8000. };
  8001. auto res = cli.Post("/post", items);
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. }
  8005. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8006. const UploadFormDataItems items = {
  8007. {"name1", "Content 1", "", ""},
  8008. {"name2", "Content 2", "file2.txt", "text/plain"},
  8009. };
  8010. Server svr;
  8011. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8012. const ContentReader &content_reader) {
  8013. ASSERT_TRUE(req.is_multipart_form_data());
  8014. std::vector<FormData> received;
  8015. content_reader(
  8016. [&](const FormData &file) {
  8017. received.push_back(file);
  8018. return true;
  8019. },
  8020. [&](const char *data, size_t data_length) {
  8021. received.back().content.append(data, data_length);
  8022. return true;
  8023. });
  8024. ASSERT_EQ(2U, received.size());
  8025. EXPECT_EQ("name1", received[0].name);
  8026. EXPECT_EQ("Content 1", received[0].content);
  8027. EXPECT_EQ("name2", received[1].name);
  8028. EXPECT_EQ("Content 2", received[1].content);
  8029. EXPECT_EQ("file2.txt", received[1].filename);
  8030. EXPECT_EQ("text/plain", received[1].content_type);
  8031. });
  8032. auto port = svr.bind_to_any_port("localhost");
  8033. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8034. auto se = detail::scope_exit([&] {
  8035. svr.stop();
  8036. t.join();
  8037. ASSERT_FALSE(svr.is_running());
  8038. });
  8039. svr.wait_until_ready();
  8040. Client cli("localhost", port);
  8041. // Whole-body serialization with a generated boundary
  8042. {
  8043. MultipartFormDataWriter writer;
  8044. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8045. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8046. writer.content_type());
  8047. auto body = writer.serialize(items);
  8048. EXPECT_EQ(body.size(), writer.content_length(items));
  8049. auto res = cli.Post("/post", body, writer.content_type());
  8050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8051. EXPECT_EQ(StatusCode::OK_200, res->status);
  8052. }
  8053. // Per-part framing with a custom boundary via a content provider
  8054. {
  8055. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8056. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8057. MultipartFormDataWriter writer("custom-boundary_123");
  8058. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8059. std::string body;
  8060. for (const auto &item : items) {
  8061. body += writer.item_begin(item);
  8062. body += item.content;
  8063. body += MultipartFormDataWriter::item_end();
  8064. }
  8065. body += writer.finish();
  8066. EXPECT_EQ(body.size(), writer.content_length(items));
  8067. auto res = cli.Post(
  8068. "/post", body.size(),
  8069. [&](size_t offset, size_t length, DataSink &sink) {
  8070. sink.write(body.data() + offset, length);
  8071. return true;
  8072. },
  8073. writer.content_type());
  8074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8075. EXPECT_EQ(StatusCode::OK_200, res->status);
  8076. }
  8077. }
  8078. TEST_F(ServerTest, PostContentReceiverGzip) {
  8079. cli_.set_compress(true);
  8080. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8082. ASSERT_EQ(StatusCode::OK_200, res->status);
  8083. ASSERT_EQ("content", res->body);
  8084. }
  8085. TEST_F(ServerTest, PutContentReceiver) {
  8086. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8088. ASSERT_EQ(StatusCode::OK_200, res->status);
  8089. ASSERT_EQ("content", res->body);
  8090. }
  8091. TEST_F(ServerTest, PatchContentReceiver) {
  8092. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8094. ASSERT_EQ(StatusCode::OK_200, res->status);
  8095. ASSERT_EQ("content", res->body);
  8096. }
  8097. template <typename ClientType>
  8098. void TestWithHeadersAndContentReceiver(
  8099. ClientType &cli,
  8100. std::function<Result(ClientType &, const std::string &, const Headers &,
  8101. const std::string &, const std::string &,
  8102. ContentReceiver, DownloadProgress)>
  8103. request_func) {
  8104. Headers headers;
  8105. headers.emplace("X-Custom-Header", "test-value");
  8106. std::string received_body;
  8107. auto res = request_func(
  8108. cli, "/content_receiver", headers, "content", "application/json",
  8109. [&](const char *data, size_t data_length) {
  8110. received_body.append(data, data_length);
  8111. return true;
  8112. },
  8113. nullptr);
  8114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8115. EXPECT_EQ(StatusCode::OK_200, res->status);
  8116. EXPECT_EQ("content", received_body);
  8117. }
  8118. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8119. #ifdef CPPHTTPLIB_SSL_ENABLED
  8120. using ClientT = SSLClient;
  8121. #else
  8122. using ClientT = Client;
  8123. #endif
  8124. TestWithHeadersAndContentReceiver<ClientT>(
  8125. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8126. const std::string &body, const std::string &content_type,
  8127. ContentReceiver receiver, DownloadProgress progress) {
  8128. return cli.Post(path, headers, body, content_type, receiver, progress);
  8129. });
  8130. }
  8131. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8132. #ifdef CPPHTTPLIB_SSL_ENABLED
  8133. using ClientT = SSLClient;
  8134. #else
  8135. using ClientT = Client;
  8136. #endif
  8137. TestWithHeadersAndContentReceiver<ClientT>(
  8138. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8139. const std::string &body, const std::string &content_type,
  8140. ContentReceiver receiver, DownloadProgress progress) {
  8141. return cli.Put(path, headers, body, content_type, receiver, progress);
  8142. });
  8143. }
  8144. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8145. #ifdef CPPHTTPLIB_SSL_ENABLED
  8146. using ClientT = SSLClient;
  8147. #else
  8148. using ClientT = Client;
  8149. #endif
  8150. TestWithHeadersAndContentReceiver<ClientT>(
  8151. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8152. const std::string &body, const std::string &content_type,
  8153. ContentReceiver receiver, DownloadProgress progress) {
  8154. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8155. });
  8156. }
  8157. template <typename ClientType>
  8158. void TestWithHeadersAndContentReceiverWithProgress(
  8159. ClientType &cli,
  8160. std::function<Result(ClientType &, const std::string &, const Headers &,
  8161. const std::string &, const std::string &,
  8162. ContentReceiver, DownloadProgress)>
  8163. request_func) {
  8164. Headers headers;
  8165. headers.emplace("X-Test-Header", "progress-test");
  8166. std::string received_body;
  8167. auto progress_called = false;
  8168. auto res = request_func(
  8169. cli, "/content_receiver", headers, "content", "text/plain",
  8170. [&](const char *data, size_t data_length) {
  8171. received_body.append(data, data_length);
  8172. return true;
  8173. },
  8174. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8175. progress_called = true;
  8176. return true;
  8177. });
  8178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8179. EXPECT_EQ(StatusCode::OK_200, res->status);
  8180. EXPECT_EQ("content", received_body);
  8181. EXPECT_TRUE(progress_called);
  8182. }
  8183. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8184. #ifdef CPPHTTPLIB_SSL_ENABLED
  8185. using ClientT = SSLClient;
  8186. #else
  8187. using ClientT = Client;
  8188. #endif
  8189. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8190. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8191. const std::string &body, const std::string &content_type,
  8192. ContentReceiver receiver, DownloadProgress progress) {
  8193. return cli.Post(path, headers, body, content_type, receiver, progress);
  8194. });
  8195. }
  8196. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8197. #ifdef CPPHTTPLIB_SSL_ENABLED
  8198. using ClientT = SSLClient;
  8199. #else
  8200. using ClientT = Client;
  8201. #endif
  8202. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8203. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8204. const std::string &body, const std::string &content_type,
  8205. ContentReceiver receiver, DownloadProgress progress) {
  8206. return cli.Put(path, headers, body, content_type, receiver, progress);
  8207. });
  8208. }
  8209. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8210. #ifdef CPPHTTPLIB_SSL_ENABLED
  8211. using ClientT = SSLClient;
  8212. #else
  8213. using ClientT = Client;
  8214. #endif
  8215. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8216. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8217. const std::string &body, const std::string &content_type,
  8218. ContentReceiver receiver, DownloadProgress progress) {
  8219. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8220. });
  8221. }
  8222. template <typename ClientType>
  8223. void TestWithHeadersAndContentReceiverError(
  8224. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8225. const Headers &, const std::string &,
  8226. const std::string &, ContentReceiver)>
  8227. request_func) {
  8228. Headers headers;
  8229. headers.emplace("X-Error-Test", "true");
  8230. std::string received_body;
  8231. auto receiver_failed = false;
  8232. auto res =
  8233. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8234. [&](const char *data, size_t data_length) {
  8235. received_body.append(data, data_length);
  8236. receiver_failed = true;
  8237. return false;
  8238. });
  8239. ASSERT_FALSE(res);
  8240. EXPECT_TRUE(receiver_failed);
  8241. }
  8242. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8243. #ifdef CPPHTTPLIB_SSL_ENABLED
  8244. using ClientT = SSLClient;
  8245. #else
  8246. using ClientT = Client;
  8247. #endif
  8248. TestWithHeadersAndContentReceiverError<ClientT>(
  8249. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8250. const std::string &body, const std::string &content_type,
  8251. ContentReceiver receiver) {
  8252. return cli.Post(path, headers, body, content_type, receiver);
  8253. });
  8254. }
  8255. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8256. #ifdef CPPHTTPLIB_SSL_ENABLED
  8257. using ClientT = SSLClient;
  8258. #else
  8259. using ClientT = Client;
  8260. #endif
  8261. TestWithHeadersAndContentReceiverError<ClientT>(
  8262. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8263. const std::string &body, const std::string &content_type,
  8264. ContentReceiver receiver) {
  8265. return cli.Put(path, headers, body, content_type, receiver);
  8266. });
  8267. }
  8268. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8269. #ifdef CPPHTTPLIB_SSL_ENABLED
  8270. using ClientT = SSLClient;
  8271. #else
  8272. using ClientT = Client;
  8273. #endif
  8274. TestWithHeadersAndContentReceiverError<ClientT>(
  8275. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8276. const std::string &body, const std::string &content_type,
  8277. ContentReceiver receiver) {
  8278. return cli.Patch(path, headers, body, content_type, receiver);
  8279. });
  8280. }
  8281. TEST_F(ServerTest, PostQueryStringAndBody) {
  8282. auto res =
  8283. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8285. ASSERT_EQ(StatusCode::OK_200, res->status);
  8286. }
  8287. TEST_F(ServerTest, HTTP2Magic) {
  8288. Request req;
  8289. req.method = "PRI";
  8290. req.path = "*";
  8291. req.body = "SM";
  8292. auto res = std::make_shared<Response>();
  8293. auto error = Error::Success;
  8294. auto ret = cli_.send(req, *res, error);
  8295. ASSERT_TRUE(ret);
  8296. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8297. }
  8298. TEST_F(ServerTest, KeepAlive) {
  8299. auto res = cli_.Get("/hi");
  8300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8301. EXPECT_EQ(StatusCode::OK_200, res->status);
  8302. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8303. EXPECT_EQ("Hello World!", res->body);
  8304. res = cli_.Get("/hi");
  8305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8306. EXPECT_EQ(StatusCode::OK_200, res->status);
  8307. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8308. EXPECT_EQ("Hello World!", res->body);
  8309. res = cli_.Get("/hi");
  8310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8311. EXPECT_EQ(StatusCode::OK_200, res->status);
  8312. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8313. EXPECT_EQ("Hello World!", res->body);
  8314. res = cli_.Get("/not-exist");
  8315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8316. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8317. res = cli_.Post("/empty", "", "text/plain");
  8318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8319. EXPECT_EQ(StatusCode::OK_200, res->status);
  8320. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8321. EXPECT_EQ("empty", res->body);
  8322. EXPECT_EQ("close", res->get_header_value("Connection"));
  8323. res = cli_.Post(
  8324. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8325. "text/plain");
  8326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8327. EXPECT_EQ(StatusCode::OK_200, res->status);
  8328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8329. EXPECT_EQ("empty", res->body);
  8330. cli_.set_keep_alive(false);
  8331. res = cli_.Get("/last-request");
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::OK_200, res->status);
  8334. EXPECT_EQ("close", res->get_header_value("Connection"));
  8335. }
  8336. TEST_F(ServerTest, TooManyRedirect) {
  8337. cli_.set_follow_location(true);
  8338. auto res = cli_.Get("/redirect/0");
  8339. ASSERT_TRUE(!res);
  8340. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8341. }
  8342. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8343. Request req;
  8344. req.method = "FOOBAR";
  8345. req.path = "/hi";
  8346. cli_.set_keep_alive(true);
  8347. auto res = cli_.send(req);
  8348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8349. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8350. EXPECT_EQ("close", res->get_header_value("Connection"));
  8351. EXPECT_FALSE(cli_.is_socket_open());
  8352. }
  8353. TEST_F(ServerTest, CustomRouteReadsBody) {
  8354. const std::string xml =
  8355. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8356. Request req;
  8357. req.method = "PROPFIND";
  8358. req.path = "/dav/dir";
  8359. req.set_header("Depth", "1");
  8360. req.body = xml;
  8361. auto res = cli_.send(req);
  8362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8363. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8364. EXPECT_EQ(xml, res->body);
  8365. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8366. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8367. }
  8368. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8369. Request req;
  8370. req.method = "PROPFIND";
  8371. req.path = "/dav/42";
  8372. auto res = cli_.send(req);
  8373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8374. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8375. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8376. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8377. }
  8378. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8379. Request req;
  8380. req.method = "PROPFIND";
  8381. req.path = "/dav-re/123";
  8382. auto res = cli_.send(req);
  8383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8384. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8385. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8386. }
  8387. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8388. Request req;
  8389. req.method = "MKCOL";
  8390. req.path = "/dav-mkcol";
  8391. auto res = cli_.send(req);
  8392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8393. EXPECT_EQ(StatusCode::Created_201, res->status);
  8394. }
  8395. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8396. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8397. Request req;
  8398. req.method = "REPORT";
  8399. req.path = "/dav-report";
  8400. req.body = xml;
  8401. auto res = cli_.send(req);
  8402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8403. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8404. EXPECT_EQ(xml, res->body);
  8405. }
  8406. // A content reader route must fire even when the request carries no body,
  8407. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8408. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8409. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8410. Request req;
  8411. req.method = "REPORT";
  8412. req.path = "/dav-report";
  8413. auto res = cli_.send(req);
  8414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8415. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8416. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8417. }
  8418. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8419. Request req;
  8420. req.method = "PROPFIND";
  8421. req.path = "/not-dav";
  8422. auto res = cli_.send(req);
  8423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8424. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8425. }
  8426. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8427. Request req;
  8428. req.method = "UNLOCK";
  8429. req.path = "/dav/dir";
  8430. cli_.set_keep_alive(true);
  8431. auto res = cli_.send(req);
  8432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8433. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8434. EXPECT_EQ("close", res->get_header_value("Connection"));
  8435. EXPECT_FALSE(cli_.is_socket_open());
  8436. }
  8437. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8438. // The mount point serves this path, but only for GET and HEAD.
  8439. auto get_res = cli_.Get("/dir/index.html");
  8440. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8441. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8442. Request req;
  8443. req.method = "PROPFIND";
  8444. req.path = "/dir/index.html";
  8445. auto res = cli_.send(req);
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8448. }
  8449. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8450. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8451. cli_.set_keep_alive(true);
  8452. for (auto i = 0; i < 2; i++) {
  8453. Request req;
  8454. req.method = "PROPFIND";
  8455. req.path = "/dav/dir";
  8456. req.body = xml;
  8457. auto res = cli_.send(req);
  8458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8459. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8460. EXPECT_EQ(xml, res->body);
  8461. EXPECT_TRUE(cli_.is_socket_open());
  8462. }
  8463. // A built-in method must still be served on the same connection.
  8464. cli_.set_keep_alive(false);
  8465. auto res = cli_.Get("/hi");
  8466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8467. EXPECT_EQ(StatusCode::OK_200, res->status);
  8468. EXPECT_EQ("close", res->get_header_value("Connection"));
  8469. }
  8470. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8471. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8472. Request req;
  8473. req.method = "PROPFIND";
  8474. req.path = "/dav/dir";
  8475. req.set_header("Expect", "100-continue");
  8476. req.body = xml;
  8477. auto res = cli_.send(req);
  8478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8479. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8480. EXPECT_EQ(xml, res->body);
  8481. }
  8482. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8483. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8484. TEST_F(ServerTest, Gzip) {
  8485. Headers headers;
  8486. headers.emplace("Accept-Encoding", "gzip, deflate");
  8487. auto res = cli_.Get("/compress", headers);
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8490. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8491. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8492. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8493. "7890123456789012345678901234567890",
  8494. res->body);
  8495. EXPECT_EQ(StatusCode::OK_200, res->status);
  8496. }
  8497. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8498. Headers headers;
  8499. headers.emplace("Accept-Encoding", "gzip, deflate");
  8500. auto res = cli_.Get("/compress-with-charset", headers);
  8501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8502. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8503. EXPECT_EQ("application/json; charset=utf-8",
  8504. res->get_header_value("Content-Type"));
  8505. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8506. "7890123456789012345678901234567890",
  8507. res->body);
  8508. EXPECT_EQ(StatusCode::OK_200, res->status);
  8509. }
  8510. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8511. Headers headers;
  8512. headers.emplace("Accept-Encoding", "");
  8513. auto res = cli_.Get("/compress", headers);
  8514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8515. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8516. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8517. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8518. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8519. "7890123456789012345678901234567890",
  8520. res->body);
  8521. EXPECT_EQ(StatusCode::OK_200, res->status);
  8522. }
  8523. TEST_F(ServerTest, GzipWithContentReceiver) {
  8524. Headers headers;
  8525. headers.emplace("Accept-Encoding", "gzip, deflate");
  8526. std::string body;
  8527. auto res =
  8528. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8529. EXPECT_EQ(100U, data_length);
  8530. body.append(data, data_length);
  8531. return true;
  8532. });
  8533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8534. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8535. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8536. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8537. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8538. "7890123456789012345678901234567890",
  8539. body);
  8540. EXPECT_EQ(StatusCode::OK_200, res->status);
  8541. }
  8542. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8543. Headers headers;
  8544. headers.emplace("Accept-Encoding", "gzip, deflate");
  8545. cli_.set_decompress(false);
  8546. auto res = cli_.Get("/compress", headers);
  8547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8549. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8550. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8551. EXPECT_EQ(33U, res->body.size());
  8552. EXPECT_EQ(StatusCode::OK_200, res->status);
  8553. }
  8554. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8555. Headers headers;
  8556. headers.emplace("Accept-Encoding", "");
  8557. std::string body;
  8558. auto res =
  8559. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8560. EXPECT_EQ(100U, data_length);
  8561. body.append(data, data_length);
  8562. return true;
  8563. });
  8564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8565. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8567. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8568. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8569. "7890123456789012345678901234567890",
  8570. body);
  8571. EXPECT_EQ(StatusCode::OK_200, res->status);
  8572. }
  8573. TEST_F(ServerTest, NoGzip) {
  8574. Headers headers;
  8575. headers.emplace("Accept-Encoding", "gzip, deflate");
  8576. auto res = cli_.Get("/nocompress", headers);
  8577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8578. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8579. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8580. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8581. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8582. "7890123456789012345678901234567890",
  8583. res->body);
  8584. EXPECT_EQ(StatusCode::OK_200, res->status);
  8585. }
  8586. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8587. Headers headers;
  8588. headers.emplace("Accept-Encoding", "gzip, deflate");
  8589. std::string body;
  8590. auto res = cli_.Get("/nocompress", headers,
  8591. [&](const char *data, size_t data_length) {
  8592. EXPECT_EQ(100U, data_length);
  8593. body.append(data, data_length);
  8594. return true;
  8595. });
  8596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8597. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8598. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8599. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8600. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8601. "7890123456789012345678901234567890",
  8602. body);
  8603. EXPECT_EQ(StatusCode::OK_200, res->status);
  8604. }
  8605. TEST_F(ServerTest, MultipartFormDataGzip) {
  8606. UploadFormDataItems items = {
  8607. {"key1", "test", "", ""},
  8608. {"key2", "--abcdefg123", "", ""},
  8609. };
  8610. cli_.set_compress(true);
  8611. auto res = cli_.Post("/compress-multipart", items);
  8612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8613. EXPECT_EQ(StatusCode::OK_200, res->status);
  8614. }
  8615. #endif
  8616. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8617. // Static file compression is opt-in, so these run their own server rather than
  8618. // flipping it on for the shared ServerTest fixture, which would silently
  8619. // rewrite what every other static file test is asserting.
  8620. class StaticFileCompressionTest : public ::testing::Test {
  8621. protected:
  8622. void TearDown() override {
  8623. if (t_.joinable()) {
  8624. svr_.stop();
  8625. t_.join();
  8626. }
  8627. }
  8628. int start(const std::function<void(Server &)> &configure = nullptr) {
  8629. // Serves the same tree as a directory of build-time compressed assets
  8630. // would be served: the mount point names the coding the files are already
  8631. // stored in. Registered before "/" so it is the one that matches.
  8632. svr_.set_mount_point("/pre-encoded", "./www",
  8633. {{"Content-Encoding", "gzip"}});
  8634. svr_.set_mount_point("/", "./www");
  8635. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8636. res.set_file_content("./www/dir/index.html", "text/html");
  8637. });
  8638. svr_.Get("/pre-encoded-file-content",
  8639. [](const Request & /*req*/, Response &res) {
  8640. res.set_header("Content-Encoding", "gzip");
  8641. res.set_file_content("./www/dir/index.html", "text/html");
  8642. });
  8643. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8644. res.set_content_provider(
  8645. 6, "text/plain",
  8646. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8647. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8648. return true;
  8649. });
  8650. });
  8651. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8652. res.set_content_provider(
  8653. 1000, "text/plain",
  8654. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8655. if (offset < 100) {
  8656. std::string data(100, 'A');
  8657. sink.write(data.data(), data.size());
  8658. return true;
  8659. }
  8660. std::this_thread::sleep_for(std::chrono::seconds(2));
  8661. std::string data(900, 'B');
  8662. sink.write(data.data(), data.size());
  8663. return true;
  8664. });
  8665. });
  8666. if (configure) { configure(svr_); }
  8667. auto port = svr_.bind_to_any_port(HOST);
  8668. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8669. svr_.wait_until_ready();
  8670. return port;
  8671. }
  8672. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8673. // Every file under ./www except 1MB.txt is smaller than the default
  8674. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8675. // it out of the way.
  8676. static void enable_without_floor(Server &svr) {
  8677. svr.set_static_file_compression(true);
  8678. svr.set_static_file_compression_min_length(0);
  8679. }
  8680. Server svr_;
  8681. std::thread t_;
  8682. };
  8683. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8684. auto port = start();
  8685. Client cli(HOST, port);
  8686. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8688. EXPECT_EQ(StatusCode::OK_200, res->status);
  8689. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8690. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8691. EXPECT_EQ(1048576U, res->body.size());
  8692. }
  8693. TEST_F(StaticFileCompressionTest, MountPoint) {
  8694. auto port = start(enable);
  8695. Client cli(HOST, port);
  8696. cli.set_decompress(false);
  8697. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8699. EXPECT_EQ(StatusCode::OK_200, res->status);
  8700. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8702. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8703. // The response stays self-delimiting: a length, not a chunked body.
  8704. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8705. EXPECT_EQ(std::to_string(res->body.size()),
  8706. res->get_header_value("Content-Length"));
  8707. EXPECT_LT(res->body.size(), 1048576U);
  8708. EXPECT_FALSE(res->body.empty());
  8709. }
  8710. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8711. auto port = start(enable);
  8712. Client cli(HOST, port);
  8713. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8715. EXPECT_EQ(StatusCode::OK_200, res->status);
  8716. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8717. EXPECT_EQ(1048576U, res->body.size());
  8718. }
  8719. TEST_F(StaticFileCompressionTest, FileContent) {
  8720. auto port = start(enable_without_floor);
  8721. Client cli(HOST, port);
  8722. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8724. EXPECT_EQ(StatusCode::OK_200, res->status);
  8725. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8726. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8727. EXPECT_EQ(104U, res->body.size());
  8728. }
  8729. // A handler that serves an already-encoded file names the coding itself. The
  8730. // file-backed path decided its coding from Accept-Encoding and the content
  8731. // type alone, so it compressed the stored bytes a second time and appended a
  8732. // second Content-Encoding field line.
  8733. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8734. auto port = start(enable_without_floor);
  8735. Client cli(HOST, port);
  8736. cli.set_decompress(false);
  8737. auto res = cli.Get("/pre-encoded-file-content",
  8738. Headers{{"Accept-Encoding", "gzip"}});
  8739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8740. EXPECT_EQ(StatusCode::OK_200, res->status);
  8741. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8742. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8743. // Vary belongs to a coding the server chose, and it chose none here.
  8744. EXPECT_FALSE(res->has_header("Vary"));
  8745. // The file travels exactly as it is stored on disk.
  8746. EXPECT_EQ(104U, res->body.size());
  8747. }
  8748. // The 1MB file clears the default floor, so this one runs the configuration a
  8749. // deployment would actually have.
  8750. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8751. auto port = start(enable);
  8752. Client cli(HOST, port);
  8753. cli.set_decompress(false);
  8754. auto res =
  8755. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8757. EXPECT_EQ(StatusCode::OK_200, res->status);
  8758. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8759. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8760. EXPECT_FALSE(res->has_header("Vary"));
  8761. EXPECT_EQ(1048576U, res->body.size());
  8762. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8763. }
  8764. TEST_F(StaticFileCompressionTest, Head) {
  8765. auto port = start(enable);
  8766. Client cli(HOST, port);
  8767. cli.set_decompress(false);
  8768. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8769. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8770. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8772. EXPECT_EQ(StatusCode::OK_200, res->status);
  8773. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8774. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8775. // HEAD still reports the size a GET would return.
  8776. EXPECT_EQ(get->get_header_value("Content-Length"),
  8777. res->get_header_value("Content-Length"));
  8778. EXPECT_TRUE(res->body.empty());
  8779. }
  8780. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8781. auto port = start(enable);
  8782. Client cli(HOST, port);
  8783. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8784. {"Accept-Encoding", "gzip"}});
  8785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8786. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8787. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8788. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8789. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8790. EXPECT_EQ("cd", res->body);
  8791. }
  8792. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8793. auto port = start(enable);
  8794. Client cli(HOST, port);
  8795. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8797. EXPECT_EQ(StatusCode::OK_200, res->status);
  8798. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8799. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8800. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8801. }
  8802. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8803. auto port = start(enable);
  8804. Client cli(HOST, port);
  8805. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8807. EXPECT_EQ(StatusCode::OK_200, res->status);
  8808. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8809. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8810. EXPECT_TRUE(res->body.empty());
  8811. }
  8812. TEST_F(StaticFileCompressionTest, MinLength) {
  8813. auto port = start(enable);
  8814. Client cli(HOST, port);
  8815. // 104 bytes, well under the default floor. Compressing it would add the
  8816. // gzip header and trailer to a body that already fits in one packet.
  8817. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8819. EXPECT_EQ(StatusCode::OK_200, res->status);
  8820. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8821. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8822. }
  8823. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8824. auto port = start([](Server &svr) {
  8825. svr.set_static_file_compression(true);
  8826. svr.set_static_file_compression_min_length(1);
  8827. });
  8828. Client cli(HOST, port);
  8829. cli.set_decompress(false);
  8830. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8832. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8833. // A 9-byte file comes back larger than it went in, because gzip's header and
  8834. // trailer outweigh anything deflate can save. That is the end of the range
  8835. // the floor exists to keep out.
  8836. EXPECT_GT(res->body.size(), 9U);
  8837. }
  8838. TEST_F(StaticFileCompressionTest, MaxLength) {
  8839. auto port = start([](Server &svr) {
  8840. svr.set_static_file_compression(true);
  8841. svr.set_static_file_compression_min_length(0);
  8842. svr.set_static_file_compression_max_length(1024);
  8843. });
  8844. Client cli(HOST, port);
  8845. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8846. // defines `small` as a macro on Windows.
  8847. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8848. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8849. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8850. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8851. // Under it: compressed.
  8852. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8853. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8854. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8855. }
  8856. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8857. auto port = start(enable_without_floor);
  8858. Client cli(HOST, port);
  8859. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8860. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8861. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8862. auto identity_etag = identity->get_header_value("ETag");
  8863. ASSERT_FALSE(identity_etag.empty());
  8864. auto gzipped =
  8865. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8866. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8867. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8868. auto gzip_etag = gzipped->get_header_value("ETag");
  8869. ASSERT_FALSE(gzip_etag.empty());
  8870. // Two representations, two validators.
  8871. EXPECT_NE(identity_etag, gzip_etag);
  8872. // Each one revalidates against the request that would produce it...
  8873. auto fresh =
  8874. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8875. {"If-None-Match", gzip_etag}});
  8876. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8877. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8878. auto fresh_identity =
  8879. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8880. {"If-None-Match", identity_etag}});
  8881. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8882. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8883. // ...and not against the other representation.
  8884. auto crossed =
  8885. cli.Get("/dir/index.html",
  8886. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8887. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8888. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8889. }
  8890. // The opt-in covers responses the server reads off disk itself. A caller's own
  8891. // known-length provider keeps its Content-Length and, more importantly, keeps
  8892. // delivering incrementally: routing it through a compressor would hold every
  8893. // write back until zlib's window filled.
  8894. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8895. auto port = start(enable);
  8896. Client cli(HOST, port);
  8897. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8901. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8902. EXPECT_EQ("aaabbb", res->body);
  8903. }
  8904. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8905. auto port = start(enable);
  8906. Client cli(HOST, port);
  8907. cli.set_read_timeout(1, 0);
  8908. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8909. Headers{{"Accept-Encoding", "gzip"}});
  8910. ASSERT_TRUE(handle.is_valid());
  8911. // The provider writes 100 bytes and then stalls for longer than the read
  8912. // timeout. Those first bytes have to arrive anyway: run the response through
  8913. // a compressor and zlib holds them until its window fills, so the read would
  8914. // come back empty instead.
  8915. char buf[256];
  8916. auto n = handle.read(buf, sizeof(buf));
  8917. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8918. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8919. }
  8920. #endif
  8921. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8922. TEST_F(ServerTest, Brotli) {
  8923. Headers headers;
  8924. headers.emplace("Accept-Encoding", "br");
  8925. auto res = cli_.Get("/compress", headers);
  8926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8927. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8929. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8931. "7890123456789012345678901234567890",
  8932. res->body);
  8933. EXPECT_EQ(StatusCode::OK_200, res->status);
  8934. }
  8935. #endif
  8936. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8937. TEST_F(ServerTest, Zstd) {
  8938. Headers headers;
  8939. headers.emplace("Accept-Encoding", "zstd");
  8940. auto res = cli_.Get("/compress", headers);
  8941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8942. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8944. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8945. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8946. "7890123456789012345678901234567890",
  8947. res->body);
  8948. EXPECT_EQ(StatusCode::OK_200, res->status);
  8949. }
  8950. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8951. Headers headers;
  8952. headers.emplace("Accept-Encoding", "");
  8953. auto res = cli_.Get("/compress", headers);
  8954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8955. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8956. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8957. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8958. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8959. "7890123456789012345678901234567890",
  8960. res->body);
  8961. EXPECT_EQ(StatusCode::OK_200, res->status);
  8962. }
  8963. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8964. Headers headers;
  8965. headers.emplace("Accept-Encoding", "zstd");
  8966. std::string body;
  8967. auto res =
  8968. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8969. EXPECT_EQ(100U, data_length);
  8970. body.append(data, data_length);
  8971. return true;
  8972. });
  8973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8974. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8975. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8976. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8977. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8978. "7890123456789012345678901234567890",
  8979. body);
  8980. EXPECT_EQ(StatusCode::OK_200, res->status);
  8981. }
  8982. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8983. Headers headers;
  8984. headers.emplace("Accept-Encoding", "zstd");
  8985. cli_.set_decompress(false);
  8986. auto res = cli_.Get("/compress", headers);
  8987. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8988. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8989. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8990. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8992. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8994. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8995. EXPECT_EQ(StatusCode::OK_200, res->status);
  8996. ASSERT_EQ(26U, res->body.size());
  8997. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8998. 0);
  8999. }
  9000. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9001. Headers headers;
  9002. headers.emplace("Accept-Encoding", "");
  9003. std::string body;
  9004. auto res =
  9005. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9006. EXPECT_EQ(100U, data_length);
  9007. body.append(data, data_length);
  9008. return true;
  9009. });
  9010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9011. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9012. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9013. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9014. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9015. "7890123456789012345678901234567890",
  9016. body);
  9017. EXPECT_EQ(StatusCode::OK_200, res->status);
  9018. }
  9019. TEST_F(ServerTest, NoZstd) {
  9020. Headers headers;
  9021. headers.emplace("Accept-Encoding", "zstd");
  9022. auto res = cli_.Get("/nocompress", headers);
  9023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9024. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9025. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9026. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9027. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9028. "7890123456789012345678901234567890",
  9029. res->body);
  9030. EXPECT_EQ(StatusCode::OK_200, res->status);
  9031. }
  9032. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9033. Headers headers;
  9034. headers.emplace("Accept-Encoding", "zstd");
  9035. std::string body;
  9036. auto res = cli_.Get("/nocompress", headers,
  9037. [&](const char *data, size_t data_length) {
  9038. EXPECT_EQ(100U, data_length);
  9039. body.append(data, data_length);
  9040. return true;
  9041. });
  9042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9043. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9044. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9045. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9046. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9047. "7890123456789012345678901234567890",
  9048. body);
  9049. EXPECT_EQ(StatusCode::OK_200, res->status);
  9050. }
  9051. // TODO: How to enable zstd ??
  9052. TEST_F(ServerTest, MultipartFormDataZstd) {
  9053. UploadFormDataItems items = {
  9054. {"key1", "test", "", ""},
  9055. {"key2", "--abcdefg123", "", ""},
  9056. };
  9057. Headers headers;
  9058. headers.emplace("Accept-Encoding", "zstd");
  9059. cli_.set_compress(true);
  9060. auto res = cli_.Post("/compress-multipart", headers, items);
  9061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9062. EXPECT_EQ(StatusCode::OK_200, res->status);
  9063. }
  9064. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9065. Headers headers;
  9066. headers.emplace("Accept-Encoding", "zstd");
  9067. cli_.set_compress(true);
  9068. auto res = cli_.Put(
  9069. "/put", headers, 3,
  9070. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9071. sink.os << "PUT";
  9072. return true;
  9073. },
  9074. "text/plain");
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ(StatusCode::OK_200, res->status);
  9077. EXPECT_EQ("PUT", res->body);
  9078. }
  9079. // Pre-compression logging tests
  9080. TEST_F(ServerTest, PreCompressionLogging) {
  9081. // Test data for compression (matches the actual /compress endpoint content)
  9082. const std::string test_content =
  9083. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9084. "3456789012345678901234567890";
  9085. // Variables to capture logging data
  9086. std::string pre_compression_body;
  9087. std::string pre_compression_content_type;
  9088. std::string pre_compression_content_encoding;
  9089. std::string post_compression_body;
  9090. std::string post_compression_content_type;
  9091. std::string post_compression_content_encoding;
  9092. // Set up pre-compression logger
  9093. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9094. const Response &res) {
  9095. pre_compression_body = res.body;
  9096. pre_compression_content_type = res.get_header_value("Content-Type");
  9097. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9098. });
  9099. // Set up post-compression logger
  9100. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9101. post_compression_body = res.body;
  9102. post_compression_content_type = res.get_header_value("Content-Type");
  9103. post_compression_content_encoding =
  9104. res.get_header_value("Content-Encoding");
  9105. });
  9106. // Test with gzip compression
  9107. Headers headers;
  9108. headers.emplace("Accept-Encoding", "gzip");
  9109. auto res = cli_.Get("/compress", headers);
  9110. // Verify response was compressed
  9111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9112. EXPECT_EQ(StatusCode::OK_200, res->status);
  9113. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9114. // Verify pre-compression logger captured uncompressed content
  9115. EXPECT_EQ(test_content, pre_compression_body);
  9116. EXPECT_EQ("text/plain", pre_compression_content_type);
  9117. EXPECT_TRUE(pre_compression_content_encoding
  9118. .empty()); // No encoding header before compression
  9119. // Verify post-compression logger captured compressed content
  9120. EXPECT_NE(test_content,
  9121. post_compression_body); // Should be different after compression
  9122. EXPECT_EQ("text/plain", post_compression_content_type);
  9123. EXPECT_EQ("gzip", post_compression_content_encoding);
  9124. // Verify compressed content is smaller
  9125. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9126. }
  9127. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9128. const std::string test_content =
  9129. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9130. "3456789012345678901234567890";
  9131. std::string pre_compression_body;
  9132. std::string post_compression_body;
  9133. svr_.set_pre_compression_logger(
  9134. [&](const Request & /*req*/, const Response &res) {
  9135. pre_compression_body = res.body;
  9136. });
  9137. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9138. post_compression_body = res.body;
  9139. });
  9140. Headers headers;
  9141. headers.emplace("Accept-Encoding", "br");
  9142. auto res = cli_.Get("/compress", headers);
  9143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9144. EXPECT_EQ(StatusCode::OK_200, res->status);
  9145. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9146. // Verify pre-compression content is uncompressed
  9147. EXPECT_EQ(test_content, pre_compression_body);
  9148. // Verify post-compression content is compressed
  9149. EXPECT_NE(test_content, post_compression_body);
  9150. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9151. }
  9152. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9153. const std::string test_content =
  9154. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9155. "3456789012345678901234567890";
  9156. std::string pre_compression_body;
  9157. std::string post_compression_body;
  9158. svr_.set_pre_compression_logger(
  9159. [&](const Request & /*req*/, const Response &res) {
  9160. pre_compression_body = res.body;
  9161. });
  9162. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9163. post_compression_body = res.body;
  9164. });
  9165. // Request without compression (use /nocompress endpoint)
  9166. Headers headers;
  9167. auto res = cli_.Get("/nocompress", headers);
  9168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9169. EXPECT_EQ(StatusCode::OK_200, res->status);
  9170. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9171. // Pre-compression logger should not be called when no compression is applied
  9172. EXPECT_TRUE(
  9173. pre_compression_body.empty()); // Pre-compression logger not called
  9174. EXPECT_EQ(
  9175. test_content,
  9176. post_compression_body); // Post-compression logger captures final content
  9177. }
  9178. TEST_F(ServerTest, LoggerSeesContentLength) {
  9179. size_t logged_content_length = 0;
  9180. std::string logged_content_length_header;
  9181. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9182. logged_content_length = res.content_length_;
  9183. logged_content_length_header = res.get_header_value("Content-Length");
  9184. });
  9185. auto res = cli_.Get("/nocompress");
  9186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9187. EXPECT_EQ(StatusCode::OK_200, res->status);
  9188. EXPECT_EQ(res->body.size(), logged_content_length);
  9189. EXPECT_EQ(std::to_string(logged_content_length),
  9190. logged_content_length_header);
  9191. }
  9192. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9193. const std::string test_content =
  9194. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9195. "3456789012345678901234567890";
  9196. std::string pre_compression_body;
  9197. bool pre_logger_called = false;
  9198. // Set only pre-compression logger
  9199. svr_.set_pre_compression_logger(
  9200. [&](const Request & /*req*/, const Response &res) {
  9201. pre_compression_body = res.body;
  9202. pre_logger_called = true;
  9203. });
  9204. Headers headers;
  9205. headers.emplace("Accept-Encoding", "gzip");
  9206. auto res = cli_.Get("/compress", headers);
  9207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9208. EXPECT_EQ(StatusCode::OK_200, res->status);
  9209. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9210. // Verify pre-compression logger was called
  9211. EXPECT_TRUE(pre_logger_called);
  9212. EXPECT_EQ(test_content, pre_compression_body);
  9213. }
  9214. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9215. {
  9216. // Test with Expect: 100-continue header - success case
  9217. // Server returns 100 Continue, client sends body, server returns 200 OK
  9218. Request req;
  9219. req.method = "POST";
  9220. req.path = "/post-large";
  9221. req.set_header("Expect", "100-continue");
  9222. req.body = LARGE_DATA;
  9223. Response res;
  9224. auto error = Error::Success;
  9225. cli_.set_keep_alive(true);
  9226. auto ret = cli_.send(req, res, error);
  9227. EXPECT_TRUE(ret);
  9228. EXPECT_EQ(StatusCode::OK_200, res.status);
  9229. EXPECT_EQ(LARGE_DATA, res.body);
  9230. }
  9231. {
  9232. // Test with Expect: 100-continue header - error case
  9233. // Client should not send the body when server returns an error
  9234. Request req;
  9235. req.method = "POST";
  9236. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9237. req.set_header("Expect", "100-continue");
  9238. req.body = LARGE_DATA;
  9239. Response res;
  9240. auto error = Error::Success;
  9241. auto start = std::chrono::high_resolution_clock::now();
  9242. cli_.set_keep_alive(true);
  9243. auto ret = cli_.send(req, res, error);
  9244. auto end = std::chrono::high_resolution_clock::now();
  9245. auto elapsed =
  9246. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9247. .count();
  9248. // With Expect: 100-continue, request completes successfully but with error
  9249. EXPECT_TRUE(ret);
  9250. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9251. EXPECT_EQ("close", res.get_header_value("Connection"));
  9252. EXPECT_FALSE(cli_.is_socket_open());
  9253. EXPECT_LE(elapsed, 2000);
  9254. }
  9255. {
  9256. // Send an extra GET request to ensure error recovery without hanging
  9257. Request req;
  9258. req.method = "GET";
  9259. req.path = "/hi";
  9260. auto start = std::chrono::high_resolution_clock::now();
  9261. auto res = cli_.send(req);
  9262. auto end = std::chrono::high_resolution_clock::now();
  9263. auto elapsed =
  9264. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9265. .count();
  9266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9267. EXPECT_EQ(StatusCode::OK_200, res->status);
  9268. EXPECT_EQ("Hello World!", res->body);
  9269. EXPECT_LE(elapsed, 500);
  9270. }
  9271. }
  9272. TEST(ZstdDecompressor, ChunkedDecompression) {
  9273. std::string data;
  9274. for (size_t i = 0; i < 32 * 1024; ++i) {
  9275. data.push_back(static_cast<char>('a' + i % 26));
  9276. }
  9277. std::string compressed_data;
  9278. {
  9279. httplib::detail::zstd_compressor compressor;
  9280. bool result = compressor.compress(
  9281. data.data(), data.size(),
  9282. /*last=*/true,
  9283. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9284. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9285. compressed_data_size);
  9286. return true;
  9287. });
  9288. ASSERT_TRUE(result);
  9289. }
  9290. std::string decompressed_data;
  9291. {
  9292. httplib::detail::zstd_decompressor decompressor;
  9293. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9294. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9295. size_t chunk_size = 130;
  9296. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9297. chunk_begin += chunk_size) {
  9298. size_t current_chunk_size =
  9299. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9300. bool result = decompressor.decompress(
  9301. compressed_data.data() + chunk_begin, current_chunk_size,
  9302. [&](const char *decompressed_data_chunk,
  9303. size_t decompressed_data_chunk_size) {
  9304. decompressed_data.insert(decompressed_data.size(),
  9305. decompressed_data_chunk,
  9306. decompressed_data_chunk_size);
  9307. return true;
  9308. });
  9309. ASSERT_TRUE(result);
  9310. }
  9311. }
  9312. ASSERT_EQ(data, decompressed_data);
  9313. }
  9314. TEST(ZstdDecompressor, Decompress) {
  9315. std::string original_text = "Compressed with ZSTD";
  9316. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9317. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9318. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9319. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9320. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9321. std::string decompressed_data;
  9322. {
  9323. httplib::detail::zstd_decompressor decompressor;
  9324. bool result = decompressor.decompress(
  9325. compressed_data.data(), compressed_data.size(),
  9326. [&](const char *decompressed_data_chunk,
  9327. size_t decompressed_data_chunk_size) {
  9328. decompressed_data.insert(decompressed_data.size(),
  9329. decompressed_data_chunk,
  9330. decompressed_data_chunk_size);
  9331. return true;
  9332. });
  9333. ASSERT_TRUE(result);
  9334. }
  9335. ASSERT_EQ(original_text, decompressed_data);
  9336. }
  9337. #endif
  9338. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9339. // separate chunks so that the server sees each part in its own read(). Used to
  9340. // place a read boundary at a specific offset of a request body.
  9341. static bool send_request_in_parts(time_t read_timeout_sec,
  9342. const std::vector<std::string> &parts,
  9343. std::string *resp = nullptr,
  9344. int port = PORT) {
  9345. auto error = Error::Success;
  9346. auto client_sock = detail::create_client_socket(
  9347. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9348. /*connection_timeout_sec=*/5, 0,
  9349. /*read_timeout_sec=*/5, 0,
  9350. /*write_timeout_sec=*/5, 0, std::string(), error);
  9351. if (client_sock == INVALID_SOCKET) { return false; }
  9352. auto ret = detail::process_client_socket(
  9353. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9354. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9355. for (size_t i = 0; i < parts.size(); i++) {
  9356. const auto &part = parts[i];
  9357. if (part.size() !=
  9358. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9359. return false;
  9360. }
  9361. if (i + 1 < parts.size()) {
  9362. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9363. }
  9364. }
  9365. char buf[512];
  9366. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9367. while (line_reader.getline()) {
  9368. if (resp) { *resp += line_reader.ptr(); }
  9369. }
  9370. return true;
  9371. });
  9372. detail::close_socket(client_sock);
  9373. return ret;
  9374. }
  9375. // Sends a raw request to a server listening at HOST:PORT.
  9376. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9377. std::string *resp = nullptr, int port = PORT) {
  9378. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9379. }
  9380. #ifdef CPPHTTPLIB_SSL_ENABLED
  9381. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9382. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9383. ASSERT_TRUE(svr.is_valid());
  9384. svr.set_read_timeout(1, 0);
  9385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9386. auto se = detail::scope_exit([&] {
  9387. svr.stop();
  9388. t.join();
  9389. ASSERT_FALSE(svr.is_running());
  9390. });
  9391. svr.wait_until_ready();
  9392. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9393. // keeps each wait well within the read timeout. The server gives up a
  9394. // second in, so the bytes sent after that fail.
  9395. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9396. parts.resize(26, std::string(1, '\0'));
  9397. EXPECT_FALSE(send_request_in_parts(5, parts));
  9398. }
  9399. #endif
  9400. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9401. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9402. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9403. const std::vector<std::string> &parts,
  9404. std::string *resp = nullptr,
  9405. int port = PORT) {
  9406. auto error = Error::Success;
  9407. auto sock = detail::create_client_socket(
  9408. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9409. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9410. /*write_timeout_sec=*/5, 0, std::string(), error);
  9411. if (sock == INVALID_SOCKET) { return false; }
  9412. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9413. auto ctx = SSL_CTX_new(TLS_client_method());
  9414. auto ssl = SSL_new(ctx);
  9415. auto ssl_se = detail::scope_exit([&] {
  9416. SSL_free(ssl);
  9417. SSL_CTX_free(ctx);
  9418. });
  9419. SSL_set_fd(ssl, static_cast<int>(sock));
  9420. if (SSL_connect(ssl) != 1) { return false; }
  9421. for (size_t i = 0; i < parts.size(); i++) {
  9422. const auto &part = parts[i];
  9423. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9424. static_cast<int>(part.size())) {
  9425. return false;
  9426. }
  9427. if (i + 1 < parts.size()) {
  9428. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9429. }
  9430. }
  9431. char buf[512];
  9432. int n;
  9433. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9434. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9435. }
  9436. return true;
  9437. }
  9438. #endif
  9439. // The request line, then a header value a byte at a time.
  9440. static std::vector<std::string> slow_request_head_parts() {
  9441. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9442. parts.resize(26, "a");
  9443. parts.emplace_back("\r\n\r\n");
  9444. return parts;
  9445. }
  9446. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9447. // within the one-second read timeout. The server gives up a second in, before
  9448. // the head is complete.
  9449. static void
  9450. expect_slow_request_head_dropped(Server &svr,
  9451. const std::function<std::string()> &send) {
  9452. std::atomic<bool> handled(false);
  9453. svr.Get("/", [&](const Request &, Response &res) {
  9454. handled = true;
  9455. res.set_content("ok", "text/plain");
  9456. });
  9457. svr.set_read_timeout(1, 0);
  9458. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9459. auto se = detail::scope_exit([&] {
  9460. svr.stop();
  9461. t.join();
  9462. ASSERT_FALSE(svr.is_running());
  9463. });
  9464. svr.wait_until_ready();
  9465. auto resp = send();
  9466. EXPECT_FALSE(handled);
  9467. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9468. }
  9469. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9470. Server svr;
  9471. expect_slow_request_head_dropped(svr, [] {
  9472. std::string resp;
  9473. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9474. return resp;
  9475. });
  9476. }
  9477. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9478. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9480. ASSERT_TRUE(svr.is_valid());
  9481. expect_slow_request_head_dropped(svr, [] {
  9482. std::string resp;
  9483. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9484. return resp;
  9485. });
  9486. }
  9487. #endif
  9488. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9489. Server svr;
  9490. std::string header_value;
  9491. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9492. header_value = req.get_header_value("foo");
  9493. res.set_content("ok", "text/plain");
  9494. });
  9495. thread t = thread([&] { svr.listen(HOST, PORT); });
  9496. auto se = detail::scope_exit([&] {
  9497. svr.stop();
  9498. t.join();
  9499. ASSERT_FALSE(svr.is_running());
  9500. });
  9501. svr.wait_until_ready();
  9502. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9503. // like characters are not treated the same - use vertical tab and escape.
  9504. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9505. "foo: \t \v bar \x1B\t \r\n"
  9506. "Connection: close\r\n"
  9507. "\r\n";
  9508. std::string res;
  9509. ASSERT_TRUE(send_request(5, req, &res));
  9510. EXPECT_EQ(header_value, "");
  9511. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9512. }
  9513. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9514. Server svr;
  9515. std::string received;
  9516. svr.Get("/order", [&](const Request &req, Response &res) {
  9517. received = entries_to_string(req.headers);
  9518. res.set_content("ok", "text/plain");
  9519. });
  9520. auto port = svr.bind_to_any_port(HOST);
  9521. thread t = thread([&] { svr.listen_after_bind(); });
  9522. auto se = detail::scope_exit([&] {
  9523. svr.stop();
  9524. t.join();
  9525. ASSERT_FALSE(svr.is_running());
  9526. });
  9527. svr.wait_until_ready();
  9528. const std::string req = "GET /order HTTP/1.1\r\n"
  9529. "Host: localhost\r\n"
  9530. "X-First: 1\r\n"
  9531. "X-Dup: a\r\n"
  9532. "X-Second: 2\r\n"
  9533. "X-Dup: b\r\n"
  9534. "Connection: close\r\n"
  9535. "\r\n";
  9536. std::string res;
  9537. ASSERT_TRUE(send_request(5, req, &res, port));
  9538. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9539. EXPECT_EQ(
  9540. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9541. received);
  9542. }
  9543. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9544. Server svr;
  9545. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9546. res.set_header("Set-Cookie", "first=1");
  9547. res.set_header("X-Between", "y");
  9548. res.set_header("Set-Cookie", "second=2");
  9549. res.set_content("ok", "text/plain");
  9550. });
  9551. auto port = svr.bind_to_any_port(HOST);
  9552. thread t = thread([&] { svr.listen_after_bind(); });
  9553. auto se = detail::scope_exit([&] {
  9554. svr.stop();
  9555. t.join();
  9556. ASSERT_FALSE(svr.is_running());
  9557. });
  9558. svr.wait_until_ready();
  9559. Client cli(HOST, port);
  9560. auto res = cli.Get("/cookies");
  9561. ASSERT_TRUE(res);
  9562. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9563. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9564. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9565. }
  9566. // A stream may send a byte at a time with a small extension on each chunk,
  9567. // however long it runs
  9568. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9569. Server svr;
  9570. svr.Post("/count", [](const Request &req, Response &res) {
  9571. res.set_content(std::to_string(req.body.size()), "text/plain");
  9572. });
  9573. auto port = svr.bind_to_any_port(HOST);
  9574. ASSERT_LT(0, port);
  9575. thread t = thread([&] { svr.listen_after_bind(); });
  9576. auto se = detail::scope_exit([&] {
  9577. svr.stop();
  9578. t.join();
  9579. ASSERT_FALSE(svr.is_running());
  9580. });
  9581. svr.wait_until_ready();
  9582. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9583. "\r\nTransfer-Encoding: chunked\r\n"
  9584. "Connection: close\r\n\r\n";
  9585. for (auto i = 0; i < 4096; i++) {
  9586. req += "1;a=b\r\nx\r\n";
  9587. }
  9588. req += "0\r\n\r\n";
  9589. std::string res;
  9590. ASSERT_TRUE(send_request(5, req, &res, port));
  9591. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9592. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9593. }
  9594. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9595. Server svr;
  9596. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9597. auto i = new int(0);
  9598. res.set_header("Trailer", "X-Safe, X-Reflected");
  9599. res.set_chunked_content_provider(
  9600. "text/plain",
  9601. [i](size_t /*offset*/, DataSink &sink) {
  9602. if (*i == 0) {
  9603. sink.os << "body";
  9604. } else {
  9605. Headers trailer;
  9606. // A valid trailer that must survive.
  9607. trailer.emplace("X-Safe", "safe");
  9608. // Attacker-controlled value carrying CR/LF (response splitting).
  9609. trailer.emplace("X-Reflected",
  9610. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9611. // Attacker-controlled name carrying CR/LF.
  9612. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9613. sink.done_with_trailer(trailer);
  9614. }
  9615. (*i)++;
  9616. return true;
  9617. },
  9618. [i](bool /*success*/) { delete i; });
  9619. });
  9620. thread t = thread([&] { svr.listen(HOST, PORT); });
  9621. auto se = detail::scope_exit([&] {
  9622. svr.stop();
  9623. t.join();
  9624. ASSERT_FALSE(svr.is_running());
  9625. });
  9626. svr.wait_until_ready();
  9627. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9628. "Host: " + HOST +
  9629. "\r\n"
  9630. "Connection: close\r\n"
  9631. "\r\n";
  9632. std::string res;
  9633. ASSERT_TRUE(send_request(5, req, &res));
  9634. // The injected fields must not appear anywhere in the raw response.
  9635. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9636. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9637. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9638. // Invalid trailers are dropped entirely, matching set_header().
  9639. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9640. // The valid trailer still passes through.
  9641. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9642. }
  9643. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9644. // A custom header writer gets only the fields the default one writes
  9645. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9646. std::string s;
  9647. for (const auto &h : hdrs) {
  9648. s += h.first + ": " + h.second + "\r\n";
  9649. }
  9650. s += "\r\n";
  9651. return strm.write(s.data(), s.size());
  9652. };
  9653. for (auto custom_writer : {false, true}) {
  9654. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9655. Server svr;
  9656. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9657. svr.set_post_routing_handler([](const Request &, Response &res) {
  9658. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9659. });
  9660. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9661. // res.headers is a public field an application can populate directly,
  9662. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9663. // A valid header that must survive.
  9664. res.headers.emplace("X-Safe", "safe");
  9665. // Attacker-controlled value carrying CR/LF (response splitting).
  9666. res.headers.emplace("X-Reflected",
  9667. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9668. // Attacker-controlled name carrying CR/LF.
  9669. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9670. res.set_content("body", "text/plain");
  9671. });
  9672. thread t = thread([&] { svr.listen(HOST, PORT); });
  9673. auto se = detail::scope_exit([&] {
  9674. svr.stop();
  9675. t.join();
  9676. ASSERT_FALSE(svr.is_running());
  9677. });
  9678. svr.wait_until_ready();
  9679. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9680. "Host: " + HOST +
  9681. "\r\n"
  9682. "Connection: close\r\n"
  9683. "\r\n";
  9684. std::string res;
  9685. ASSERT_TRUE(send_request(5, req, &res));
  9686. // The injected fields must not appear anywhere in the raw response.
  9687. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9688. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9689. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9690. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9691. // Invalid headers are dropped entirely, matching set_header().
  9692. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9693. // The valid header still passes through.
  9694. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9695. }
  9696. }
  9697. // Forward declaration: in split builds split.py strips `inline` and moves the
  9698. // definition into httplib.cc, so detail::write_request_line is not visible from
  9699. // the public httplib.h. Re-declaring it here lets the tests link against the
  9700. // symbol in both header-only and split builds.
  9701. namespace httplib {
  9702. namespace detail {
  9703. ssize_t write_request_line(Stream &strm, const std::string &method,
  9704. const std::string &path);
  9705. } // namespace detail
  9706. } // namespace httplib
  9707. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9708. // A well-formed target is written verbatim.
  9709. {
  9710. detail::BufferStream strm;
  9711. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9712. EXPECT_GT(n, 0);
  9713. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9714. }
  9715. // A target carrying CR/LF, SP or other control octets must be rejected
  9716. // before anything reaches the wire, otherwise it splits the request line and
  9717. // injects a header or a whole request.
  9718. const std::string evil_targets[] = {
  9719. "/a\r\nInjected: pwned",
  9720. "/a\rInjected",
  9721. "/a\nInjected",
  9722. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9723. "/a b",
  9724. "/a\tb",
  9725. "/a\x7f",
  9726. };
  9727. for (const auto &evil : evil_targets) {
  9728. detail::BufferStream strm;
  9729. auto n = detail::write_request_line(strm, "GET", evil);
  9730. EXPECT_LT(n, 0);
  9731. EXPECT_TRUE(strm.get_buffer().empty());
  9732. }
  9733. }
  9734. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9735. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9736. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9737. // target reaches write_request. The client must fail cleanly with
  9738. // Error::Write instead of putting a request-line-less, header-injecting
  9739. // request on the wire.
  9740. Server svr;
  9741. svr.Get("/a", [](const Request &, Response &res) {
  9742. res.set_content("ok", "text/plain");
  9743. });
  9744. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9745. auto se = detail::scope_exit([&] {
  9746. svr.stop();
  9747. thread.join();
  9748. ASSERT_FALSE(svr.is_running());
  9749. });
  9750. svr.wait_until_ready();
  9751. {
  9752. Client cli(HOST, PORT);
  9753. cli.set_path_encode(false);
  9754. // The request is rejected before anything is written, so the connection
  9755. // stays silent and the subsequent response read would otherwise block for
  9756. // the full default read timeout. Shorten it -- the assertion is on the
  9757. // error, not the timeout.
  9758. cli.set_read_timeout(1, 0);
  9759. auto res = cli.Get("/a\r\nInjected: pwned");
  9760. EXPECT_FALSE(res);
  9761. EXPECT_EQ(Error::Write, res.error());
  9762. }
  9763. }
  9764. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9765. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9766. // including extension methods.
  9767. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9768. for (const auto &method : good_methods) {
  9769. detail::BufferStream strm;
  9770. auto n = detail::write_request_line(strm, method, "/");
  9771. EXPECT_GT(n, 0);
  9772. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9773. }
  9774. // A method carrying CR/LF would split the request line and smuggle a whole
  9775. // request ahead of the real one. A space or an empty method corrupts the
  9776. // request line. All must be rejected before anything reaches the wire.
  9777. const std::string evil_methods[] = {
  9778. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9779. "GET\r\nInjected: pwned",
  9780. "GET\r",
  9781. "GET\n",
  9782. "GE T",
  9783. "",
  9784. };
  9785. for (const auto &evil : evil_methods) {
  9786. detail::BufferStream strm;
  9787. auto n = detail::write_request_line(strm, evil, "/");
  9788. EXPECT_LT(n, 0);
  9789. EXPECT_TRUE(strm.get_buffer().empty());
  9790. }
  9791. }
  9792. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9793. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9794. // through Client::send must fail with Error::Write and no request, neither
  9795. // the smuggled one nor the real one, may reach the server.
  9796. Server svr;
  9797. std::atomic<int> request_count(0);
  9798. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9799. request_count++;
  9800. res.status = StatusCode::OK_200;
  9801. return Server::HandlerResponse::Handled;
  9802. });
  9803. auto port = svr.bind_to_any_port(HOST);
  9804. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9805. auto se = detail::scope_exit([&] {
  9806. svr.stop();
  9807. thread.join();
  9808. ASSERT_FALSE(svr.is_running());
  9809. });
  9810. svr.wait_until_ready();
  9811. {
  9812. Client cli(HOST, port);
  9813. const std::string evil_methods[] = {
  9814. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9815. "GE T",
  9816. "",
  9817. };
  9818. for (const auto &evil : evil_methods) {
  9819. Request req;
  9820. req.method = evil;
  9821. req.path = "/";
  9822. auto res = cli.send(req);
  9823. EXPECT_FALSE(res);
  9824. EXPECT_EQ(Error::Write, res.error());
  9825. }
  9826. auto handle =
  9827. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9828. EXPECT_FALSE(handle.is_valid());
  9829. EXPECT_EQ(Error::Write, handle.error);
  9830. // A valid request on the same client still goes through.
  9831. auto res = cli.Get("/");
  9832. ASSERT_TRUE(res);
  9833. EXPECT_EQ(StatusCode::OK_200, res->status);
  9834. }
  9835. EXPECT_EQ(1, request_count.load());
  9836. }
  9837. // Sends a raw request and verifies that there isn't a crash or exception.
  9838. static void test_raw_request(const std::string &req,
  9839. std::string *out = nullptr) {
  9840. Server svr;
  9841. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9842. res.set_content("ok", "text/plain");
  9843. });
  9844. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9845. res.set_content("ok", "text/plain");
  9846. });
  9847. svr.Get("/header_field_value_check",
  9848. [&](const Request & /*req*/, Response &res) {
  9849. res.set_content("ok", "text/plain");
  9850. });
  9851. svr.CustomRoute("PROPFIND", "/dav",
  9852. [&](const Request & /*req*/, Response &res) {
  9853. res.status = StatusCode::MultiStatus_207;
  9854. });
  9855. // Server read timeout must be longer than the client read timeout for the
  9856. // bug to reproduce, probably to force the server to process a request
  9857. // without a trailing blank line.
  9858. const time_t client_read_timeout_sec = 1;
  9859. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9860. bool listen_thread_ok = false;
  9861. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9862. auto se = detail::scope_exit([&] {
  9863. svr.stop();
  9864. t.join();
  9865. ASSERT_FALSE(svr.is_running());
  9866. EXPECT_TRUE(listen_thread_ok);
  9867. });
  9868. svr.wait_until_ready();
  9869. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9870. }
  9871. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9872. // A certain header line causes an exception if the header property is parsed
  9873. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9874. test_raw_request(
  9875. "GET /hi HTTP/1.1\r\n"
  9876. " : "
  9877. " "
  9878. " ");
  9879. }
  9880. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9881. // A certain header line causes an exception if the header property *name* is
  9882. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9883. // greedy matcher and requires backtracking when there are a lot of ":"
  9884. // characters.
  9885. // This occurs with libc++ but not libstdc++.
  9886. test_raw_request(
  9887. "GET /hi HTTP/1.1\r\n"
  9888. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9889. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9890. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9891. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9892. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9893. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9894. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9895. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9896. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9897. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9898. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9899. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9900. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9901. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9902. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9903. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9904. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9905. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9906. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9907. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9908. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9909. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9910. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9911. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9912. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9913. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9914. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9915. "&&&%%%");
  9916. }
  9917. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9918. // Make sure this doesn't crash the server.
  9919. // In a previous version of the header line regex, the "\r" rendered the line
  9920. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9921. // a new position where the leading white space ended and the field value
  9922. // began.
  9923. // The crash occurs with libc++ but not libstdc++.
  9924. test_raw_request("GET /hi HTTP/1.1\r\n"
  9925. "a:" +
  9926. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9927. "\r\n"
  9928. "\r\n");
  9929. }
  9930. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9931. const char *rejected[] = {
  9932. // RFC 9112 §3: one SP between the parts, and nothing else
  9933. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9934. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9935. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9936. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9937. // A request-target has no fragment
  9938. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9939. // An HTTP/1.1 request needs a Host
  9940. "GET /hi HTTP/1.1\r\n\r\n",
  9941. };
  9942. for (auto request : rejected) {
  9943. std::string out;
  9944. test_raw_request(request, &out);
  9945. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9946. }
  9947. std::string out;
  9948. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9949. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9950. }
  9951. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9952. // RFC 9112 §6.1
  9953. const char *requests[] = {
  9954. "PUT /put_hi HTTP/1.1\r\n"
  9955. "Host: localhost\r\n"
  9956. "Content-Length: 0\r\n"
  9957. "Transfer-Encoding: chunked\r\n"
  9958. "\r\n"
  9959. "0\r\n\r\n",
  9960. "PUT /put_hi HTTP/1.0\r\n"
  9961. "Connection: keep-alive\r\n"
  9962. "Transfer-Encoding: chunked\r\n"
  9963. "\r\n"
  9964. "0\r\n\r\n",
  9965. };
  9966. for (auto request : requests) {
  9967. std::string out;
  9968. test_raw_request(request, &out);
  9969. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9970. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9971. }
  9972. }
  9973. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9974. std::string out;
  9975. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9976. "Content-Type: text/plain\r\n"
  9977. "Transfer-Encoding: chunked\r\n"
  9978. "\r\n"
  9979. "nothex\r\n",
  9980. &out);
  9981. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9982. }
  9983. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9984. std::string out;
  9985. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9986. "Content-Type: text/plain\r\n"
  9987. "Transfer-Encoding: chunked\r\n"
  9988. "\r\n"
  9989. "3\r\n"
  9990. "xyz\r\n"
  9991. "NaN\r\n",
  9992. &out);
  9993. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9994. }
  9995. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9996. std::string out;
  9997. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9998. "Content-Type: text/plain\r\n"
  9999. "Transfer-Encoding: chunked\r\n"
  10000. "\r\n"
  10001. // Length is too large for 64 bits.
  10002. "1ffffffffffffffff\r\n"
  10003. "xyz\r\n",
  10004. &out);
  10005. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10006. }
  10007. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10008. test_raw_request("GET /hi HTTP/1.1\r\n"
  10009. "Content-Type: text/plain\r\n\r");
  10010. }
  10011. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10012. std::string out;
  10013. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10014. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10015. }
  10016. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10017. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10018. std::string out;
  10019. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10020. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10021. }
  10022. }
  10023. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10024. std::string out;
  10025. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10026. "Host: localhost\r\n"
  10027. "Connection: close\r\n\r\n",
  10028. &out);
  10029. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10030. }
  10031. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10032. Server svr;
  10033. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10034. EXPECT_TRUE(!req.remote_addr.empty());
  10035. });
  10036. thread t = thread([&] { svr.listen(HOST, PORT); });
  10037. auto se = detail::scope_exit([&] {
  10038. svr.stop();
  10039. t.join();
  10040. ASSERT_FALSE(svr.is_running());
  10041. });
  10042. svr.wait_until_ready();
  10043. // Send an invalid request line to trigger Bad Request
  10044. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10045. std::string out;
  10046. ASSERT_TRUE(send_request(5, bad_req, &out));
  10047. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10048. }
  10049. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10050. // answered right away rather than blocking on a read that waits for EOF.
  10051. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10052. std::string out;
  10053. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10054. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10055. }
  10056. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10057. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10058. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10059. for (const auto *method : methods) {
  10060. Server svr;
  10061. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10062. EXPECT_FALSE(svr.is_valid()) << method;
  10063. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10064. }
  10065. }
  10066. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10067. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10068. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10069. for (const auto *method : methods) {
  10070. Server svr;
  10071. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10072. EXPECT_FALSE(svr.is_valid()) << method;
  10073. }
  10074. }
  10075. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10076. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10077. "COPY", "MOVE", "LOCK",
  10078. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10079. Server svr;
  10080. for (const auto *method : methods) {
  10081. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10082. }
  10083. EXPECT_TRUE(svr.is_valid());
  10084. }
  10085. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10086. Server svr;
  10087. svr.CustomRoute("POST", "/x",
  10088. [](const Request &, Response &, const ContentReader &) {});
  10089. EXPECT_FALSE(svr.is_valid());
  10090. }
  10091. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10092. Server svr;
  10093. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10094. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10095. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10096. EXPECT_FALSE(svr.is_valid());
  10097. }
  10098. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10099. Server svr;
  10100. auto captured = Error::Success;
  10101. svr.set_error_logger(
  10102. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10103. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10104. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10105. }
  10106. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10107. std::string out;
  10108. std::string request(
  10109. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10110. test_raw_request(request, &out);
  10111. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10112. }
  10113. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10114. std::string out;
  10115. std::string request(
  10116. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10117. test_raw_request(request, &out);
  10118. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10119. }
  10120. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10121. std::string out;
  10122. std::string request(
  10123. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10124. test_raw_request(request, &out);
  10125. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10126. }
  10127. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10128. std::string out;
  10129. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10130. "Host: localhost\r\n"
  10131. "Test: \r\n\r\n",
  10132. &out);
  10133. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10134. }
  10135. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10136. Server svr;
  10137. std::string x_custom;
  10138. std::string cookie;
  10139. std::string xff;
  10140. std::string x_unicode;
  10141. std::string x_iis;
  10142. svr.Get("/check", [&](const Request &req, Response &res) {
  10143. x_custom = req.get_header_value("X-Custom");
  10144. cookie = req.get_header_value("Cookie");
  10145. xff = req.get_header_value("X-Forwarded-For");
  10146. x_unicode = req.get_header_value("X-Unicode");
  10147. x_iis = req.get_header_value("X-IIS");
  10148. res.set_content("ok", "text/plain");
  10149. });
  10150. thread t = thread([&] { svr.listen(HOST, PORT); });
  10151. auto se = detail::scope_exit([&] {
  10152. svr.stop();
  10153. t.join();
  10154. ASSERT_FALSE(svr.is_running());
  10155. });
  10156. svr.wait_until_ready();
  10157. const std::string req = "GET /check HTTP/1.1\r\n"
  10158. "Host: localhost\r\n"
  10159. "X-Custom: a%0D%0AInjected: b\r\n"
  10160. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10161. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10162. "X-Unicode: %E3%81%82\r\n"
  10163. "X-IIS: %u00E9\r\n"
  10164. "Connection: close\r\n"
  10165. "\r\n";
  10166. std::string res;
  10167. ASSERT_TRUE(send_request(5, req, &res));
  10168. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10169. // Every value must be returned verbatim (wire form), with no decoding.
  10170. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10171. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10172. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10173. EXPECT_EQ("%E3%81%82", x_unicode);
  10174. EXPECT_EQ("%u00E9", x_iis);
  10175. }
  10176. // Applications that previously relied on automatic percent-decoding can
  10177. // reproduce the old behavior by explicitly calling decode_path_component()
  10178. // or, for RFC 3986 conformance, decode_uri_component().
  10179. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10180. Server svr;
  10181. std::string decoded;
  10182. svr.Get("/check", [&](const Request &req, Response &res) {
  10183. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10184. res.set_content("ok", "text/plain");
  10185. });
  10186. thread t = thread([&] { svr.listen(HOST, PORT); });
  10187. auto se = detail::scope_exit([&] {
  10188. svr.stop();
  10189. t.join();
  10190. ASSERT_FALSE(svr.is_running());
  10191. });
  10192. svr.wait_until_ready();
  10193. const std::string req = "GET /check HTTP/1.1\r\n"
  10194. "Host: localhost\r\n"
  10195. "X-Custom: hello%20world\r\n"
  10196. "Connection: close\r\n"
  10197. "\r\n";
  10198. std::string res;
  10199. ASSERT_TRUE(send_request(5, req, &res));
  10200. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10201. EXPECT_EQ("hello world", decoded);
  10202. }
  10203. // Regression test for #2033. Browsers send Referer values that include
  10204. // percent-encoded characters such as %0A inside the URL. Decoding the
  10205. // header value would either trip the post-decode CR/LF/NUL guard (the
  10206. // original bug, returning 400) or, after that guard was relaxed, silently
  10207. // store a literal LF — both unacceptable. The wire form must round-trip.
  10208. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10209. Server svr;
  10210. std::string referer;
  10211. svr.Get("/check", [&](const Request &req, Response &res) {
  10212. referer = req.get_header_value("Referer");
  10213. res.set_content("ok", "text/plain");
  10214. });
  10215. thread t = thread([&] { svr.listen(HOST, PORT); });
  10216. auto se = detail::scope_exit([&] {
  10217. svr.stop();
  10218. t.join();
  10219. ASSERT_FALSE(svr.is_running());
  10220. });
  10221. svr.wait_until_ready();
  10222. const std::string req = "GET /check HTTP/1.1\r\n"
  10223. "Host: localhost\r\n"
  10224. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10225. "Connection: close\r\n"
  10226. "\r\n";
  10227. std::string res;
  10228. ASSERT_TRUE(send_request(5, req, &res));
  10229. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10230. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10231. }
  10232. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10233. Server svr;
  10234. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10235. res.set_header("Cache-Control", "no-cache");
  10236. res.set_chunked_content_provider(
  10237. "text/event-stream", [](size_t offset, DataSink &sink) {
  10238. std::string s = "data:";
  10239. s += std::to_string(offset);
  10240. s += "\n\n";
  10241. auto ret = sink.write(s.data(), s.size());
  10242. EXPECT_TRUE(ret);
  10243. std::this_thread::sleep_for(std::chrono::seconds(1));
  10244. return true;
  10245. });
  10246. });
  10247. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10248. svr.wait_until_ready();
  10249. Client client(HOST, PORT);
  10250. const Headers headers = {{"Accept", "text/event-stream"}};
  10251. auto get_thread = std::thread([&client, &headers]() {
  10252. auto res = client.Get(
  10253. "/events", headers,
  10254. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10255. });
  10256. auto se = detail::scope_exit([&] {
  10257. svr.stop();
  10258. get_thread.join();
  10259. listen_thread.join();
  10260. ASSERT_FALSE(svr.is_running());
  10261. });
  10262. // Give GET time to get a few messages.
  10263. std::this_thread::sleep_for(std::chrono::seconds(2));
  10264. }
  10265. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10266. httplib::Server svr;
  10267. svr.Post("/hi",
  10268. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10269. res.status = StatusCode::OK_200;
  10270. });
  10271. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10272. svr.wait_until_ready();
  10273. Client cli(HOST, PORT);
  10274. auto res = cli.Post("/hi", "data", "text/plain");
  10275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10276. EXPECT_EQ(StatusCode::OK_200, res->status);
  10277. svr.stop();
  10278. thread.join();
  10279. ASSERT_FALSE(svr.is_running());
  10280. res = cli.Post("/hi", "data", "text/plain");
  10281. ASSERT_FALSE(res);
  10282. }
  10283. TEST(ServerStopTest, ListenFailure) {
  10284. Server svr;
  10285. auto t = thread([&]() {
  10286. auto ret = svr.listen("????", PORT);
  10287. EXPECT_FALSE(ret);
  10288. });
  10289. svr.wait_until_ready();
  10290. svr.stop();
  10291. t.join();
  10292. }
  10293. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10294. TEST(ServerStopTest, Decommision) {
  10295. Server svr;
  10296. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10297. for (int i = 0; i < 4; i++) {
  10298. auto is_even = !(i % 2);
  10299. std::thread t{[&] {
  10300. try {
  10301. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10302. if (is_even) {
  10303. throw std::runtime_error("Some thing that happens to go wrong.");
  10304. }
  10305. svr.listen(HOST, PORT);
  10306. } catch (...) { svr.decommission(); }
  10307. }};
  10308. svr.wait_until_ready();
  10309. // Server is up
  10310. {
  10311. Client cli(HOST, PORT);
  10312. auto res = cli.Get("/hi");
  10313. if (is_even) {
  10314. EXPECT_FALSE(res);
  10315. } else {
  10316. EXPECT_TRUE(res);
  10317. EXPECT_EQ("hi...", res->body);
  10318. }
  10319. }
  10320. svr.stop();
  10321. t.join();
  10322. // Server is down...
  10323. {
  10324. Client cli(HOST, PORT);
  10325. auto res = cli.Get("/hi");
  10326. EXPECT_FALSE(res);
  10327. }
  10328. }
  10329. }
  10330. #endif
  10331. // Helper function for string body upload progress tests
  10332. template <typename SetupHandler, typename ClientCall>
  10333. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10334. ClientCall &&client_call,
  10335. const string &body) {
  10336. Server svr;
  10337. setup_handler(svr);
  10338. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10339. auto se = detail::scope_exit([&] {
  10340. svr.stop();
  10341. t.join();
  10342. });
  10343. svr.wait_until_ready();
  10344. Client cli(HOST, PORT);
  10345. vector<uint64_t> progress_values;
  10346. bool progress_called = false;
  10347. auto res =
  10348. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10349. progress_values.push_back(current);
  10350. progress_called = true;
  10351. return true;
  10352. });
  10353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10354. EXPECT_EQ(200, res->status);
  10355. EXPECT_TRUE(progress_called);
  10356. }
  10357. TEST(UploadProgressTest, PostStringBodyBasic) {
  10358. TestStringBodyUploadProgress(
  10359. [](Server &svr) {
  10360. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10361. res.set_content("received", "text/plain");
  10362. });
  10363. },
  10364. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10365. return cli.Post("/test", body, "text/plain", progress_callback);
  10366. },
  10367. "test data for upload progress");
  10368. }
  10369. TEST(UploadProgressTest, PutStringBodyBasic) {
  10370. TestStringBodyUploadProgress(
  10371. [](Server &svr) {
  10372. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10373. res.set_content("put received", "text/plain");
  10374. });
  10375. },
  10376. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10377. return cli.Put("/test", body, "text/plain", progress_callback);
  10378. },
  10379. "put test data for upload progress");
  10380. }
  10381. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10382. TestStringBodyUploadProgress(
  10383. [](Server &svr) {
  10384. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10385. res.set_content("patch received", "text/plain");
  10386. });
  10387. },
  10388. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10389. return cli.Patch("/test", body, "text/plain", progress_callback);
  10390. },
  10391. "patch test data for upload progress");
  10392. }
  10393. // Helper function for content provider upload progress tests
  10394. template <typename SetupHandler, typename ClientCall>
  10395. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10396. ClientCall &&client_call) {
  10397. Server svr;
  10398. setup_handler(svr);
  10399. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10400. auto se = detail::scope_exit([&] {
  10401. svr.stop();
  10402. t.join();
  10403. });
  10404. svr.wait_until_ready();
  10405. Client cli(HOST, PORT);
  10406. vector<uint64_t> progress_values;
  10407. auto res =
  10408. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10409. progress_values.push_back(current);
  10410. return true;
  10411. });
  10412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10413. EXPECT_EQ(200, res->status);
  10414. EXPECT_FALSE(progress_values.empty());
  10415. }
  10416. TEST(UploadProgressTest, PostContentProviderProgress) {
  10417. TestContentProviderUploadProgress(
  10418. [](Server &svr) {
  10419. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10420. res.set_content("provider received", "text/plain");
  10421. });
  10422. },
  10423. [](Client &cli, UploadProgress progress_callback) {
  10424. return cli.Post(
  10425. "/test", 9,
  10426. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10427. sink.os << "test data";
  10428. return true;
  10429. },
  10430. "text/plain", progress_callback);
  10431. });
  10432. }
  10433. // Helper function for multipart upload progress tests
  10434. template <typename SetupHandler, typename ClientCall>
  10435. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10436. ClientCall &&client_call,
  10437. const string &endpoint) {
  10438. Server svr;
  10439. setup_handler(svr);
  10440. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10441. auto se = detail::scope_exit([&] {
  10442. svr.stop();
  10443. t.join();
  10444. });
  10445. svr.wait_until_ready();
  10446. Client cli(HOST, PORT);
  10447. vector<uint64_t> progress_values;
  10448. UploadFormDataItems items = {
  10449. {"field1", "value1", "", ""},
  10450. {"field2", "longer value for progress tracking test", "", ""},
  10451. {"file1", "file content data for upload progress", "test.txt",
  10452. "text/plain"}};
  10453. auto res = client_call(cli, endpoint, items,
  10454. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10455. progress_values.push_back(current);
  10456. return true;
  10457. });
  10458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10459. EXPECT_EQ(200, res->status);
  10460. EXPECT_FALSE(progress_values.empty());
  10461. }
  10462. TEST(UploadProgressTest, PostMultipartProgress) {
  10463. TestMultipartUploadProgress(
  10464. [](Server &svr) {
  10465. svr.Post("/multipart", [](const Request &req, Response &res) {
  10466. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10467. res.set_content("multipart received", "text/plain");
  10468. });
  10469. },
  10470. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10471. UploadProgress progress_callback) {
  10472. return cli.Post(endpoint, items, progress_callback);
  10473. },
  10474. "/multipart");
  10475. }
  10476. // Helper function for basic download progress tests
  10477. template <typename SetupHandler, typename ClientCall>
  10478. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10479. ClientCall &&client_call, const string &endpoint,
  10480. size_t expected_content_size) {
  10481. Server svr;
  10482. setup_handler(svr);
  10483. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10484. auto se = detail::scope_exit([&] {
  10485. svr.stop();
  10486. t.join();
  10487. });
  10488. svr.wait_until_ready();
  10489. Client cli(HOST, PORT);
  10490. vector<uint64_t> progress_values;
  10491. auto res = client_call(cli, endpoint,
  10492. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10493. progress_values.push_back(current);
  10494. return true;
  10495. });
  10496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10497. EXPECT_EQ(200, res->status);
  10498. EXPECT_FALSE(progress_values.empty());
  10499. EXPECT_EQ(expected_content_size, res->body.size());
  10500. }
  10501. TEST(DownloadProgressTest, GetBasic) {
  10502. TestBasicDownloadProgress(
  10503. [](Server &svr) {
  10504. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10505. string content(1000, 'D');
  10506. res.set_content(content, "text/plain");
  10507. });
  10508. },
  10509. [](Client &cli, const string &endpoint,
  10510. DownloadProgress progress_callback) {
  10511. return cli.Get(endpoint, progress_callback);
  10512. },
  10513. "/download", 1000u);
  10514. }
  10515. // Helper function for content receiver download progress tests
  10516. template <typename SetupHandler, typename ClientCall>
  10517. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10518. ClientCall &&client_call,
  10519. const string &endpoint,
  10520. size_t expected_content_size) {
  10521. Server svr;
  10522. setup_handler(svr);
  10523. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10524. auto se = detail::scope_exit([&] {
  10525. svr.stop();
  10526. t.join();
  10527. });
  10528. svr.wait_until_ready();
  10529. Client cli(HOST, PORT);
  10530. vector<uint64_t> progress_values;
  10531. string received_body;
  10532. auto res = client_call(
  10533. cli, endpoint,
  10534. [&](const char *data, size_t data_length) -> bool {
  10535. received_body.append(data, data_length);
  10536. return true;
  10537. },
  10538. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10539. progress_values.push_back(current);
  10540. return true;
  10541. });
  10542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10543. EXPECT_EQ(200, res->status);
  10544. EXPECT_FALSE(progress_values.empty());
  10545. EXPECT_EQ(expected_content_size, received_body.size());
  10546. EXPECT_TRUE(res->body.empty());
  10547. }
  10548. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10549. TestContentReceiverDownloadProgress(
  10550. [](Server &svr) {
  10551. svr.Get("/download-receiver",
  10552. [](const Request & /*req*/, Response &res) {
  10553. string content(2000, 'R');
  10554. res.set_content(content, "text/plain");
  10555. });
  10556. },
  10557. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10558. DownloadProgress progress_callback) {
  10559. return cli.Get(endpoint, content_receiver, progress_callback);
  10560. },
  10561. "/download-receiver", 2000u);
  10562. }
  10563. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10564. // A provider reaching a pass with nothing to hand over - an empty buffer
  10565. // popped off a queue, say - must not be taken to mean the body is finished.
  10566. // It used to end the loop with the terminating chunk unwritten while the
  10567. // server still considered the response complete, so the peer waited for an
  10568. // end that never arrived.
  10569. Server svr;
  10570. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10571. auto step = std::make_shared<int>(0);
  10572. res.set_chunked_content_provider("text/plain",
  10573. [step](size_t /*offset*/, DataSink &sink) {
  10574. switch ((*step)++) {
  10575. case 0: sink.write("", 0); break;
  10576. case 1: sink.write("hello", 5); break;
  10577. default: sink.done(); break;
  10578. }
  10579. return true;
  10580. });
  10581. });
  10582. auto port = svr.bind_to_any_port(HOST);
  10583. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10584. auto listen_se = detail::scope_exit([&] {
  10585. svr.stop();
  10586. listen_thread.join();
  10587. ASSERT_FALSE(svr.is_running());
  10588. });
  10589. svr.wait_until_ready();
  10590. Client cli(HOST, port);
  10591. // Without the fix the body is never terminated, so bound the wait rather
  10592. // than letting the test hang on the default read timeout.
  10593. cli.set_read_timeout(5, 0);
  10594. auto res = cli.Get("/stream");
  10595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10596. EXPECT_EQ(StatusCode::OK_200, res->status);
  10597. EXPECT_EQ("hello", res->body);
  10598. }
  10599. TEST(StreamingTest, NoContentLengthStreaming) {
  10600. Server svr;
  10601. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10602. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10603. if (offset < 6) {
  10604. sink.os << (offset < 3 ? "a" : "b");
  10605. } else {
  10606. sink.done();
  10607. }
  10608. return true;
  10609. });
  10610. });
  10611. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10612. auto listen_se = detail::scope_exit([&] {
  10613. svr.stop();
  10614. listen_thread.join();
  10615. ASSERT_FALSE(svr.is_running());
  10616. });
  10617. svr.wait_until_ready();
  10618. Client client(HOST, PORT);
  10619. auto get_thread = std::thread([&client]() {
  10620. std::string s;
  10621. auto res =
  10622. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10623. s += std::string(data, len);
  10624. return true;
  10625. });
  10626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10627. EXPECT_EQ(StatusCode::OK_200, res->status);
  10628. EXPECT_EQ("aaabbb", s);
  10629. });
  10630. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10631. // Give GET time to get a few messages.
  10632. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10633. }
  10634. TEST(MountTest, Unmount) {
  10635. Server svr;
  10636. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10637. auto se = detail::scope_exit([&] {
  10638. svr.stop();
  10639. listen_thread.join();
  10640. ASSERT_FALSE(svr.is_running());
  10641. });
  10642. svr.wait_until_ready();
  10643. Client cli("localhost", PORT);
  10644. svr.set_mount_point("/mount2", "./www2");
  10645. auto res = cli.Get("/");
  10646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10647. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10648. res = cli.Get("/mount2/dir/test.html");
  10649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10650. EXPECT_EQ(StatusCode::OK_200, res->status);
  10651. svr.set_mount_point("/", "./www");
  10652. res = cli.Get("/dir/");
  10653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10654. EXPECT_EQ(StatusCode::OK_200, res->status);
  10655. svr.remove_mount_point("/");
  10656. res = cli.Get("/dir/");
  10657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10658. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10659. svr.remove_mount_point("/mount2");
  10660. res = cli.Get("/mount2/dir/test.html");
  10661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10662. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10663. }
  10664. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10665. Server svr;
  10666. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10667. svr.Get("/api/hello", [](const Request &, Response &res) {
  10668. res.set_content("api", "text/plain");
  10669. });
  10670. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10671. auto se = detail::scope_exit([&] {
  10672. svr.stop();
  10673. listen_thread.join();
  10674. ASSERT_FALSE(svr.is_running());
  10675. });
  10676. svr.wait_until_ready();
  10677. Client cli(HOST, PORT);
  10678. auto res = cli.Get("/dir/test.html");
  10679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10680. EXPECT_EQ(StatusCode::OK_200, res->status);
  10681. res = cli.Get("/api/hello");
  10682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10683. EXPECT_EQ(StatusCode::OK_200, res->status);
  10684. EXPECT_EQ("api", res->body);
  10685. }
  10686. TEST(MountTest, PathSegmentBoundary) {
  10687. Server svr;
  10688. svr.set_mount_point("/mount2", "./www2");
  10689. svr.set_mount_point("/", "./www");
  10690. auto port = svr.bind_to_any_port(HOST);
  10691. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10692. auto se = detail::scope_exit([&] {
  10693. svr.stop();
  10694. listen_thread.join();
  10695. ASSERT_FALSE(svr.is_running());
  10696. });
  10697. svr.wait_until_ready();
  10698. Client cli(HOST, port);
  10699. auto res = cli.Get("/mount2/dir/test.html");
  10700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10701. EXPECT_EQ(StatusCode::OK_200, res->status);
  10702. // "/mount2" must not match part-way through a path segment.
  10703. res = cli.Get("/mount2dir/test.html");
  10704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10705. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10706. // A mount point ending in '/' keeps matching every path below it.
  10707. res = cli.Get("/dir/test.html");
  10708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10709. EXPECT_EQ(StatusCode::OK_200, res->status);
  10710. }
  10711. TEST(MountTest, Redicect) {
  10712. Server svr;
  10713. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10714. auto se = detail::scope_exit([&] {
  10715. svr.stop();
  10716. listen_thread.join();
  10717. ASSERT_FALSE(svr.is_running());
  10718. });
  10719. svr.set_mount_point("/", "./www");
  10720. svr.wait_until_ready();
  10721. Client cli("localhost", PORT);
  10722. auto res = cli.Get("/dir/");
  10723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10724. EXPECT_EQ(StatusCode::OK_200, res->status);
  10725. res = cli.Get("/dir");
  10726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10727. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10728. res = cli.Get("/file");
  10729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10730. EXPECT_EQ(StatusCode::OK_200, res->status);
  10731. res = cli.Get("/file/");
  10732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10733. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10734. cli.set_follow_location(true);
  10735. res = cli.Get("/dir");
  10736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10737. EXPECT_EQ(StatusCode::OK_200, res->status);
  10738. }
  10739. TEST(MountTest, MultibytesPathName) {
  10740. Server svr;
  10741. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10742. auto se = detail::scope_exit([&] {
  10743. svr.stop();
  10744. listen_thread.join();
  10745. ASSERT_FALSE(svr.is_running());
  10746. });
  10747. svr.set_mount_point("/", "./www");
  10748. svr.wait_until_ready();
  10749. Client cli("localhost", PORT);
  10750. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10752. EXPECT_EQ(StatusCode::OK_200, res->status);
  10753. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10754. }
  10755. // A mount point serves no path with an empty segment or one ending in '.' or
  10756. // a space, so a guard in the pre-routing handler sees the path of every file
  10757. // that is served
  10758. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10759. Server svr;
  10760. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10761. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10762. if (req.path == "/dir/test.html") {
  10763. res.status = StatusCode::Unauthorized_401;
  10764. return Server::HandlerResponse::Handled;
  10765. }
  10766. return Server::HandlerResponse::Unhandled;
  10767. });
  10768. auto port = svr.bind_to_any_port(HOST);
  10769. ASSERT_LT(0, port);
  10770. thread t = thread([&] { svr.listen_after_bind(); });
  10771. auto se = detail::scope_exit([&] {
  10772. svr.stop();
  10773. t.join();
  10774. ASSERT_FALSE(svr.is_running());
  10775. });
  10776. svr.wait_until_ready();
  10777. Client cli(HOST, port);
  10778. for (auto path :
  10779. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10780. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10781. "/dir/test.html.", "/dir/test.html%20"}) {
  10782. SCOPED_TRACE(path);
  10783. auto res = cli.Get(path);
  10784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10785. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10786. }
  10787. }
  10788. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10789. Server svr;
  10790. svr.set_mount_point("/", "./www");
  10791. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10792. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10793. auto port = svr.bind_to_any_port(HOST);
  10794. ASSERT_GT(port, 0);
  10795. thread t = thread([&] { svr.listen_after_bind(); });
  10796. auto se = detail::scope_exit([&] {
  10797. svr.stop();
  10798. t.join();
  10799. ASSERT_FALSE(svr.is_running());
  10800. });
  10801. svr.wait_until_ready();
  10802. Client cli(HOST, port);
  10803. auto res = cli.Get("/dir/test.abcde");
  10804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10805. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10806. res = cli.Get("/dir/test.html");
  10807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10808. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10809. }
  10810. #ifdef _WIN32
  10811. // Issue #2435: mmap::open() must succeed even when another handle holds
  10812. // the file open for writing (e.g. an active log file).
  10813. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10814. const char *path = "mmap_concurrent_writer_test.txt";
  10815. const char *content = "hello";
  10816. {
  10817. std::ofstream f(path, std::ios::binary);
  10818. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10819. }
  10820. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10821. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10822. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10823. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10824. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10825. detail::mmap m(path);
  10826. ASSERT_TRUE(m.is_open());
  10827. EXPECT_EQ(strlen(content), m.size());
  10828. char buf[8];
  10829. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10830. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10831. }
  10832. #endif
  10833. #ifndef _WIN32
  10834. // A directory or a device has no size to serve.
  10835. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10836. const char *path = "./mmap_not_regular_test_dir";
  10837. ASSERT_EQ(0, ::mkdir(path, 0755));
  10838. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10839. for (auto p : {path, "/dev/null"}) {
  10840. detail::mmap m(p);
  10841. EXPECT_FALSE(m.is_open()) << p;
  10842. EXPECT_EQ(0U, m.size()) << p;
  10843. }
  10844. Server svr;
  10845. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10846. res.set_file_content("/dev/null");
  10847. });
  10848. auto port = svr.bind_to_any_port(HOST);
  10849. thread t = thread([&] { svr.listen_after_bind(); });
  10850. auto se = detail::scope_exit([&] {
  10851. svr.stop();
  10852. t.join();
  10853. });
  10854. svr.wait_until_ready();
  10855. auto res = Client(HOST, port).Get("/null");
  10856. ASSERT_TRUE(res);
  10857. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10858. }
  10859. #endif
  10860. #ifdef __linux__
  10861. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10862. TEST(MmapTest, FileIsNotMapped) {
  10863. const char *path = "mmap_not_mapped_test.txt";
  10864. {
  10865. std::ofstream f(path, std::ios::binary);
  10866. f << "hello";
  10867. }
  10868. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10869. detail::mmap m(path);
  10870. ASSERT_TRUE(m.is_open());
  10871. std::ifstream maps("/proc/self/maps");
  10872. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10873. std::istreambuf_iterator<char>());
  10874. EXPECT_EQ(std::string::npos, mappings.find(path));
  10875. }
  10876. #endif
  10877. TEST(KeepAliveTest, ReadTimeout) {
  10878. Server svr;
  10879. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10880. std::this_thread::sleep_for(std::chrono::seconds(2));
  10881. res.set_content("a", "text/plain");
  10882. });
  10883. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10884. res.set_content("b", "text/plain");
  10885. });
  10886. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10887. auto se = detail::scope_exit([&] {
  10888. svr.stop();
  10889. listen_thread.join();
  10890. ASSERT_FALSE(svr.is_running());
  10891. });
  10892. svr.wait_until_ready();
  10893. Client cli("localhost", PORT);
  10894. cli.set_keep_alive(true);
  10895. cli.set_read_timeout(std::chrono::seconds(1));
  10896. auto resa = cli.Get("/a");
  10897. ASSERT_FALSE(resa);
  10898. EXPECT_EQ(Error::Read, resa.error());
  10899. auto resb = cli.Get("/b");
  10900. ASSERT_TRUE(resb);
  10901. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10902. EXPECT_EQ("b", resb->body);
  10903. }
  10904. TEST(KeepAliveTest, MaxCount) {
  10905. size_t keep_alive_max_count = 3;
  10906. Server svr;
  10907. svr.set_keep_alive_max_count(keep_alive_max_count);
  10908. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10909. res.set_content("Hello World!", "text/plain");
  10910. });
  10911. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10912. auto se = detail::scope_exit([&] {
  10913. svr.stop();
  10914. listen_thread.join();
  10915. ASSERT_FALSE(svr.is_running());
  10916. });
  10917. svr.wait_until_ready();
  10918. Client cli(HOST, PORT);
  10919. cli.set_keep_alive(true);
  10920. for (size_t i = 0; i < 5; i++) {
  10921. auto result = cli.Get("/hi");
  10922. ASSERT_TRUE(result);
  10923. EXPECT_EQ(StatusCode::OK_200, result->status);
  10924. if (i == keep_alive_max_count - 1) {
  10925. EXPECT_EQ("close", result->get_header_value("Connection"));
  10926. } else {
  10927. EXPECT_FALSE(result->has_header("Connection"));
  10928. }
  10929. }
  10930. }
  10931. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10932. // can pull the next one into the server's buffer. The server must serve it
  10933. // without waiting for the socket to become readable again. The keep-alive
  10934. // timeout outlasts the client's read timeout, so a request left waiting for it
  10935. // shows up as a missing response.
  10936. static void serve_pipelining_routes(Server &svr,
  10937. const std::function<void(int)> &client) {
  10938. svr.set_keep_alive_timeout(5);
  10939. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10940. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10941. });
  10942. svr.Post("/echo", [](const Request &req, Response &res) {
  10943. res.set_content("echo " + req.body, "text/plain");
  10944. });
  10945. auto port = svr.bind_to_any_port(HOST);
  10946. thread t = thread([&] { svr.listen_after_bind(); });
  10947. auto se = detail::scope_exit([&] {
  10948. svr.stop();
  10949. t.join();
  10950. });
  10951. svr.wait_until_ready();
  10952. client(port);
  10953. }
  10954. static std::string
  10955. send_pipelined_requests(const std::vector<std::string> &parts) {
  10956. Server svr;
  10957. std::string res;
  10958. serve_pipelining_routes(svr, [&](int port) {
  10959. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10960. });
  10961. return res;
  10962. }
  10963. static void expect_in_order(const std::string &res,
  10964. const std::vector<std::string> &bodies) {
  10965. size_t pos = 0;
  10966. for (const auto &body : bodies) {
  10967. pos = res.find(body, pos);
  10968. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10969. pos += body.size();
  10970. }
  10971. }
  10972. TEST(KeepAliveTest, PipelinedRequests) {
  10973. auto res = send_pipelined_requests(
  10974. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10975. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10976. "Content-Length: 4\r\n\r\nbody"
  10977. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10978. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10979. }
  10980. // The second request starts in the server's buffer and ends on the socket.
  10981. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10982. auto res =
  10983. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10984. "GET /hi/2 HTTP/1.1\r\nHo",
  10985. "st: localhost\r\nConnection: close\r\n\r\n"});
  10986. expect_in_order(res, {"hi 1", "hi 2"});
  10987. }
  10988. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10989. // CRLF after a body does not turn into a 400 for the next request.
  10990. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10991. auto res = send_pipelined_requests(
  10992. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10993. "Content-Length: 4\r\n\r\nbody\r\n"
  10994. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10995. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10996. expect_in_order(res, {"echo body", "hi 2"});
  10997. }
  10998. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10999. // must not be served as the next request.
  11000. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11001. auto res = send_pipelined_requests(
  11002. {"INVALID REQUEST LINE\r\n\r\n"
  11003. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11004. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11005. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11006. }
  11007. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11008. // Over TLS, the next request is held by the TLS library as already decrypted
  11009. // data rather than on the socket.
  11010. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11012. std::string res;
  11013. serve_pipelining_routes(svr, [&](int port) {
  11014. // One part, so all three requests arrive in one TLS record
  11015. EXPECT_TRUE(send_ssl_request_in_parts(
  11016. 2,
  11017. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11018. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11019. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11020. &res, port));
  11021. });
  11022. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11023. }
  11024. #endif
  11025. TEST(KeepAliveTest, Issue1041) {
  11026. Server svr;
  11027. svr.set_keep_alive_timeout(3);
  11028. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11029. res.set_content("Hello World!", "text/plain");
  11030. });
  11031. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11032. auto se = detail::scope_exit([&] {
  11033. svr.stop();
  11034. listen_thread.join();
  11035. ASSERT_FALSE(svr.is_running());
  11036. });
  11037. svr.wait_until_ready();
  11038. Client cli(HOST, PORT);
  11039. cli.set_keep_alive(true);
  11040. auto result = cli.Get("/hi");
  11041. ASSERT_TRUE(result);
  11042. EXPECT_EQ(StatusCode::OK_200, result->status);
  11043. std::this_thread::sleep_for(std::chrono::seconds(5));
  11044. result = cli.Get("/hi");
  11045. ASSERT_TRUE(result);
  11046. EXPECT_EQ(StatusCode::OK_200, result->status);
  11047. }
  11048. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11049. Server svr;
  11050. svr.set_keep_alive_max_count(0);
  11051. std::set<int> remote_ports;
  11052. svr.Get("/hi", [&](const Request &req, Response &res) {
  11053. remote_ports.insert(req.remote_port);
  11054. res.set_content("hi", "text/plain");
  11055. });
  11056. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11057. auto se = detail::scope_exit([&] {
  11058. svr.stop();
  11059. listen_thread.join();
  11060. ASSERT_FALSE(svr.is_running());
  11061. });
  11062. svr.wait_until_ready();
  11063. Client cli(HOST, PORT);
  11064. cli.set_keep_alive(true);
  11065. for (int i = 0; i < 3; i++) {
  11066. auto res = cli.Get("/hi");
  11067. ASSERT_TRUE(res);
  11068. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11069. }
  11070. // All three over one connection
  11071. EXPECT_EQ(1u, remote_ports.size());
  11072. }
  11073. TEST(KeepAliveTest, Issue1959) {
  11074. Server svr;
  11075. svr.set_keep_alive_timeout(5);
  11076. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11077. res.set_content("a", "text/plain");
  11078. });
  11079. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11080. auto se = detail::scope_exit([&] {
  11081. if (!svr.is_running()) return;
  11082. svr.stop();
  11083. listen_thread.join();
  11084. ASSERT_FALSE(svr.is_running());
  11085. });
  11086. svr.wait_until_ready();
  11087. Client cli("localhost", PORT);
  11088. cli.set_keep_alive(true);
  11089. using namespace std::chrono;
  11090. auto start = steady_clock::now();
  11091. cli.Get("/a");
  11092. svr.stop();
  11093. listen_thread.join();
  11094. auto end = steady_clock::now();
  11095. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11096. EXPECT_LT(elapsed, 5000);
  11097. }
  11098. #ifdef CPPHTTPLIB_SSL_ENABLED
  11099. TEST(KeepAliveTest, SSLClientReconnection) {
  11100. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11101. ASSERT_TRUE(svr.is_valid());
  11102. svr.set_keep_alive_timeout(1);
  11103. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11104. res.set_content("Hello World!", "text/plain");
  11105. });
  11106. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11107. auto se = detail::scope_exit([&] {
  11108. svr.stop();
  11109. listen_thread.join();
  11110. ASSERT_FALSE(svr.is_running());
  11111. });
  11112. svr.wait_until_ready();
  11113. SSLClient cli(HOST, PORT);
  11114. cli.enable_server_certificate_verification(false);
  11115. cli.set_keep_alive(true);
  11116. auto result = cli.Get("/hi");
  11117. ASSERT_TRUE(result);
  11118. EXPECT_EQ(StatusCode::OK_200, result->status);
  11119. result = cli.Get("/hi");
  11120. ASSERT_TRUE(result);
  11121. EXPECT_EQ(StatusCode::OK_200, result->status);
  11122. std::this_thread::sleep_for(std::chrono::seconds(2));
  11123. // Recoonect
  11124. result = cli.Get("/hi");
  11125. ASSERT_TRUE(result);
  11126. EXPECT_EQ(StatusCode::OK_200, result->status);
  11127. result = cli.Get("/hi");
  11128. ASSERT_TRUE(result);
  11129. EXPECT_EQ(StatusCode::OK_200, result->status);
  11130. }
  11131. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11133. ASSERT_TRUE(svr.is_valid());
  11134. svr.set_keep_alive_timeout(1);
  11135. std::string content = "reconnect";
  11136. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11137. res.set_content("Hello World!", "text/plain");
  11138. });
  11139. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11140. auto se = detail::scope_exit([&] {
  11141. svr.stop();
  11142. listen_thread.join();
  11143. ASSERT_FALSE(svr.is_running());
  11144. });
  11145. svr.wait_until_ready();
  11146. SSLClient cli(HOST, PORT);
  11147. cli.enable_server_certificate_verification(false);
  11148. cli.set_keep_alive(true);
  11149. auto result = cli.Post(
  11150. "/hi", content.size(),
  11151. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11152. sink.write(content.c_str(), content.size());
  11153. return true;
  11154. },
  11155. "text/plain");
  11156. ASSERT_TRUE(result);
  11157. EXPECT_EQ(200, result->status);
  11158. std::this_thread::sleep_for(std::chrono::seconds(2));
  11159. // Recoonect
  11160. result = cli.Post(
  11161. "/hi", content.size(),
  11162. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11163. sink.write(content.c_str(), content.size());
  11164. return true;
  11165. },
  11166. "text/plain");
  11167. ASSERT_TRUE(result);
  11168. EXPECT_EQ(200, result->status);
  11169. result = cli.Post(
  11170. "/hi", content.size(),
  11171. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11172. sink.write(content.c_str(), content.size());
  11173. return true;
  11174. },
  11175. "text/plain");
  11176. ASSERT_TRUE(result);
  11177. EXPECT_EQ(200, result->status);
  11178. }
  11179. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11180. using namespace httplib::tls;
  11181. {
  11182. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11183. ASSERT_TRUE(svr.is_valid());
  11184. svr.Get("/sni", [&](const Request &req, Response &res) {
  11185. std::string expected = req.sni();
  11186. EXPECT_EQ(expected, req.get_param_value("expected"));
  11187. res.set_content("ok", "text/plain");
  11188. });
  11189. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11190. auto se = detail::scope_exit([&] {
  11191. svr.stop();
  11192. listen_thread.join();
  11193. ASSERT_FALSE(svr.is_running());
  11194. });
  11195. svr.wait_until_ready();
  11196. {
  11197. SSLClient cli("localhost", PORT);
  11198. cli.enable_server_certificate_verification(false);
  11199. auto res = cli.Get("/sni?expected=localhost");
  11200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11201. }
  11202. {
  11203. SSLClient cli("::1", PORT);
  11204. cli.enable_server_certificate_verification(false);
  11205. auto res = cli.Get("/sni?expected=");
  11206. // NOTE: This may fail if the server is listening on IPv4 only
  11207. // (e.g., when localhost resolves to 127.0.0.1 only)
  11208. if (res) {
  11209. EXPECT_EQ(StatusCode::OK_200, res->status);
  11210. } else {
  11211. EXPECT_EQ(Error::Connection, res.error());
  11212. }
  11213. }
  11214. }
  11215. }
  11216. // The SNI of a failed handshake does not reach the next connection that the
  11217. // same worker thread serves
  11218. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11219. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11220. ASSERT_TRUE(svr.is_valid());
  11221. svr.new_task_queue = [] { return new ThreadPool(1); };
  11222. svr.Get("/sni", [](const Request &req, Response &res) {
  11223. res.set_content(req.sni(), "text/plain");
  11224. });
  11225. auto port = svr.bind_to_any_port("127.0.0.1");
  11226. ASSERT_LT(0, port);
  11227. thread t = thread([&] { svr.listen_after_bind(); });
  11228. auto se = detail::scope_exit([&] {
  11229. svr.stop();
  11230. t.join();
  11231. ASSERT_FALSE(svr.is_running());
  11232. });
  11233. svr.wait_until_ready();
  11234. {
  11235. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11236. SSLClient cli("localhost", port);
  11237. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11238. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11239. auto res = cli.Get("/sni");
  11240. ASSERT_FALSE(res);
  11241. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11242. }
  11243. // An IP host sends no SNI (RFC 6066)
  11244. SSLClient cli("127.0.0.1", port);
  11245. cli.enable_server_certificate_verification(false);
  11246. auto res = cli.Get("/sni");
  11247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11248. EXPECT_EQ("", res->body);
  11249. }
  11250. #endif
  11251. TEST(ClientProblemDetectionTest, ContentProvider) {
  11252. Server svr;
  11253. size_t content_length = 1024 * 1024;
  11254. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11255. res.set_content_provider(
  11256. content_length, "text/plain",
  11257. [&](size_t offset, size_t length, DataSink &sink) {
  11258. auto out_len = std::min(length, static_cast<size_t>(1024));
  11259. std::string out(out_len, '@');
  11260. sink.write(out.data(), out_len);
  11261. return offset < 4096;
  11262. },
  11263. [](bool success) { ASSERT_FALSE(success); });
  11264. });
  11265. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11266. res.set_content_provider(
  11267. 0, "text/plain",
  11268. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11269. EXPECT_TRUE(false);
  11270. return true;
  11271. },
  11272. [](bool success) { ASSERT_FALSE(success); });
  11273. });
  11274. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11275. auto se = detail::scope_exit([&] {
  11276. svr.stop();
  11277. listen_thread.join();
  11278. ASSERT_FALSE(svr.is_running());
  11279. });
  11280. svr.wait_until_ready();
  11281. Client cli("localhost", PORT);
  11282. {
  11283. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11284. size_t /*data_length*/) { return false; });
  11285. ASSERT_FALSE(res);
  11286. }
  11287. {
  11288. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11289. size_t /*data_length*/) { return false; });
  11290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11291. }
  11292. }
  11293. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11294. // A provider that reports success without writing anything and without
  11295. // calling done() used to be handed the same offset and length again on every
  11296. // pass, so it spun for as long as the peer stayed connected.
  11297. Server svr;
  11298. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11299. res.set_content("ok", "text/plain");
  11300. });
  11301. auto port = svr.bind_to_any_port(HOST);
  11302. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11303. auto se = detail::scope_exit([&] {
  11304. svr.stop();
  11305. listen_thread.join();
  11306. ASSERT_FALSE(svr.is_running());
  11307. });
  11308. svr.wait_until_ready();
  11309. std::atomic<int> call_count{0};
  11310. Client cli(HOST, port);
  11311. auto res = cli.Post(
  11312. "/", 1024,
  11313. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11314. // Give up after enough passes to show the spin, so that losing the
  11315. // check below fails this test instead of hanging it.
  11316. return ++call_count < 100;
  11317. },
  11318. "text/plain");
  11319. ASSERT_FALSE(res);
  11320. EXPECT_EQ(Error::Write, res.error());
  11321. EXPECT_EQ(1, call_count.load());
  11322. }
  11323. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11324. // A writer only has to assign `write`. The other three used to be left as
  11325. // empty std::functions, so a provider calling one threw
  11326. // std::bad_function_call out of the thread running it and took the whole
  11327. // process down.
  11328. DataSink sink;
  11329. std::string written;
  11330. sink.write = [&](const char *data, size_t data_len) {
  11331. written.append(data, data_len);
  11332. return true;
  11333. };
  11334. EXPECT_TRUE(sink.is_writable());
  11335. sink.done();
  11336. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11337. EXPECT_TRUE(written.empty());
  11338. }
  11339. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11340. // A sink that cannot carry trailers still has to finish.
  11341. DataSink sink;
  11342. auto done_count = 0;
  11343. sink.done = [&]() { done_count++; };
  11344. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11345. EXPECT_EQ(1, done_count);
  11346. }
  11347. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11348. Server svr;
  11349. const std::string body(4096, 'x');
  11350. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11351. res.set_content_provider(body.size(), "text/plain",
  11352. [&](size_t offset, size_t length, DataSink &sink) {
  11353. sink.write(body.data() + offset, length);
  11354. sink.done();
  11355. return true;
  11356. });
  11357. });
  11358. auto port = svr.bind_to_any_port(HOST);
  11359. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11360. auto se = detail::scope_exit([&] {
  11361. svr.stop();
  11362. listen_thread.join();
  11363. ASSERT_FALSE(svr.is_running());
  11364. });
  11365. svr.wait_until_ready();
  11366. Client cli(HOST, port);
  11367. auto res = cli.Get("/");
  11368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11369. EXPECT_EQ(StatusCode::OK_200, res->status);
  11370. EXPECT_EQ(body, res->body);
  11371. }
  11372. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11373. Server svr;
  11374. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11375. res.set_content_provider(
  11376. 1024, "text/plain",
  11377. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11378. sink.write("hello", 5);
  11379. sink.done(); // short of the 1024 bytes the response promised
  11380. return true;
  11381. });
  11382. });
  11383. auto port = svr.bind_to_any_port(HOST);
  11384. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11385. auto se = detail::scope_exit([&] {
  11386. svr.stop();
  11387. listen_thread.join();
  11388. ASSERT_FALSE(svr.is_running());
  11389. });
  11390. svr.wait_until_ready();
  11391. Client cli(HOST, port);
  11392. cli.set_read_timeout(5, 0);
  11393. // The response is short of its Content-Length, so the client cannot read a
  11394. // complete body. What matters is that this returns at all: a no-op done()
  11395. // would leave the writer looping over a provider that never makes progress.
  11396. auto res = cli.Get("/");
  11397. EXPECT_FALSE(res);
  11398. }
  11399. // Read as the next response by a peer that sees it after a framed body.
  11400. static const std::string smuggled_response =
  11401. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11402. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11403. Server svr;
  11404. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11405. res.set_content_provider(
  11406. 5, "text/plain",
  11407. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11408. auto data = "AAAAA" + smuggled_response;
  11409. sink.write(data.data(), data.size());
  11410. return true;
  11411. });
  11412. });
  11413. thread t = thread([&] { svr.listen(HOST, PORT); });
  11414. auto se = detail::scope_exit([&] {
  11415. svr.stop();
  11416. t.join();
  11417. ASSERT_FALSE(svr.is_running());
  11418. });
  11419. svr.wait_until_ready();
  11420. std::string resp;
  11421. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11422. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11423. resp.clear();
  11424. ASSERT_TRUE(send_request(
  11425. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11426. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11427. }
  11428. TEST(NoContentTest, BodyIsNotSent) {
  11429. Server svr;
  11430. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11431. res.status = StatusCode::NoContent_204;
  11432. res.set_content(smuggled_response, "text/plain");
  11433. });
  11434. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11435. res.status = StatusCode::NotModified_304;
  11436. res.set_chunked_content_provider(
  11437. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11438. sink.write(smuggled_response.data(), smuggled_response.size());
  11439. sink.done();
  11440. return true;
  11441. });
  11442. });
  11443. thread t = thread([&] { svr.listen(HOST, PORT); });
  11444. auto se = detail::scope_exit([&] {
  11445. svr.stop();
  11446. t.join();
  11447. ASSERT_FALSE(svr.is_running());
  11448. });
  11449. svr.wait_until_ready();
  11450. for (auto path : {"/204", "/304"}) {
  11451. std::string resp;
  11452. ASSERT_TRUE(send_request(
  11453. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11454. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11455. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11456. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11457. }
  11458. }
  11459. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11460. Server svr;
  11461. std::atomic<bool> smuggled(false);
  11462. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11463. res.set_content("ok", "text/plain");
  11464. });
  11465. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11466. smuggled = true;
  11467. });
  11468. auto port = svr.bind_to_any_port(HOST);
  11469. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11470. auto se = detail::scope_exit([&] {
  11471. svr.stop();
  11472. listen_thread.join();
  11473. ASSERT_FALSE(svr.is_running());
  11474. });
  11475. svr.wait_until_ready();
  11476. // What follows the body would be read as the next request.
  11477. Client cli(HOST, port);
  11478. auto res = cli.Post(
  11479. "/", 5,
  11480. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11481. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11482. sink.write(data.data(), data.size());
  11483. return true;
  11484. },
  11485. "text/plain");
  11486. ASSERT_FALSE(res);
  11487. EXPECT_EQ(Error::Write, res.error());
  11488. EXPECT_FALSE(smuggled);
  11489. }
  11490. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11491. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11492. // The compressed path builds the whole body before connecting, so this
  11493. // fails client-side and never reaches a server.
  11494. Client cli(HOST, PORT);
  11495. cli.set_compress(true);
  11496. auto res = cli.Post(
  11497. "/", 1024,
  11498. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11499. sink.write("hello", 5);
  11500. sink.done(); // short of the 1024 bytes the request announced
  11501. return true;
  11502. },
  11503. "text/plain");
  11504. ASSERT_FALSE(res);
  11505. EXPECT_EQ(Error::Write, res.error());
  11506. }
  11507. #endif
  11508. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11509. Server svr;
  11510. svr.set_error_handler([](Request const &, Response &res) -> void {
  11511. res.set_chunked_content_provider(
  11512. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11513. sink.os << "hello";
  11514. sink.os << "world";
  11515. sink.done();
  11516. return true;
  11517. });
  11518. });
  11519. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11520. auto se = detail::scope_exit([&] {
  11521. svr.stop();
  11522. listen_thread.join();
  11523. ASSERT_FALSE(svr.is_running());
  11524. });
  11525. svr.wait_until_ready();
  11526. Client cli("localhost", PORT);
  11527. auto res = cli.Get("/");
  11528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11529. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11530. EXPECT_EQ("helloworld", res->body);
  11531. }
  11532. // A body set after a content provider must replace it, not be sent through it.
  11533. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11534. Server svr;
  11535. svr.set_mount_point("/", "./www");
  11536. svr.set_file_request_handler([](const Request &req, Response &res) {
  11537. if (req.path == "/dir/test.html") {
  11538. res.status = StatusCode::Forbidden_403;
  11539. res.set_content(std::string(5000, 'D'), "text/plain");
  11540. } else if (req.path == "/file") {
  11541. res.status = StatusCode::Forbidden_403;
  11542. res.body = "Denied";
  11543. }
  11544. });
  11545. auto port = svr.bind_to_any_port(HOST);
  11546. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11547. auto se = detail::scope_exit([&] {
  11548. svr.stop();
  11549. t.join();
  11550. ASSERT_FALSE(svr.is_running());
  11551. });
  11552. svr.wait_until_ready();
  11553. Client cli(HOST, port);
  11554. {
  11555. auto res = cli.Get("/dir/test.html");
  11556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11557. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11558. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11559. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11560. }
  11561. {
  11562. auto res = cli.Get("/file");
  11563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11564. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11565. EXPECT_EQ("Denied", res->body);
  11566. }
  11567. {
  11568. auto res = cli.Get("/dir/index.html");
  11569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11570. EXPECT_EQ(StatusCode::OK_200, res->status);
  11571. EXPECT_EQ(0U, res->body.find("<html>"));
  11572. }
  11573. }
  11574. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11575. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11576. Server svr;
  11577. std::vector<bool> released;
  11578. std::mutex released_mutex;
  11579. auto releaser = [&](bool success) {
  11580. std::lock_guard<std::mutex> guard(released_mutex);
  11581. released.push_back(success);
  11582. };
  11583. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11584. return sink.write(&"hello"[offset], length);
  11585. };
  11586. svr.Get("/sized", [&](const Request &, Response &res) {
  11587. res.status = StatusCode::NotFound_404;
  11588. res.set_content_provider(5, "text/plain", provider, releaser);
  11589. });
  11590. svr.Get("/chunked", [&](const Request &, Response &res) {
  11591. res.status = StatusCode::ServiceUnavailable_503;
  11592. res.set_chunked_content_provider(
  11593. "text/plain",
  11594. [](size_t, DataSink &sink) {
  11595. sink.os << "chunk";
  11596. sink.done();
  11597. return true;
  11598. },
  11599. releaser);
  11600. });
  11601. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11602. res.set_content_provider(5, "text/plain", provider, releaser);
  11603. throw std::runtime_error("after the provider");
  11604. });
  11605. svr.set_error_handler([](const Request &req, Response &res) {
  11606. // Leave the exception handler's content to it.
  11607. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11608. res.set_content(std::string(1000, 'E'), "text/html");
  11609. return Server::HandlerResponse::Handled;
  11610. });
  11611. svr.set_exception_handler(
  11612. [](const Request &, Response &res, std::exception_ptr) {
  11613. res.status = StatusCode::InternalServerError_500;
  11614. res.set_content(std::string(1000, 'X'), "text/html");
  11615. });
  11616. auto port = svr.bind_to_any_port(HOST);
  11617. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11618. auto se = detail::scope_exit([&] {
  11619. svr.stop();
  11620. t.join();
  11621. ASSERT_FALSE(svr.is_running());
  11622. });
  11623. svr.wait_until_ready();
  11624. Client cli(HOST, port);
  11625. {
  11626. auto res = cli.Get("/sized");
  11627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11628. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11629. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11630. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11631. }
  11632. {
  11633. auto res = cli.Get("/chunked");
  11634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11635. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11636. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11637. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11638. }
  11639. {
  11640. auto res = cli.Get("/throw");
  11641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11642. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11643. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11644. }
  11645. std::lock_guard<std::mutex> guard(released_mutex);
  11646. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11647. }
  11648. #endif
  11649. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11650. Server svr;
  11651. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11652. return sink.write(&"abc"[offset], length);
  11653. };
  11654. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11655. res.set_file_content("./www/dir/test.html");
  11656. res.set_content("body", "text/plain");
  11657. });
  11658. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11659. res.set_content(std::string(100, 'B'), "text/plain");
  11660. res.set_file_content("./www/dir/test.html");
  11661. });
  11662. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11663. res.set_content(std::string(100, 'B'), "text/plain");
  11664. res.set_content_provider(3, "text/x-provider", abc);
  11665. });
  11666. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11667. res.set_content_provider(3, "text/x-provider", abc);
  11668. res.set_content(std::string(100, 'B'), "text/plain");
  11669. });
  11670. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11671. res.set_content_provider(3, "text/x-provider", abc);
  11672. res.set_file_content("./www/dir/test.html", "text/x-file");
  11673. });
  11674. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11675. res.set_file_content("./www/dir/test.html");
  11676. res.set_header("Content-Type", "text/x-handler");
  11677. });
  11678. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11679. res.set_content_provider(3, "text/plain", abc);
  11680. res.body = "direct";
  11681. });
  11682. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11683. res.set_file_content("./www/dir/test.html");
  11684. res.body = "direct";
  11685. });
  11686. auto port = svr.bind_to_any_port(HOST);
  11687. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11688. auto se = detail::scope_exit([&] {
  11689. svr.stop();
  11690. t.join();
  11691. ASSERT_FALSE(svr.is_running());
  11692. });
  11693. svr.wait_until_ready();
  11694. Client cli(HOST, port);
  11695. auto expect_body = [&](const char *path, const std::string &body,
  11696. const std::string &type) {
  11697. // Uncompressed, so Content-Length can be compared with the body.
  11698. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11699. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11700. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11701. EXPECT_EQ(body, res->body) << path;
  11702. EXPECT_EQ(std::to_string(body.size()),
  11703. res->get_header_value("Content-Length"))
  11704. << path;
  11705. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11706. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11707. };
  11708. expect_body("/file-then-body", "body", "text/plain");
  11709. expect_body("/body-then-file", "test.html", "text/html");
  11710. expect_body("/body-then-provider", "abc", "text/x-provider");
  11711. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11712. expect_body("/provider-then-file", "test.html", "text/x-file");
  11713. expect_body("/file-then-header", "test.html", "text/x-handler");
  11714. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11715. expect_body("/file-then-direct-body", "direct", "text/plain");
  11716. // Ranges are checked against the body, not the dropped provider.
  11717. {
  11718. auto res = cli.Get("/provider-then-direct-body",
  11719. Headers{{make_range_header({{1, 2}})}});
  11720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11722. EXPECT_EQ("ir", res->body);
  11723. }
  11724. {
  11725. auto res = cli.Get("/file-then-direct-body",
  11726. Headers{{make_range_header({{7, 8}})}});
  11727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11728. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11729. }
  11730. }
  11731. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11732. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11733. const char *path = "./truncated_while_served.txt";
  11734. const size_t size = 32 * 1024 * 1024;
  11735. {
  11736. std::ofstream f(path, std::ios::binary);
  11737. f << std::string(size, 'x');
  11738. }
  11739. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11740. // Over TLS, where the bytes are encrypted in this process rather than
  11741. // copied by send().
  11742. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11743. svr.Get("/file", [&](const Request &, Response &res) {
  11744. res.set_file_content(path, "text/plain");
  11745. });
  11746. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11747. auto se = detail::scope_exit([&] {
  11748. svr.stop();
  11749. thread.join();
  11750. ASSERT_FALSE(svr.is_running());
  11751. });
  11752. svr.wait_until_ready();
  11753. // The file shrinks once the first bytes are in, as a rewrite in place
  11754. // would, and reading the mapping past its new end used to raise SIGBUS.
  11755. SSLClient cli(HOST, PORT);
  11756. cli.enable_server_certificate_verification(false);
  11757. size_t received = 0;
  11758. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11759. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11760. received += len;
  11761. return true;
  11762. });
  11763. EXPECT_FALSE(res);
  11764. EXPECT_LT(received, size);
  11765. }
  11766. #endif
  11767. // Forward declaration (see the base64_encode note).
  11768. namespace httplib {
  11769. namespace detail {
  11770. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11771. const std::string &content_type,
  11772. EncodingType encoding);
  11773. } // namespace detail
  11774. } // namespace httplib
  11775. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11776. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11777. ASSERT_TRUE(mm->is_open());
  11778. Response res;
  11779. detail::set_file_content_provider(res, mm, "text/html",
  11780. detail::EncodingType::None);
  11781. std::string out;
  11782. DataSink sink;
  11783. sink.write = [&](const char *d, size_t l) {
  11784. out.append(d, l);
  11785. return true;
  11786. };
  11787. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11788. EXPECT_EQ("test.html", out);
  11789. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11790. EXPECT_EQ("test.html", out);
  11791. }
  11792. TEST(LongPollingTest, ClientCloseDetection) {
  11793. Server svr;
  11794. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11795. res.set_chunked_content_provider(
  11796. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11797. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11798. sink.os << "hello";
  11799. auto count = 10;
  11800. while (count > 0 && sink.is_writable()) {
  11801. this_thread::sleep_for(chrono::milliseconds(10));
  11802. count--;
  11803. }
  11804. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11805. return true;
  11806. });
  11807. });
  11808. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11809. auto se = detail::scope_exit([&] {
  11810. svr.stop();
  11811. listen_thread.join();
  11812. ASSERT_FALSE(svr.is_running());
  11813. });
  11814. svr.wait_until_ready();
  11815. Client cli("localhost", PORT);
  11816. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11817. EXPECT_EQ("hello", string(data, data_length));
  11818. return false; // close the socket immediately.
  11819. });
  11820. ASSERT_FALSE(res);
  11821. }
  11822. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11823. Server svr;
  11824. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11825. res.set_chunked_content_provider(
  11826. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11827. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11828. sink.os << "hello";
  11829. EXPECT_TRUE(sink.os.good());
  11830. // Wait for the client to close the connection
  11831. auto count = 10;
  11832. while (count > 0 && sink.is_writable()) {
  11833. this_thread::sleep_for(chrono::milliseconds(10));
  11834. count--;
  11835. }
  11836. // After client disconnect, write repeatedly until the socket
  11837. // write actually fails (small writes may be absorbed by the
  11838. // kernel buffer)
  11839. std::string chunk(1024, 'x');
  11840. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11841. sink.os << chunk;
  11842. }
  11843. EXPECT_TRUE(sink.os.fail());
  11844. return true;
  11845. });
  11846. });
  11847. auto port = svr.bind_to_any_port("localhost");
  11848. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11849. auto se = detail::scope_exit([&] {
  11850. svr.stop();
  11851. listen_thread.join();
  11852. ASSERT_FALSE(svr.is_running());
  11853. });
  11854. svr.wait_until_ready();
  11855. Client cli("localhost", port);
  11856. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11857. EXPECT_EQ("hello", string(data, data_length));
  11858. return false; // close the socket immediately.
  11859. });
  11860. ASSERT_FALSE(res);
  11861. }
  11862. TEST(GetWithParametersTest, GetWithParameters) {
  11863. Server svr;
  11864. svr.Get("/", [&](const Request &req, Response &) {
  11865. EXPECT_EQ("world", req.get_param_value("hello"));
  11866. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11867. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11868. });
  11869. svr.Get("/params", [&](const Request &req, Response &) {
  11870. EXPECT_EQ("world", req.get_param_value("hello"));
  11871. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11872. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11873. });
  11874. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11875. EXPECT_EQ("resource-id", req.matches[1]);
  11876. EXPECT_EQ("foo", req.get_param_value("param1"));
  11877. EXPECT_EQ("bar", req.get_param_value("param2"));
  11878. });
  11879. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11880. EXPECT_EQ("user-id", req.path_params.at("id"));
  11881. EXPECT_EQ("foo", req.get_param_value("param1"));
  11882. EXPECT_EQ("bar", req.get_param_value("param2"));
  11883. });
  11884. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11885. auto se = detail::scope_exit([&] {
  11886. svr.stop();
  11887. listen_thread.join();
  11888. ASSERT_FALSE(svr.is_running());
  11889. });
  11890. svr.wait_until_ready();
  11891. {
  11892. Client cli(HOST, PORT);
  11893. Params params;
  11894. params.emplace("hello", "world");
  11895. params.emplace("hello2", "world2");
  11896. params.emplace("hello3", "world3");
  11897. auto res = cli.Get("/", params, Headers{});
  11898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11899. EXPECT_EQ(StatusCode::OK_200, res->status);
  11900. }
  11901. {
  11902. Client cli(HOST, PORT);
  11903. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11905. EXPECT_EQ(StatusCode::OK_200, res->status);
  11906. }
  11907. {
  11908. Client cli(HOST, PORT);
  11909. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11911. EXPECT_EQ(StatusCode::OK_200, res->status);
  11912. }
  11913. {
  11914. Client cli(HOST, PORT);
  11915. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11917. EXPECT_EQ(StatusCode::OK_200, res->status);
  11918. }
  11919. }
  11920. TEST(GetWithParametersTest, GetWithParameters2) {
  11921. Server svr;
  11922. svr.Get("/", [&](const Request &req, Response &res) {
  11923. auto text = req.get_param_value("hello");
  11924. res.set_content(text, "text/plain");
  11925. });
  11926. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11927. auto se = detail::scope_exit([&] {
  11928. svr.stop();
  11929. listen_thread.join();
  11930. ASSERT_FALSE(svr.is_running());
  11931. });
  11932. svr.wait_until_ready();
  11933. Client cli("localhost", PORT);
  11934. Params params;
  11935. params.emplace("hello", "world");
  11936. std::string body;
  11937. auto res = cli.Get("/", params, Headers{},
  11938. [&](const char *data, size_t data_length) {
  11939. body.append(data, data_length);
  11940. return true;
  11941. });
  11942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11943. EXPECT_EQ(StatusCode::OK_200, res->status);
  11944. EXPECT_EQ("world", body);
  11945. }
  11946. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11947. Server svr;
  11948. svr.Get("/search", [&](const Request &req, Response &res) {
  11949. auto q = req.get_param_value("q");
  11950. res.set_content(q, "text/plain");
  11951. });
  11952. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11953. auto se = detail::scope_exit([&] {
  11954. svr.stop();
  11955. listen_thread.join();
  11956. ASSERT_FALSE(svr.is_running());
  11957. });
  11958. svr.wait_until_ready();
  11959. Client cli("localhost", PORT);
  11960. // Verify that Get(path, params) works without requiring Headers argument
  11961. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11963. EXPECT_EQ(StatusCode::OK_200, res->status);
  11964. EXPECT_EQ("cpp-httplib", res->body);
  11965. }
  11966. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11967. auto host = "httpbingo.org";
  11968. auto path = std::string{"/range/32"};
  11969. #ifdef CPPHTTPLIB_SSL_ENABLED
  11970. SSLClient cli(host);
  11971. #else
  11972. Client cli(host);
  11973. #endif
  11974. cli.set_default_headers({make_range_header({{1, 10}})});
  11975. cli.set_connection_timeout(5);
  11976. {
  11977. auto res = cli.Get(path);
  11978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11979. EXPECT_EQ("bcdefghijk", res->body);
  11980. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11981. }
  11982. {
  11983. auto res = cli.Get(path);
  11984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11985. EXPECT_EQ("bcdefghijk", res->body);
  11986. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11987. }
  11988. }
  11989. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11990. Server svr;
  11991. svr.set_default_headers({{"Hello", "World"}});
  11992. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11993. res.set_content("ok", "text/plain");
  11994. });
  11995. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11996. auto se = detail::scope_exit([&] {
  11997. svr.stop();
  11998. listen_thread.join();
  11999. ASSERT_FALSE(svr.is_running());
  12000. });
  12001. svr.wait_until_ready();
  12002. Client cli("localhost", PORT);
  12003. auto res = cli.Get("/");
  12004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12005. EXPECT_EQ(StatusCode::OK_200, res->status);
  12006. EXPECT_EQ("ok", res->body);
  12007. EXPECT_EQ("World", res->get_header_value("Hello"));
  12008. }
  12009. #ifdef CPPHTTPLIB_SSL_ENABLED
  12010. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12011. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12012. ASSERT_TRUE(svr.is_valid());
  12013. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12014. std::this_thread::sleep_for(std::chrono::seconds(2));
  12015. res.set_content("a", "text/plain");
  12016. });
  12017. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12018. res.set_content("b", "text/plain");
  12019. });
  12020. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12021. auto se = detail::scope_exit([&] {
  12022. svr.stop();
  12023. listen_thread.join();
  12024. ASSERT_FALSE(svr.is_running());
  12025. });
  12026. svr.wait_until_ready();
  12027. SSLClient cli("localhost", PORT);
  12028. cli.enable_server_certificate_verification(false);
  12029. cli.set_keep_alive(true);
  12030. cli.set_read_timeout(std::chrono::seconds(1));
  12031. auto resa = cli.Get("/a");
  12032. ASSERT_TRUE(!resa);
  12033. EXPECT_EQ(Error::Read, resa.error());
  12034. auto resb = cli.Get("/b");
  12035. ASSERT_TRUE(resb);
  12036. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12037. EXPECT_EQ("b", resb->body);
  12038. }
  12039. // Closing an idle keep-alive connection sends close_notify and returns. The
  12040. // server must not wait for the client's close_notify: an idle client never
  12041. // sends one, so the worker would be held until the read timeout expires, and
  12042. // stop() would wait for it.
  12043. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12044. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12045. ASSERT_TRUE(svr.is_valid());
  12046. svr.set_keep_alive_timeout(1);
  12047. svr.set_read_timeout(10, 0);
  12048. svr.Get("/", [](const Request &, Response &res) {
  12049. res.set_content("ok", "text/plain");
  12050. });
  12051. auto port = svr.bind_to_any_port(HOST);
  12052. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12053. auto se = detail::scope_exit([&] {
  12054. if (listen_thread.joinable()) {
  12055. svr.stop();
  12056. listen_thread.join();
  12057. }
  12058. });
  12059. svr.wait_until_ready();
  12060. SSLClient cli(HOST, port);
  12061. cli.enable_server_certificate_verification(false);
  12062. cli.set_keep_alive(true);
  12063. auto res = cli.Get("/");
  12064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12065. EXPECT_EQ(StatusCode::OK_200, res->status);
  12066. // Stay idle past the keep-alive timeout so the server closes the connection.
  12067. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12068. auto start = std::chrono::steady_clock::now();
  12069. svr.stop();
  12070. listen_thread.join();
  12071. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12072. std::chrono::steady_clock::now() - start)
  12073. .count();
  12074. EXPECT_LT(elapsed, 3000);
  12075. }
  12076. #endif
  12077. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12078. protected:
  12079. ServerTestWithAI_PASSIVE()
  12080. : cli_(HOST, PORT)
  12081. #ifdef CPPHTTPLIB_SSL_ENABLED
  12082. ,
  12083. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12084. #endif
  12085. {
  12086. #ifdef CPPHTTPLIB_SSL_ENABLED
  12087. cli_.enable_server_certificate_verification(false);
  12088. #endif
  12089. }
  12090. virtual void SetUp() {
  12091. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12092. res.set_content("Hello World!", "text/plain");
  12093. });
  12094. t_ = thread(
  12095. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12096. svr_.wait_until_ready();
  12097. }
  12098. virtual void TearDown() {
  12099. svr_.stop();
  12100. t_.join();
  12101. }
  12102. #ifdef CPPHTTPLIB_SSL_ENABLED
  12103. SSLClient cli_;
  12104. SSLServer svr_;
  12105. #else
  12106. Client cli_;
  12107. Server svr_;
  12108. #endif
  12109. thread t_;
  12110. };
  12111. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12112. auto res = cli_.Get("/hi");
  12113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12114. EXPECT_EQ(StatusCode::OK_200, res->status);
  12115. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12116. EXPECT_EQ("Hello World!", res->body);
  12117. }
  12118. class ServerUpDownTest : public ::testing::Test {
  12119. protected:
  12120. ServerUpDownTest() : cli_(HOST, PORT) {}
  12121. virtual void SetUp() {
  12122. t_ = thread([&]() {
  12123. svr_.bind_to_any_port(HOST);
  12124. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12125. ASSERT_TRUE(svr_.listen_after_bind());
  12126. });
  12127. svr_.wait_until_ready();
  12128. }
  12129. virtual void TearDown() {
  12130. svr_.stop();
  12131. t_.join();
  12132. }
  12133. Client cli_;
  12134. Server svr_;
  12135. thread t_;
  12136. };
  12137. TEST_F(ServerUpDownTest, QuickStartStop) {
  12138. // Should not crash, especially when run with
  12139. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12140. }
  12141. class PayloadMaxLengthTest : public ::testing::Test {
  12142. protected:
  12143. PayloadMaxLengthTest()
  12144. : cli_(HOST, PORT)
  12145. #ifdef CPPHTTPLIB_SSL_ENABLED
  12146. ,
  12147. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12148. #endif
  12149. {
  12150. #ifdef CPPHTTPLIB_SSL_ENABLED
  12151. cli_.enable_server_certificate_verification(false);
  12152. #endif
  12153. }
  12154. virtual void SetUp() {
  12155. svr_.set_payload_max_length(8);
  12156. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12157. res.set_content("test", "text/plain");
  12158. });
  12159. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12160. svr_.wait_until_ready();
  12161. }
  12162. virtual void TearDown() {
  12163. svr_.stop();
  12164. t_.join();
  12165. }
  12166. #ifdef CPPHTTPLIB_SSL_ENABLED
  12167. SSLClient cli_;
  12168. SSLServer svr_;
  12169. #else
  12170. Client cli_;
  12171. Server svr_;
  12172. #endif
  12173. thread t_;
  12174. };
  12175. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12176. auto res = cli_.Post("/test", "123456789", "text/plain");
  12177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12178. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12179. res = cli_.Post("/test", "12345678", "text/plain");
  12180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12181. EXPECT_EQ(StatusCode::OK_200, res->status);
  12182. }
  12183. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12184. // Test chunked encoding with payload exceeding the 8-byte limit
  12185. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12186. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12188. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12189. }
  12190. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12191. // Test chunked encoding with payload within the 8-byte limit
  12192. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12193. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12195. EXPECT_EQ(StatusCode::OK_200, res->status);
  12196. }
  12197. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12198. // Test using send_request to send chunked data exceeding payload limit
  12199. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12200. "Host: " +
  12201. std::string(HOST) + ":" + std::to_string(PORT) +
  12202. "\r\n"
  12203. "Transfer-Encoding: chunked\r\n"
  12204. "Connection: close\r\n"
  12205. "\r\n"
  12206. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12207. "0123456789\r\n"
  12208. "0\r\n" // End chunk
  12209. "\r\n";
  12210. std::string response;
  12211. bool result = send_request(1, chunked_request, &response);
  12212. if (!result) {
  12213. // If send_request fails, it might be because the server closed the
  12214. // connection due to payload limit enforcement, which is acceptable
  12215. SUCCEED()
  12216. << "Server rejected oversized chunked request (connection closed)";
  12217. } else {
  12218. // If we got a response, check if it's an error response or connection was
  12219. // closed early Short response length indicates connection was closed due to
  12220. // payload limit
  12221. if (response.length() <= 10) {
  12222. SUCCEED() << "Server closed connection for oversized chunked request";
  12223. } else {
  12224. // Check for error status codes
  12225. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12226. response.find("Payload Too Large") != std::string::npos ||
  12227. response.find("400") != std::string::npos);
  12228. }
  12229. }
  12230. }
  12231. class LargePayloadMaxLengthTest : public ::testing::Test {
  12232. protected:
  12233. LargePayloadMaxLengthTest()
  12234. : cli_(HOST, PORT)
  12235. #ifdef CPPHTTPLIB_SSL_ENABLED
  12236. ,
  12237. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12238. #endif
  12239. {
  12240. #ifdef CPPHTTPLIB_SSL_ENABLED
  12241. cli_.enable_server_certificate_verification(false);
  12242. #endif
  12243. }
  12244. virtual void SetUp() {
  12245. // Set 10MB payload limit
  12246. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12247. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12248. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12249. res.set_content("Large payload test", "text/plain");
  12250. });
  12251. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12252. svr_.wait_until_ready();
  12253. }
  12254. virtual void TearDown() {
  12255. svr_.stop();
  12256. t_.join();
  12257. }
  12258. #ifdef CPPHTTPLIB_SSL_ENABLED
  12259. SSLClient cli_;
  12260. SSLServer svr_;
  12261. #else
  12262. Client cli_;
  12263. Server svr_;
  12264. #endif
  12265. thread t_;
  12266. };
  12267. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12268. // Test chunked encoding with payload within 10MB limit
  12269. std::string medium_payload(5 * 1024 * 1024,
  12270. 'A'); // 5MB payload, within 10MB limit
  12271. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12273. EXPECT_EQ(StatusCode::OK_200, res->status);
  12274. }
  12275. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12276. // Test chunked encoding with payload exceeding 10MB limit
  12277. std::string large_payload(12 * 1024 * 1024,
  12278. 'B'); // 12MB payload, exceeds 10MB limit
  12279. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12280. // Server may either return 413 or close the connection
  12281. if (res) {
  12282. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12283. } else {
  12284. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12285. }
  12286. }
  12287. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12288. Server svr;
  12289. svr.Get("/", [](const Request &, Response &res) {
  12290. // Claims the most the client accepts, far more than it sends, then drops
  12291. // the connection.
  12292. res.set_content_provider(std::string().max_size(), "text/plain",
  12293. [](size_t, size_t, DataSink &sink) {
  12294. sink.write("abc", 3);
  12295. return false;
  12296. });
  12297. });
  12298. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12299. auto se = detail::scope_exit([&] {
  12300. svr.stop();
  12301. thread.join();
  12302. ASSERT_FALSE(svr.is_running());
  12303. });
  12304. svr.wait_until_ready();
  12305. Client cli(HOST, PORT);
  12306. cli.set_payload_max_length(0);
  12307. EXPECT_FALSE(cli.Get("/"));
  12308. }
  12309. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12310. // Stream API does, not as a plain read failure
  12311. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12312. Server svr;
  12313. svr.Get("/big", [](const Request &, Response &res) {
  12314. res.set_content(std::string(100000, 'b'), "text/plain");
  12315. });
  12316. auto port = svr.bind_to_any_port(HOST);
  12317. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12318. auto se = detail::scope_exit([&] {
  12319. svr.stop();
  12320. thread.join();
  12321. });
  12322. svr.wait_until_ready();
  12323. Client cli(HOST, port);
  12324. cli.set_payload_max_length(1000);
  12325. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12326. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12327. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12328. [](const char *, size_t) { return true; });
  12329. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12330. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12331. // Small on the wire, over the limit once decompressed
  12332. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12333. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12334. #endif
  12335. }
  12336. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12337. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12338. // path.
  12339. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12340. Server svr;
  12341. const size_t LIMIT = 64 * 1024; // 64KB
  12342. svr.set_payload_max_length(LIMIT);
  12343. size_t total = 0;
  12344. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12345. const ContentReader &content_reader) {
  12346. content_reader([&](const char * /*data*/, size_t len) {
  12347. total += len;
  12348. return true;
  12349. });
  12350. res.status = 200;
  12351. res.set_content("stream_ok", "text/plain");
  12352. });
  12353. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12354. auto se = detail::scope_exit([&] {
  12355. svr.stop();
  12356. thread.join();
  12357. ASSERT_FALSE(svr.is_running());
  12358. });
  12359. svr.wait_until_ready();
  12360. // Prepare 256KB raw data and gzip-compress it
  12361. std::string raw(256 * 1024, 'A');
  12362. std::string gz;
  12363. {
  12364. z_stream zs{};
  12365. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12366. Z_DEFAULT_STRATEGY);
  12367. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12368. zs.avail_in = static_cast<uInt>(raw.size());
  12369. char outbuf[4096];
  12370. int ret;
  12371. do {
  12372. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12373. zs.avail_out = sizeof(outbuf);
  12374. ret = deflate(&zs, Z_FINISH);
  12375. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12376. } while (ret != Z_STREAM_END);
  12377. deflateEnd(&zs);
  12378. }
  12379. Client cli(HOST, PORT);
  12380. cli.set_connection_timeout(std::chrono::seconds(5));
  12381. Headers headers = {{"Content-Encoding", "gzip"}};
  12382. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12383. "application/octet-stream");
  12384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12385. // Server must reject oversized decompressed payloads with 413.
  12386. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12387. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12388. EXPECT_LE(total, LIMIT);
  12389. }
  12390. #endif
  12391. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12392. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12393. // the payload must be passed through untouched instead of being rejected.
  12394. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12395. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12396. Server svr;
  12397. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12398. res.set_content(body, "image/jpeg");
  12399. res.set_header("Content-Encoding", "UTF-8");
  12400. });
  12401. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12402. res.set_content(body, "image/jpeg");
  12403. res.set_header("Content-Encoding", "identity");
  12404. });
  12405. svr.Post("/echo", [](const Request &req, Response &res) {
  12406. res.set_content(req.body, "image/jpeg");
  12407. });
  12408. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12409. auto se = detail::scope_exit([&] {
  12410. svr.stop();
  12411. t.join();
  12412. ASSERT_FALSE(svr.is_running());
  12413. });
  12414. svr.wait_until_ready();
  12415. Client cli(HOST, PORT);
  12416. {
  12417. auto res = cli.Get("/image");
  12418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12419. EXPECT_EQ(StatusCode::OK_200, res->status);
  12420. EXPECT_EQ(body, res->body);
  12421. }
  12422. {
  12423. auto res = cli.Get("/identity");
  12424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12425. EXPECT_EQ(StatusCode::OK_200, res->status);
  12426. EXPECT_EQ(body, res->body);
  12427. }
  12428. {
  12429. // The same applies to a request body reaching the server.
  12430. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12431. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12433. EXPECT_EQ(StatusCode::OK_200, res->status);
  12434. EXPECT_EQ(body, res->body);
  12435. }
  12436. }
  12437. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12438. // gzip-encoded response even when the build has no zlib support.
  12439. static const char GZIPPED_HELLO_WORLD[] = {
  12440. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12441. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12442. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12443. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12444. // A content coding is a whole token, not something the field value merely
  12445. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12446. // as "fibre" look like Brotli, and turned a multi-coding value like
  12447. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12448. // it was never meant to see.
  12449. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12450. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12451. Server svr;
  12452. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12453. res.set_content(body, "image/jpeg");
  12454. res.set_header("Content-Encoding", "fibre");
  12455. });
  12456. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12457. res.set_content(body, "image/jpeg");
  12458. res.set_header("Content-Encoding", "gzip, br");
  12459. });
  12460. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12461. res.set_content(body, "image/jpeg");
  12462. res.set_header("Content-Encoding", "x-zstd-ish");
  12463. });
  12464. auto port = svr.bind_to_any_port(HOST);
  12465. thread t = thread([&]() { svr.listen_after_bind(); });
  12466. auto se = detail::scope_exit([&] {
  12467. svr.stop();
  12468. t.join();
  12469. ASSERT_FALSE(svr.is_running());
  12470. });
  12471. svr.wait_until_ready();
  12472. Client cli(HOST, port);
  12473. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12474. auto res = cli.Get(path);
  12475. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12476. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12477. // Not a coding we recognize, so the payload comes back untouched
  12478. EXPECT_EQ(body, res->body) << path;
  12479. }
  12480. }
  12481. // A content coding cpp-httplib recognizes but was not built with must be
  12482. // reported as such. Handing the still-compressed payload back to the caller
  12483. // would silently corrupt it.
  12484. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12485. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12486. Server svr;
  12487. // "image/jpeg" keeps the server from applying a content coding of its own,
  12488. // so the hand-crafted Content-Encoding below survives.
  12489. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12490. res.set_content(gzipped, "image/jpeg");
  12491. res.set_header("Content-Encoding", "gzip");
  12492. });
  12493. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12494. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12495. res.set_content(gzipped, "image/jpeg");
  12496. res.set_header("Content-Encoding", "GZIP");
  12497. });
  12498. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12499. auto se = detail::scope_exit([&] {
  12500. svr.stop();
  12501. t.join();
  12502. ASSERT_FALSE(svr.is_running());
  12503. });
  12504. svr.wait_until_ready();
  12505. Client cli(HOST, PORT);
  12506. {
  12507. auto res = cli.Get("/gzipped");
  12508. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12510. EXPECT_EQ("Hello World!", res->body);
  12511. #else
  12512. ASSERT_FALSE(res);
  12513. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12514. #endif
  12515. }
  12516. {
  12517. // open_stream() must behave the same way.
  12518. auto handle = cli.open_stream("GET", "/gzipped");
  12519. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12520. ASSERT_TRUE(handle.is_valid());
  12521. std::string received;
  12522. char buf[256];
  12523. ssize_t n;
  12524. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12525. received.append(buf, static_cast<size_t>(n));
  12526. }
  12527. EXPECT_EQ("Hello World!", received);
  12528. #else
  12529. EXPECT_FALSE(handle.is_valid());
  12530. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12531. #endif
  12532. }
  12533. {
  12534. // A differently-cased coding must not be mistaken for an unknown one, or
  12535. // the body would be handed back still compressed.
  12536. auto res = cli.Get("/gzipped-uppercase");
  12537. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12539. EXPECT_EQ("Hello World!", res->body);
  12540. #else
  12541. ASSERT_FALSE(res);
  12542. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12543. #endif
  12544. }
  12545. }
  12546. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12547. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12548. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12549. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12550. // body a second time and appending a second Content-Encoding field line, so
  12551. // clients that decode one coding per listed value handed back raw gzip bytes.
  12552. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12553. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12554. Server svr;
  12555. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12556. // keeps the server from applying a coding of its own.
  12557. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12558. res.set_content(gzipped, "text/plain");
  12559. res.set_header("Content-Encoding", "gzip");
  12560. });
  12561. auto port = svr.bind_to_any_port(HOST);
  12562. thread t = thread([&]() { svr.listen_after_bind(); });
  12563. auto se = detail::scope_exit([&] {
  12564. svr.stop();
  12565. t.join();
  12566. ASSERT_FALSE(svr.is_running());
  12567. });
  12568. svr.wait_until_ready();
  12569. Client cli(HOST, port);
  12570. Headers headers = {{"Accept-Encoding", "gzip"}};
  12571. auto res = cli.Get("/pre-gzipped", headers);
  12572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12573. EXPECT_EQ(StatusCode::OK_200, res->status);
  12574. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12575. EXPECT_EQ("Hello World!", res->body);
  12576. }
  12577. // set_compress(false) sends every handler response as it is, buffered or
  12578. // streamed
  12579. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12580. const std::string text(1000, 'a');
  12581. Server svr;
  12582. svr.set_compress(false);
  12583. svr.Get("/buffered", [&](const Request &, Response &res) {
  12584. res.set_content(text, "text/plain");
  12585. });
  12586. svr.Get("/streamed", [&](const Request &, Response &res) {
  12587. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12588. sink.write(text.data(), text.size());
  12589. sink.done();
  12590. return true;
  12591. });
  12592. });
  12593. auto port = svr.bind_to_any_port(HOST);
  12594. ASSERT_LT(0, port);
  12595. thread t = thread([&] { svr.listen_after_bind(); });
  12596. auto se = detail::scope_exit([&] {
  12597. svr.stop();
  12598. t.join();
  12599. ASSERT_FALSE(svr.is_running());
  12600. });
  12601. svr.wait_until_ready();
  12602. Client cli(HOST, port);
  12603. cli.set_decompress(false);
  12604. for (auto path : {"/buffered", "/streamed"}) {
  12605. SCOPED_TRACE(path);
  12606. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12608. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12609. EXPECT_EQ(text, res->body);
  12610. }
  12611. }
  12612. // A chunked provider settles its coding where the headers are written and
  12613. // reuses it at write time. Both ends of that have to hold: a handler's own
  12614. // Content-Encoding suppresses the coding, and a response without one is still
  12615. // compressed as it always was.
  12616. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12617. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12618. const std::string plain = "Hello World! Hello World! Hello World!";
  12619. Server svr;
  12620. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12621. res.set_header("Content-Encoding", "gzip");
  12622. res.set_chunked_content_provider(
  12623. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12624. sink.write(gzipped.data(), gzipped.size());
  12625. sink.done();
  12626. return true;
  12627. });
  12628. });
  12629. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12630. res.set_chunked_content_provider(
  12631. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12632. sink.write(plain.data(), plain.size());
  12633. sink.done();
  12634. return true;
  12635. });
  12636. });
  12637. auto port = svr.bind_to_any_port(HOST);
  12638. thread t = thread([&]() { svr.listen_after_bind(); });
  12639. auto se = detail::scope_exit([&] {
  12640. svr.stop();
  12641. t.join();
  12642. ASSERT_FALSE(svr.is_running());
  12643. });
  12644. svr.wait_until_ready();
  12645. Client cli(HOST, port);
  12646. Headers headers = {{"Accept-Encoding", "gzip"}};
  12647. {
  12648. auto res = cli.Get("/pre-gzipped", headers);
  12649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12650. EXPECT_EQ(StatusCode::OK_200, res->status);
  12651. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12652. EXPECT_EQ("Hello World!", res->body);
  12653. }
  12654. {
  12655. auto res = cli.Get("/negotiated", headers);
  12656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12657. EXPECT_EQ(StatusCode::OK_200, res->status);
  12658. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12659. EXPECT_EQ(plain, res->body);
  12660. }
  12661. }
  12662. #endif
  12663. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12664. // the same message as the comma-joined one, so both have to be read the same
  12665. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12666. // single gzip coding, and a body the sender says was encoded twice was handed
  12667. // back after one pass, still compressed but presented as decoded.
  12668. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12669. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12670. Server svr;
  12671. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12672. res.set_content(body, "image/jpeg");
  12673. res.headers.emplace("Content-Encoding", "gzip");
  12674. res.headers.emplace("Content-Encoding", "gzip");
  12675. });
  12676. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12677. res.set_content(body, "image/jpeg");
  12678. res.set_header("Content-Encoding", "gzip, gzip");
  12679. });
  12680. auto port = svr.bind_to_any_port(HOST);
  12681. thread t = thread([&]() { svr.listen_after_bind(); });
  12682. auto se = detail::scope_exit([&] {
  12683. svr.stop();
  12684. t.join();
  12685. ASSERT_FALSE(svr.is_running());
  12686. });
  12687. svr.wait_until_ready();
  12688. Client cli(HOST, port);
  12689. // Two codings is not something cpp-httplib decodes, so both representations
  12690. // take the pass-through path rather than one of them being gunzipped once.
  12691. for (const char *path : {"/split", "/joined"}) {
  12692. auto res = cli.Get(path);
  12693. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12694. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12695. EXPECT_EQ(body, res->body) << path;
  12696. }
  12697. }
  12698. // Regression test for DoS vulnerability: a malicious server sending a response
  12699. // without Content-Length header must not cause unbounded memory consumption on
  12700. // the client side. The client should stop reading after a reasonable limit,
  12701. // similar to the server-side set_payload_max_length protection.
  12702. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12703. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12704. #ifndef _WIN32
  12705. signal(SIGPIPE, SIG_IGN);
  12706. #endif
  12707. auto server_thread = std::thread([] {
  12708. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12709. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12710. default_socket_options(srv);
  12711. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12712. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12713. sockaddr_in addr{};
  12714. addr.sin_family = AF_INET;
  12715. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12716. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12717. int opt = 1;
  12718. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12719. #ifdef _WIN32
  12720. reinterpret_cast<const char *>(&opt),
  12721. #else
  12722. &opt,
  12723. #endif
  12724. sizeof(opt));
  12725. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12726. ::listen(srv, 1);
  12727. sockaddr_in cli_addr{};
  12728. socklen_t cli_len = sizeof(cli_addr);
  12729. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12730. if (cli != INVALID_SOCKET) {
  12731. char buf[4096];
  12732. ::recv(cli, buf, sizeof(buf), 0);
  12733. // Malicious response: no Content-Length, no chunked encoding
  12734. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12735. "Connection: close\r\n"
  12736. "\r\n";
  12737. ::send(cli,
  12738. #ifdef _WIN32
  12739. static_cast<const char *>(response_header.c_str()),
  12740. static_cast<int>(response_header.size()),
  12741. #else
  12742. response_header.c_str(), response_header.size(),
  12743. #endif
  12744. 0);
  12745. // Send 10MB of data
  12746. std::string chunk(64 * 1024, 'A');
  12747. size_t total_sent = 0;
  12748. while (total_sent < MALICIOUS_DATA_SIZE) {
  12749. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12750. auto sent = ::send(cli,
  12751. #ifdef _WIN32
  12752. static_cast<const char *>(chunk.c_str()),
  12753. static_cast<int>(to_send),
  12754. #else
  12755. chunk.c_str(), to_send,
  12756. #endif
  12757. 0);
  12758. if (sent <= 0) break;
  12759. total_sent += static_cast<size_t>(sent);
  12760. }
  12761. detail::close_socket(cli);
  12762. }
  12763. detail::close_socket(srv);
  12764. });
  12765. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12766. size_t total_read = 0;
  12767. {
  12768. Client cli("127.0.0.1", PORT + 2);
  12769. cli.set_read_timeout(5, 0);
  12770. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12771. auto stream = cli.open_stream("GET", "/malicious");
  12772. ASSERT_TRUE(stream.is_valid());
  12773. char buffer[64 * 1024];
  12774. ssize_t n;
  12775. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12776. total_read += static_cast<size_t>(n);
  12777. }
  12778. } // StreamHandle and Client destroyed here, closing the socket
  12779. server_thread.join();
  12780. // With set_payload_max_length, the client must stop reading before consuming
  12781. // all 10MB. The read loop should be cut off at or near the configured limit.
  12782. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12783. << "Client read " << total_read << " bytes, exceeding the configured "
  12784. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12785. }
  12786. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12787. // the entire response body without truncation.
  12788. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12789. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12790. #ifndef _WIN32
  12791. signal(SIGPIPE, SIG_IGN);
  12792. #endif
  12793. auto server_thread = std::thread([] {
  12794. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12795. default_socket_options(srv);
  12796. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12797. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12798. sockaddr_in addr{};
  12799. addr.sin_family = AF_INET;
  12800. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12801. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12802. int opt = 1;
  12803. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12804. #ifdef _WIN32
  12805. reinterpret_cast<const char *>(&opt),
  12806. #else
  12807. &opt,
  12808. #endif
  12809. sizeof(opt));
  12810. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12811. ::listen(srv, 1);
  12812. sockaddr_in cli_addr{};
  12813. socklen_t cli_len = sizeof(cli_addr);
  12814. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12815. if (cli != INVALID_SOCKET) {
  12816. char buf[4096];
  12817. ::recv(cli, buf, sizeof(buf), 0);
  12818. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12819. "Connection: close\r\n"
  12820. "\r\n";
  12821. ::send(cli,
  12822. #ifdef _WIN32
  12823. static_cast<const char *>(response_header.c_str()),
  12824. static_cast<int>(response_header.size()),
  12825. #else
  12826. response_header.c_str(), response_header.size(),
  12827. #endif
  12828. 0);
  12829. std::string chunk(64 * 1024, 'A');
  12830. size_t total_sent = 0;
  12831. while (total_sent < DATA_SIZE) {
  12832. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12833. auto sent = ::send(cli,
  12834. #ifdef _WIN32
  12835. static_cast<const char *>(chunk.c_str()),
  12836. static_cast<int>(to_send),
  12837. #else
  12838. chunk.c_str(), to_send,
  12839. #endif
  12840. 0);
  12841. if (sent <= 0) break;
  12842. total_sent += static_cast<size_t>(sent);
  12843. }
  12844. #ifdef _WIN32
  12845. ::shutdown(cli, SD_SEND);
  12846. #else
  12847. ::shutdown(cli, SHUT_WR);
  12848. #endif
  12849. // Drain until the client closes its end, ensuring all data is delivered
  12850. char drain[1024];
  12851. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12852. detail::close_socket(cli);
  12853. }
  12854. detail::close_socket(srv);
  12855. });
  12856. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12857. size_t total_read = 0;
  12858. {
  12859. Client cli("127.0.0.1", PORT + 2);
  12860. cli.set_read_timeout(5, 0);
  12861. cli.set_payload_max_length(0); // 0 means no limit
  12862. auto stream = cli.open_stream("GET", "/data");
  12863. ASSERT_TRUE(stream.is_valid());
  12864. char buffer[64 * 1024];
  12865. ssize_t n;
  12866. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12867. total_read += static_cast<size_t>(n);
  12868. }
  12869. }
  12870. server_thread.join();
  12871. EXPECT_EQ(total_read, DATA_SIZE)
  12872. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12873. << " bytes without truncation, but only read " << total_read << " bytes.";
  12874. }
  12875. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12876. // enormous Content-Length must not cause the client to pre-allocate a huge
  12877. // response body buffer. The reservation is capped at payload_max_length_, and
  12878. // the read itself fails when the body exceeds the limit.
  12879. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12880. #ifndef _WIN32
  12881. signal(SIGPIPE, SIG_IGN);
  12882. #endif
  12883. auto server_thread = std::thread([] {
  12884. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12885. default_socket_options(srv);
  12886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12887. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12888. sockaddr_in addr{};
  12889. addr.sin_family = AF_INET;
  12890. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12891. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12892. int opt = 1;
  12893. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12894. #ifdef _WIN32
  12895. reinterpret_cast<const char *>(&opt),
  12896. #else
  12897. &opt,
  12898. #endif
  12899. sizeof(opt));
  12900. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12901. ::listen(srv, 1);
  12902. sockaddr_in cli_addr{};
  12903. socklen_t cli_len = sizeof(cli_addr);
  12904. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12905. if (cli != INVALID_SOCKET) {
  12906. char buf[4096];
  12907. ::recv(cli, buf, sizeof(buf), 0);
  12908. // Malicious response: claim a 20GB body but send only a tiny payload.
  12909. std::string response = "HTTP/1.1 200 OK\r\n"
  12910. "Content-Length: 20000000000\r\n"
  12911. "\r\n"
  12912. "abc";
  12913. ::send(cli,
  12914. #ifdef _WIN32
  12915. static_cast<const char *>(response.c_str()),
  12916. static_cast<int>(response.size()),
  12917. #else
  12918. response.c_str(), response.size(),
  12919. #endif
  12920. 0);
  12921. detail::close_socket(cli);
  12922. }
  12923. detail::close_socket(srv);
  12924. });
  12925. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12926. {
  12927. Client cli("127.0.0.1", PORT + 2);
  12928. cli.set_read_timeout(5, 0);
  12929. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12930. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12931. // (server claims more bytes than payload_max_length permits), but it must
  12932. // not exhaust memory before getting there.
  12933. auto res = cli.Get("/malicious");
  12934. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12935. }
  12936. server_thread.join();
  12937. }
  12938. // Verify that content_receiver bypasses the default payload_max_length,
  12939. // allowing streaming downloads larger than 100MB without requiring an explicit
  12940. // set_payload_max_length call.
  12941. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12942. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12943. #ifndef _WIN32
  12944. signal(SIGPIPE, SIG_IGN);
  12945. #endif
  12946. auto server_thread = std::thread([] {
  12947. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12948. default_socket_options(srv);
  12949. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12950. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12951. sockaddr_in addr{};
  12952. addr.sin_family = AF_INET;
  12953. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12954. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12955. int opt = 1;
  12956. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12957. #ifdef _WIN32
  12958. reinterpret_cast<const char *>(&opt),
  12959. #else
  12960. &opt,
  12961. #endif
  12962. sizeof(opt));
  12963. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12964. ::listen(srv, 1);
  12965. sockaddr_in cli_addr{};
  12966. socklen_t cli_len = sizeof(cli_addr);
  12967. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12968. if (cli != INVALID_SOCKET) {
  12969. char buf[4096];
  12970. ::recv(cli, buf, sizeof(buf), 0);
  12971. // Response with Content-Length larger than default 100MB limit
  12972. auto content_length = std::to_string(DATA_SIZE);
  12973. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12974. "Content-Length: " +
  12975. content_length +
  12976. "\r\n"
  12977. "Connection: close\r\n"
  12978. "\r\n";
  12979. ::send(cli,
  12980. #ifdef _WIN32
  12981. static_cast<const char *>(response_header.c_str()),
  12982. static_cast<int>(response_header.size()),
  12983. #else
  12984. response_header.c_str(), response_header.size(),
  12985. #endif
  12986. 0);
  12987. std::string chunk(64 * 1024, 'A');
  12988. size_t total_sent = 0;
  12989. while (total_sent < DATA_SIZE) {
  12990. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12991. auto sent = ::send(cli,
  12992. #ifdef _WIN32
  12993. static_cast<const char *>(chunk.c_str()),
  12994. static_cast<int>(to_send),
  12995. #else
  12996. chunk.c_str(), to_send,
  12997. #endif
  12998. 0);
  12999. if (sent <= 0) break;
  13000. total_sent += static_cast<size_t>(sent);
  13001. }
  13002. detail::close_socket(cli);
  13003. }
  13004. detail::close_socket(srv);
  13005. });
  13006. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13007. size_t total_received = 0;
  13008. {
  13009. Client cli("127.0.0.1", PORT + 2);
  13010. cli.set_read_timeout(10, 0);
  13011. // Do NOT call set_payload_max_length — use the default 100MB limit
  13012. auto res =
  13013. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13014. total_received += data_length;
  13015. return true;
  13016. });
  13017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13018. EXPECT_EQ(StatusCode::OK_200, res->status);
  13019. }
  13020. server_thread.join();
  13021. EXPECT_EQ(total_received, DATA_SIZE)
  13022. << "With content_receiver, the client should read all " << DATA_SIZE
  13023. << " bytes despite the default 100MB payload_max_length, but only read "
  13024. << total_received << " bytes.";
  13025. }
  13026. // Verify that an explicit set_payload_max_length smaller than the response is
  13027. // enforced even when a content_receiver is used.
  13028. TEST(ClientVulnerabilityTest,
  13029. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13030. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13031. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13032. #ifndef _WIN32
  13033. signal(SIGPIPE, SIG_IGN);
  13034. #endif
  13035. auto server_thread = std::thread([] {
  13036. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13037. default_socket_options(srv);
  13038. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13039. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13040. sockaddr_in addr{};
  13041. addr.sin_family = AF_INET;
  13042. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13043. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13044. int opt = 1;
  13045. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13046. #ifdef _WIN32
  13047. reinterpret_cast<const char *>(&opt),
  13048. #else
  13049. &opt,
  13050. #endif
  13051. sizeof(opt));
  13052. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13053. ::listen(srv, 1);
  13054. sockaddr_in cli_addr{};
  13055. socklen_t cli_len = sizeof(cli_addr);
  13056. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13057. if (cli != INVALID_SOCKET) {
  13058. char buf[4096];
  13059. ::recv(cli, buf, sizeof(buf), 0);
  13060. auto content_length = std::to_string(DATA_SIZE);
  13061. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13062. "Content-Length: " +
  13063. content_length +
  13064. "\r\n"
  13065. "Connection: close\r\n"
  13066. "\r\n";
  13067. ::send(cli,
  13068. #ifdef _WIN32
  13069. static_cast<const char *>(response_header.c_str()),
  13070. static_cast<int>(response_header.size()),
  13071. #else
  13072. response_header.c_str(), response_header.size(),
  13073. #endif
  13074. 0);
  13075. std::string chunk(64 * 1024, 'A');
  13076. size_t total_sent = 0;
  13077. while (total_sent < DATA_SIZE) {
  13078. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13079. auto sent = ::send(cli,
  13080. #ifdef _WIN32
  13081. static_cast<const char *>(chunk.c_str()),
  13082. static_cast<int>(to_send),
  13083. #else
  13084. chunk.c_str(), to_send,
  13085. #endif
  13086. 0);
  13087. if (sent <= 0) break;
  13088. total_sent += static_cast<size_t>(sent);
  13089. }
  13090. detail::close_socket(cli);
  13091. }
  13092. detail::close_socket(srv);
  13093. });
  13094. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13095. size_t total_received = 0;
  13096. {
  13097. Client cli("127.0.0.1", PORT + 2);
  13098. cli.set_read_timeout(10, 0);
  13099. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13100. auto res =
  13101. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13102. total_received += data_length;
  13103. return true;
  13104. });
  13105. // Should fail because 200MB exceeds the explicit 150MB limit
  13106. EXPECT_FALSE(res);
  13107. }
  13108. server_thread.join();
  13109. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13110. << "Client with content_receiver should respect the explicit "
  13111. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13112. << total_received << " bytes.";
  13113. }
  13114. // Verify that an explicit set_payload_max_length larger than the response
  13115. // allows the content_receiver to read all data successfully.
  13116. TEST(ClientVulnerabilityTest,
  13117. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13118. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13119. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13120. #ifndef _WIN32
  13121. signal(SIGPIPE, SIG_IGN);
  13122. #endif
  13123. auto server_thread = std::thread([] {
  13124. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13125. default_socket_options(srv);
  13126. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13127. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13128. sockaddr_in addr{};
  13129. addr.sin_family = AF_INET;
  13130. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13131. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13132. int opt = 1;
  13133. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13134. #ifdef _WIN32
  13135. reinterpret_cast<const char *>(&opt),
  13136. #else
  13137. &opt,
  13138. #endif
  13139. sizeof(opt));
  13140. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13141. ::listen(srv, 1);
  13142. sockaddr_in cli_addr{};
  13143. socklen_t cli_len = sizeof(cli_addr);
  13144. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13145. if (cli != INVALID_SOCKET) {
  13146. char buf[4096];
  13147. ::recv(cli, buf, sizeof(buf), 0);
  13148. auto content_length = std::to_string(DATA_SIZE);
  13149. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13150. "Content-Length: " +
  13151. content_length +
  13152. "\r\n"
  13153. "Connection: close\r\n"
  13154. "\r\n";
  13155. ::send(cli,
  13156. #ifdef _WIN32
  13157. static_cast<const char *>(response_header.c_str()),
  13158. static_cast<int>(response_header.size()),
  13159. #else
  13160. response_header.c_str(), response_header.size(),
  13161. #endif
  13162. 0);
  13163. std::string chunk(64 * 1024, 'A');
  13164. size_t total_sent = 0;
  13165. while (total_sent < DATA_SIZE) {
  13166. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13167. auto sent = ::send(cli,
  13168. #ifdef _WIN32
  13169. static_cast<const char *>(chunk.c_str()),
  13170. static_cast<int>(to_send),
  13171. #else
  13172. chunk.c_str(), to_send,
  13173. #endif
  13174. 0);
  13175. if (sent <= 0) break;
  13176. total_sent += static_cast<size_t>(sent);
  13177. }
  13178. #ifdef _WIN32
  13179. ::shutdown(cli, SD_SEND);
  13180. #else
  13181. ::shutdown(cli, SHUT_WR);
  13182. #endif
  13183. char drain[1024];
  13184. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13185. detail::close_socket(cli);
  13186. }
  13187. detail::close_socket(srv);
  13188. });
  13189. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13190. size_t total_received = 0;
  13191. {
  13192. Client cli("127.0.0.1", PORT + 2);
  13193. cli.set_read_timeout(10, 0);
  13194. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13195. auto res =
  13196. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13197. total_received += data_length;
  13198. return true;
  13199. });
  13200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13201. EXPECT_EQ(StatusCode::OK_200, res->status);
  13202. }
  13203. server_thread.join();
  13204. EXPECT_EQ(total_received, DATA_SIZE)
  13205. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13206. << " bytes (larger than " << DATA_SIZE
  13207. << " bytes response), content_receiver should read all data, but only "
  13208. "read "
  13209. << total_received << " bytes.";
  13210. }
  13211. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13212. // Regression test for "zip bomb" attack on the client side: a malicious server
  13213. // sends a small gzip-compressed response that decompresses to a huge payload.
  13214. // The client must enforce payload_max_length on the decompressed size.
  13215. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13216. constexpr size_t DECOMPRESSED_SIZE =
  13217. 10 * 1024 * 1024; // 10MB after decompression
  13218. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13219. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13220. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13221. std::string compressed;
  13222. {
  13223. httplib::detail::gzip_compressor compressor;
  13224. bool ok =
  13225. compressor.compress(uncompressed.data(), uncompressed.size(),
  13226. /*last=*/true, [&](const char *buf, size_t len) {
  13227. compressed.append(buf, len);
  13228. return true;
  13229. });
  13230. ASSERT_TRUE(ok);
  13231. }
  13232. // Sanity: compressed data should be much smaller than the decompressed size
  13233. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13234. #ifndef _WIN32
  13235. signal(SIGPIPE, SIG_IGN);
  13236. #endif
  13237. // Set up the listening socket in the main thread so the server is guaranteed
  13238. // to be ready before the client connects (eliminates race condition).
  13239. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13240. default_socket_options(srv);
  13241. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13242. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13243. sockaddr_in addr{};
  13244. addr.sin_family = AF_INET;
  13245. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13246. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13247. int opt = 1;
  13248. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13249. #ifdef _WIN32
  13250. reinterpret_cast<const char *>(&opt),
  13251. #else
  13252. &opt,
  13253. #endif
  13254. sizeof(opt));
  13255. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13256. ASSERT_EQ(0, ::listen(srv, 1));
  13257. auto server_thread = std::thread([&compressed, srv] {
  13258. sockaddr_in cli_addr{};
  13259. socklen_t cli_len = sizeof(cli_addr);
  13260. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13261. if (cli != INVALID_SOCKET) {
  13262. // Read the full HTTP request (until \r\n\r\n)
  13263. char buf[4096];
  13264. size_t total = 0;
  13265. while (total < sizeof(buf)) {
  13266. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13267. if (n <= 0) break;
  13268. total += static_cast<size_t>(n);
  13269. // Check for end of headers
  13270. if (total >= 4) {
  13271. std::string req(buf, total);
  13272. if (req.find("\r\n\r\n") != std::string::npos) break;
  13273. }
  13274. }
  13275. // Malicious response: gzip-compressed body, no Content-Length
  13276. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13277. "Content-Encoding: gzip\r\n"
  13278. "Connection: close\r\n"
  13279. "\r\n";
  13280. ::send(cli,
  13281. #ifdef _WIN32
  13282. static_cast<const char *>(response_header.c_str()),
  13283. static_cast<int>(response_header.size()),
  13284. #else
  13285. response_header.c_str(), response_header.size(),
  13286. #endif
  13287. 0);
  13288. // Send the compressed payload (small on the wire, huge when decompressed)
  13289. size_t total_sent = 0;
  13290. while (total_sent < compressed.size()) {
  13291. auto to_send = std::min(compressed.size() - total_sent,
  13292. static_cast<size_t>(64 * 1024));
  13293. auto sent =
  13294. ::send(cli,
  13295. #ifdef _WIN32
  13296. static_cast<const char *>(compressed.c_str() + total_sent),
  13297. static_cast<int>(to_send),
  13298. #else
  13299. compressed.c_str() + total_sent, to_send,
  13300. #endif
  13301. 0);
  13302. if (sent <= 0) break;
  13303. total_sent += static_cast<size_t>(sent);
  13304. }
  13305. detail::close_socket(cli);
  13306. }
  13307. });
  13308. auto se = detail::scope_exit([&] {
  13309. detail::close_socket(srv);
  13310. server_thread.join();
  13311. });
  13312. size_t total_decompressed = 0;
  13313. {
  13314. Client cli("127.0.0.1", PORT + 3);
  13315. cli.set_read_timeout(5, 0);
  13316. cli.set_decompress(true);
  13317. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13318. auto stream = cli.open_stream("GET", "/zipbomb");
  13319. ASSERT_TRUE(stream.is_valid());
  13320. char buffer[64 * 1024];
  13321. ssize_t n;
  13322. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13323. total_decompressed += static_cast<size_t>(n);
  13324. }
  13325. }
  13326. // The decompressed size must be capped by payload_max_length. Without
  13327. // protection, the client would decompress the full 10MB from a tiny
  13328. // compressed payload, enabling a zip bomb DoS attack.
  13329. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13330. << "Client decompressed " << total_decompressed
  13331. << " bytes from a gzip response. The decompressed size should be "
  13332. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13333. }
  13334. #endif
  13335. TEST(HostAndPortPropertiesTest, NoSSL) {
  13336. httplib::Client cli("www.google.com", 1234);
  13337. ASSERT_EQ("www.google.com", cli.host());
  13338. ASSERT_EQ(1234, cli.port());
  13339. }
  13340. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13341. httplib::Client cli("www.google.com:1234");
  13342. ASSERT_EQ("www.google.com", cli.host());
  13343. ASSERT_EQ(1234, cli.port());
  13344. }
  13345. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13346. // Port number that overflows int — should not crash, client becomes invalid
  13347. httplib::Client cli("http://www.google.com:99999999999999999999");
  13348. ASSERT_FALSE(cli.is_valid());
  13349. }
  13350. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13351. // Port 99999 exceeds valid range (1-65535) — should not crash
  13352. httplib::Client cli("http://www.google.com:99999");
  13353. ASSERT_FALSE(cli.is_valid());
  13354. auto res = cli.Get("/");
  13355. EXPECT_FALSE(res);
  13356. EXPECT_EQ(Error::Connection, res.error());
  13357. }
  13358. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13359. httplib::Client cli("http://user:pass@localhost:1234");
  13360. ASSERT_FALSE(cli.is_valid());
  13361. EXPECT_FALSE(cli.Get("/"));
  13362. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13363. }
  13364. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13365. httplib::Client cli("http://www.google.com:80abc");
  13366. ASSERT_FALSE(cli.is_valid());
  13367. }
  13368. #ifdef CPPHTTPLIB_SSL_ENABLED
  13369. TEST(HostAndPortPropertiesTest, SSL) {
  13370. httplib::SSLClient cli("www.google.com");
  13371. ASSERT_EQ("www.google.com", cli.host());
  13372. ASSERT_EQ(443, cli.port());
  13373. }
  13374. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13375. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13376. std::string cert;
  13377. read_file(CA_CERT_FILE, cert);
  13378. httplib::SSLClient httplib_client("www.google.com");
  13379. // Load CA store first time
  13380. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13381. // Load CA store second time (update)
  13382. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13383. // Verify client is still valid and can make connections
  13384. httplib_client.enable_server_certificate_verification(true);
  13385. auto res = httplib_client.Get("/");
  13386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13387. // Google may return 200 or 301 depending on various factors
  13388. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13389. res->status == StatusCode::MovedPermanently_301);
  13390. }
  13391. TEST(SSLClientTest, ServerNameIndication_Online) {
  13392. auto host = "httpbingo.org";
  13393. auto path = std::string{"/get"};
  13394. SSLClient cli(host, 443);
  13395. auto res = cli.Get(path);
  13396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13397. ASSERT_EQ(StatusCode::OK_200, res->status);
  13398. }
  13399. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13400. // Use a site that will cause SSL verification failure due to self-signed cert
  13401. SSLClient cli("self-signed.badssl.com", 443);
  13402. cli.enable_server_certificate_verification(true);
  13403. auto res = cli.Get("/");
  13404. ASSERT_TRUE(!res);
  13405. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13406. // Verify backend error is captured for SSLServerVerification
  13407. // This occurs when certificate verification fails
  13408. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13409. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13410. EXPECT_NE(0UL, res.ssl_backend_error());
  13411. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13412. res.ssl_error());
  13413. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13414. #if !defined(_WIN32) || \
  13415. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13416. // On non-Windows or when Windows Schannel is disabled, the error comes
  13417. // from OpenSSL's verification
  13418. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13419. res.ssl_backend_error());
  13420. #endif
  13421. #endif
  13422. }
  13423. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13424. // Use a site where hostname doesn't match the certificate
  13425. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13426. SSLClient cli("wrong.host.badssl.com", 443);
  13427. cli.enable_server_certificate_verification(true);
  13428. cli.enable_server_hostname_verification(true);
  13429. auto res = cli.Get("/");
  13430. ASSERT_TRUE(!res);
  13431. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13432. // Verify backend error is captured for hostname verification failure
  13433. EXPECT_NE(0UL, res.ssl_backend_error());
  13434. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13435. res.ssl_error());
  13436. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13437. #if !defined(_WIN32) || \
  13438. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13439. // On non-Windows or when Windows Schannel is disabled, the error comes
  13440. // from OpenSSL's hostname verification
  13441. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13442. res.ssl_backend_error());
  13443. #endif
  13444. #endif
  13445. }
  13446. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13447. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13448. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13449. SSLClient cli("www.google.com", 443);
  13450. cli.enable_server_certificate_verification(true);
  13451. auto res = cli.Get("/");
  13452. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13453. }
  13454. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13455. SSLClient cli("www.google.com", 443);
  13456. cli.enable_server_certificate_verification(true);
  13457. cli.enable_windows_certificate_verification(false);
  13458. auto res = cli.Get("/");
  13459. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13460. }
  13461. // The server sends an intermediate cross-signed by a root Windows trusts,
  13462. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13463. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13464. SSLClient cli("accounts.spotify.com", 443);
  13465. auto res = cli.Get("/");
  13466. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13467. << " ssl_backend_error=" << res.ssl_backend_error();
  13468. }
  13469. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13470. // policy status, which no backend reports for a self-signed certificate.
  13471. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13472. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13473. ASSERT_TRUE(svr.is_valid());
  13474. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13475. auto se = detail::scope_exit([&] {
  13476. svr.stop();
  13477. t.join();
  13478. ASSERT_FALSE(svr.is_running());
  13479. });
  13480. svr.wait_until_ready();
  13481. SSLClient cli("127.0.0.1", PORT);
  13482. cli.set_connection_timeout(30);
  13483. auto res = cli.Get("/");
  13484. ASSERT_FALSE(res);
  13485. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13486. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13487. }
  13488. #endif
  13489. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13490. Client cli("https://google.com");
  13491. auto res = cli.Get("/");
  13492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13493. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13494. }
  13495. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13496. SSLClient cli("google.com");
  13497. cli.set_ca_cert_path(CA_CERT_FILE);
  13498. auto res = cli.Get("/");
  13499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13500. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13501. }
  13502. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13503. SSLClient cli("google.com");
  13504. cli.enable_server_certificate_verification(true);
  13505. cli.set_ca_cert_path("hello");
  13506. auto res = cli.Get("/");
  13507. ASSERT_TRUE(!res);
  13508. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13509. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13510. // should be set
  13511. EXPECT_EQ(0, res.ssl_error());
  13512. // Verify backend error is captured for SSLLoadingCerts
  13513. // This error occurs when loading CA certificates fails
  13514. EXPECT_NE(0UL, res.ssl_backend_error());
  13515. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13516. // OpenSSL specific error codes:
  13517. // > openssl errstr 0x80000002
  13518. // error:80000002:system library::No such file or directory
  13519. // > openssl errstr 0xA000126
  13520. // error:0A000126:SSL routines::unexpected eof while reading
  13521. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13522. res.ssl_backend_error() == 0xA000126);
  13523. #endif
  13524. }
  13525. TEST(SSLClientTest, ServerCertificateVerification4) {
  13526. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13527. ASSERT_TRUE(svr.is_valid());
  13528. svr.Get("/test", [&](const Request &, Response &res) {
  13529. res.set_content("test", "text/plain");
  13530. svr.stop();
  13531. ASSERT_TRUE(true);
  13532. });
  13533. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13534. auto se = detail::scope_exit([&] {
  13535. t.join();
  13536. ASSERT_FALSE(svr.is_running());
  13537. });
  13538. svr.wait_until_ready();
  13539. SSLClient cli("127.0.0.1", PORT);
  13540. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13541. cli.enable_server_certificate_verification(true);
  13542. cli.set_connection_timeout(30);
  13543. auto res = cli.Get("/test");
  13544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13545. ASSERT_EQ(StatusCode::OK_200, res->status);
  13546. }
  13547. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13548. std::string cert;
  13549. read_file(CA_CERT_FILE, cert);
  13550. SSLClient cli("google.com");
  13551. cli.load_ca_cert_store(cert.data(), cert.size());
  13552. const auto res = cli.Get("/");
  13553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13554. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13555. }
  13556. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13557. // clang-format off
  13558. static constexpr char cert[] =
  13559. "GlobalSign Root CA\n"
  13560. "==================\n"
  13561. "-----BEGIN CERTIFICATE-----\n"
  13562. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13563. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13564. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13565. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13566. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13567. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13568. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13569. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13570. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13571. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13572. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13573. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13574. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13575. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13576. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13577. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13578. "-----END CERTIFICATE-----\n";
  13579. // clang-format on
  13580. SSLClient cli("google.com");
  13581. cli.load_ca_cert_store(cert, sizeof(cert));
  13582. const auto res = cli.Get("/");
  13583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13584. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13585. }
  13586. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13587. SSLClient cli("www.youtube.com");
  13588. cli.set_ca_cert_path(CA_CERT_FILE);
  13589. cli.enable_server_certificate_verification(true);
  13590. cli.set_follow_location(true);
  13591. auto res = cli.Get("/");
  13592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13593. ASSERT_EQ(StatusCode::OK_200, res->status);
  13594. }
  13595. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13596. SSLClient cli("wWw.YouTube.Com");
  13597. cli.set_ca_cert_path(CA_CERT_FILE);
  13598. cli.enable_server_certificate_verification(true);
  13599. cli.enable_server_hostname_verification(true);
  13600. cli.set_follow_location(true);
  13601. auto res = cli.Get("/");
  13602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13603. ASSERT_EQ(StatusCode::OK_200, res->status);
  13604. }
  13605. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13606. SSLClient cli("gOoGlE.COm");
  13607. cli.enable_server_certificate_verification(true);
  13608. cli.enable_server_hostname_verification(true);
  13609. cli.set_follow_location(true);
  13610. auto res = cli.Get("/");
  13611. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13612. ASSERT_EQ(StatusCode::OK_200, res->status);
  13613. }
  13614. TEST(SSLClientTest, Issue2004_Online) {
  13615. Client client("https://google.com");
  13616. client.set_follow_location(true);
  13617. auto res = client.Get("/");
  13618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13619. ASSERT_EQ(StatusCode::OK_200, res->status);
  13620. auto body = res->body;
  13621. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13622. }
  13623. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13624. // Create SSLClient with invalid cert/key to make is_valid() return false
  13625. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13626. "nonexistent_key.pem");
  13627. // is_valid() should be false due to cert loading failure
  13628. ASSERT_FALSE(cli.is_valid());
  13629. auto res = cli.Get("/");
  13630. ASSERT_FALSE(res);
  13631. EXPECT_EQ(Error::SSLConnection, res.error());
  13632. }
  13633. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13634. // Test for Issue #2251: SSL error not properly reported when client cert
  13635. // and key paths are swapped or mismatched
  13636. // This simulates the scenario where user accidentally swaps the cert and key
  13637. // files
  13638. // Using client cert file as private key and vice versa (completely wrong)
  13639. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13640. // Should fail validation due to cert/key mismatch
  13641. ASSERT_FALSE(cli.is_valid());
  13642. // Attempt to make a request should fail with proper error
  13643. auto res = cli.Get("/");
  13644. ASSERT_FALSE(res);
  13645. EXPECT_EQ(Error::SSLConnection, res.error());
  13646. // SSL error should be recorded in the Result object (this is the key fix for
  13647. // Issue #2251)
  13648. auto backend_error = res.ssl_backend_error();
  13649. EXPECT_NE(0u, backend_error);
  13650. }
  13651. // Tests cert/key mismatch detection at the TLS context level
  13652. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13653. // Test that using mismatched cert/key causes connection failure.
  13654. // We verify this at the SSLClient level rather than through internal
  13655. // TLS API functions.
  13656. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13657. cli.enable_server_certificate_verification(false);
  13658. cli.set_connection_timeout(2);
  13659. // The mismatch should cause a connection or handshake error
  13660. auto res = cli.Get("/test");
  13661. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13662. // Either way, the request should fail
  13663. EXPECT_FALSE(res);
  13664. }
  13665. #endif
  13666. #if 0
  13667. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13668. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13669. ASSERT_TRUE(cli != nullptr);
  13670. cli->set_address_family(AF_INET6);
  13671. cli->set_interface("en0");
  13672. auto res = cli->Get("/get");
  13673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13674. ASSERT_EQ(StatusCode::OK_200, res->status);
  13675. }
  13676. #endif
  13677. // Client certificate tests - work with all TLS backends
  13678. #ifdef CPPHTTPLIB_SSL_ENABLED
  13679. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13680. void ClientCertPresent(
  13681. const std::string &client_cert_file,
  13682. const std::string &client_private_key_file,
  13683. const std::string &client_encrypted_private_key_pass = std::string(),
  13684. const ClientCertServerSetup &setup = nullptr) {
  13685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13686. ASSERT_TRUE(svr.is_valid());
  13687. if (setup) { setup(svr); }
  13688. svr.Get("/test", [&](const Request &req, Response &res) {
  13689. res.set_content("test", "text/plain");
  13690. auto cert = req.peer_cert();
  13691. ASSERT_TRUE(static_cast<bool>(cert));
  13692. std::string common_name = cert.subject_cn();
  13693. EXPECT_EQ("Common Name", common_name);
  13694. });
  13695. auto port = svr.bind_to_any_port(HOST);
  13696. ASSERT_LT(0, port);
  13697. thread t = thread([&]() { svr.listen_after_bind(); });
  13698. auto se = detail::scope_exit([&] {
  13699. svr.stop();
  13700. t.join();
  13701. ASSERT_FALSE(svr.is_running());
  13702. });
  13703. svr.wait_until_ready();
  13704. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13705. client_encrypted_private_key_pass);
  13706. cli.enable_server_certificate_verification(false);
  13707. cli.set_connection_timeout(30);
  13708. auto res = cli.Get("/test");
  13709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13710. ASSERT_EQ(StatusCode::OK_200, res->status);
  13711. }
  13712. TEST(SSLClientServerTest, ClientCertPresent) {
  13713. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13714. }
  13715. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13716. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13717. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13718. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13719. }
  13720. // Expects svr, which must require client certificates, to reject a client
  13721. // that has none
  13722. void RejectsClientWithoutCert(SSLServer &svr) {
  13723. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13724. auto port = svr.bind_to_any_port(HOST);
  13725. ASSERT_LT(0, port);
  13726. thread t = thread([&]() { svr.listen_after_bind(); });
  13727. auto se = detail::scope_exit([&] {
  13728. svr.stop();
  13729. t.join();
  13730. ASSERT_FALSE(svr.is_running());
  13731. });
  13732. svr.wait_until_ready();
  13733. SSLClient cli(HOST, port);
  13734. cli.set_connection_timeout(30);
  13735. // Skip the server certificate check, so that the request fails because the
  13736. // client certificate is missing rather than because cert.pem is not trusted
  13737. cli.enable_server_certificate_verification(false);
  13738. auto res = cli.Get("/test");
  13739. ASSERT_FALSE(res);
  13740. // The server rejects the client during the handshake, or on TLS 1.3 right
  13741. // after it, which the client notices on its first write or read
  13742. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13743. res.error() == Error::Write || res.error() == Error::Read)
  13744. << to_string(res.error());
  13745. if (res.error() == Error::SSLConnection) {
  13746. EXPECT_NE(0UL, res.ssl_backend_error());
  13747. }
  13748. // A rejection noticed on the write keeps the TLS error the write hit
  13749. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13750. }
  13751. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13752. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13753. ASSERT_TRUE(svr.is_valid());
  13754. if (setup) { setup(svr); }
  13755. RejectsClientWithoutCert(svr);
  13756. }
  13757. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13758. // A server that requires client certificates must keep requiring them after
  13759. // setup changes it, and keep accepting a client that has one
  13760. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13761. ClientCertMissing(setup);
  13762. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13763. setup);
  13764. }
  13765. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13766. ClientCertStillRequired([](SSLServer &svr) {
  13767. ASSERT_TRUE(tls::set_verify_callback(
  13768. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13769. });
  13770. }
  13771. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13772. ClientCertStillRequired([](SSLServer &svr) {
  13773. ASSERT_TRUE(tls::set_verify_callback(
  13774. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13775. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13776. });
  13777. }
  13778. // The client verifies the server certificate during the handshake, so a
  13779. // server that fails the check never gets the client certificate, even when a
  13780. // verifier of the client's own accepts it
  13781. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13782. struct Case {
  13783. const char *trusted_ca;
  13784. const char *host;
  13785. Error error;
  13786. };
  13787. // cert2.pem names localhost: the first client does not trust it, and the
  13788. // second trusts it but asks for another name
  13789. for (const auto &c :
  13790. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13791. Case{SERVER_CERT2_FILE, "example.com",
  13792. Error::SSLServerHostnameVerification}}) {
  13793. for (auto with_verifier : {false, true}) {
  13794. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13795. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13796. CLIENT_CA_CERT_FILE);
  13797. ASSERT_TRUE(svr.is_valid());
  13798. std::atomic<bool> got_client_cert{false};
  13799. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13800. [&](const tls::VerifyContext &) {
  13801. got_client_cert = true;
  13802. return true;
  13803. }));
  13804. auto port = svr.bind_to_any_port("127.0.0.1");
  13805. ASSERT_LT(0, port);
  13806. thread t = thread([&] { svr.listen_after_bind(); });
  13807. svr.wait_until_ready();
  13808. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13809. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13810. cli.set_ca_cert_path(c.trusted_ca);
  13811. if (with_verifier) {
  13812. cli.set_server_certificate_verifier(
  13813. [](const tls::VerifyContext &) { return true; });
  13814. }
  13815. auto res = cli.Get("/");
  13816. EXPECT_FALSE(res);
  13817. EXPECT_EQ(c.error, res.error());
  13818. svr.stop();
  13819. t.join();
  13820. EXPECT_FALSE(got_client_cert);
  13821. }
  13822. }
  13823. }
  13824. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13825. std::string cert_pem, key_pem, ca_pem;
  13826. read_file(SERVER_CERT_FILE, cert_pem);
  13827. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13828. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13829. ASSERT_TRUE(
  13830. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13831. }
  13832. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13833. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13834. ASSERT_TRUE(svr.is_valid());
  13835. UpdateCertsPemWithClientCA(svr);
  13836. RejectsClientWithoutCert(svr);
  13837. }
  13838. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13839. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13840. }
  13841. // A TLS error from one request must not show up in a later request's Result
  13842. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13843. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13844. ASSERT_TRUE(svr.is_valid());
  13845. svr.Get("/test", [](const Request &, Response &res) {
  13846. res.set_content("test", "text/plain");
  13847. });
  13848. auto port = svr.bind_to_any_port(HOST);
  13849. ASSERT_LT(0, port);
  13850. thread t = thread([&]() { svr.listen_after_bind(); });
  13851. auto se = detail::scope_exit([&] {
  13852. svr.stop();
  13853. t.join();
  13854. ASSERT_FALSE(svr.is_running());
  13855. });
  13856. svr.wait_until_ready();
  13857. SSLClient cli(HOST, port);
  13858. cli.set_connection_timeout(30);
  13859. cli.enable_server_hostname_verification(false);
  13860. // cert.pem is not trusted, so the handshake fails
  13861. ASSERT_FALSE(cli.Get("/test"));
  13862. cli.enable_server_certificate_verification(false);
  13863. auto res = cli.Get("/test");
  13864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13865. EXPECT_EQ(0, res.ssl_error());
  13866. EXPECT_EQ(0UL, res.ssl_backend_error());
  13867. }
  13868. // PEM memory-based constructor tests (works with all TLS backends).
  13869. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13870. // terminator after it.
  13871. void PemMemoryClientCertPresent(
  13872. const std::string &client_cert_file,
  13873. const std::string &client_private_key_file,
  13874. const std::string &client_encrypted_private_key_pass = std::string(),
  13875. bool exact_size = false) {
  13876. // Read PEM files into memory
  13877. std::string server_cert_pem, server_key_pem;
  13878. std::string client_ca_pem;
  13879. std::string client_cert_pem, client_key_pem;
  13880. read_file(SERVER_CERT_FILE, server_cert_pem);
  13881. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13882. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13883. read_file(client_cert_file, client_cert_pem);
  13884. read_file(client_private_key_file, client_key_pem);
  13885. std::list<std::vector<char>> exact_copies;
  13886. auto data = [&](const std::string &pem) -> const char * {
  13887. if (!exact_size) { return pem.c_str(); }
  13888. exact_copies.emplace_back(pem.begin(), pem.end());
  13889. return exact_copies.back().data();
  13890. };
  13891. // Create server with PEM memory
  13892. SSLServer::PemMemory server_pem = {
  13893. data(server_cert_pem),
  13894. server_cert_pem.size(),
  13895. data(server_key_pem),
  13896. server_key_pem.size(),
  13897. data(client_ca_pem),
  13898. client_ca_pem.size(),
  13899. nullptr // no password for server key
  13900. };
  13901. SSLServer svr(server_pem);
  13902. ASSERT_TRUE(svr.is_valid());
  13903. svr.Get("/test", [&](const Request &req, Response &res) {
  13904. res.set_content("test", "text/plain");
  13905. auto cert = req.peer_cert();
  13906. ASSERT_TRUE(static_cast<bool>(cert));
  13907. EXPECT_EQ("Common Name", cert.subject_cn());
  13908. });
  13909. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13910. auto se = detail::scope_exit([&] {
  13911. svr.stop();
  13912. t.join();
  13913. ASSERT_FALSE(svr.is_running());
  13914. });
  13915. svr.wait_until_ready();
  13916. // Create client with PEM memory
  13917. const char *password = client_encrypted_private_key_pass.empty()
  13918. ? nullptr
  13919. : client_encrypted_private_key_pass.c_str();
  13920. SSLClient::PemMemory client_pem = {
  13921. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13922. client_key_pem.size(), password};
  13923. SSLClient cli(HOST, PORT, client_pem);
  13924. cli.enable_server_certificate_verification(false);
  13925. cli.set_connection_timeout(30);
  13926. auto res = cli.Get("/test");
  13927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13928. ASSERT_EQ(StatusCode::OK_200, res->status);
  13929. }
  13930. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13931. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13932. }
  13933. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13934. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13935. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13936. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13937. }
  13938. // A server built from PEM memory with a client CA requires client certificates,
  13939. // also when the CA is a NUL-terminated string passed with a length of 0
  13940. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13941. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13942. read_file(SERVER_CERT_FILE, server_cert_pem);
  13943. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13944. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13945. SSLServer::PemMemory server_pem = {
  13946. server_cert_pem.c_str(),
  13947. server_cert_pem.size(),
  13948. server_key_pem.c_str(),
  13949. server_key_pem.size(),
  13950. client_ca_pem.c_str(),
  13951. client_ca_pem.size(),
  13952. nullptr // no password for server key
  13953. };
  13954. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13955. SCOPED_TRACE(client_ca_pem_len);
  13956. server_pem.client_ca_pem_len = client_ca_pem_len;
  13957. SSLServer svr(server_pem);
  13958. ASSERT_TRUE(svr.is_valid());
  13959. RejectsClientWithoutCert(svr);
  13960. }
  13961. // An empty CA fails to load instead of turning the check off
  13962. server_pem.client_ca_pem = "";
  13963. server_pem.client_ca_pem_len = 0;
  13964. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13965. }
  13966. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13967. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13968. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13969. true);
  13970. }
  13971. // A length shorter than the PEM cuts it short, so it no longer loads
  13972. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13973. std::string cert, key;
  13974. read_file(SERVER_CERT_FILE, cert);
  13975. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13976. for (auto cut_cert : {true, false}) {
  13977. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13978. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13979. SSLServer::PemMemory server_pem = {
  13980. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13981. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13982. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13983. key_len, nullptr};
  13984. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13985. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13986. key.c_str(), key_len, nullptr};
  13987. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13988. }
  13989. }
  13990. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13991. class NoListenSSLServer : public SSLServer {
  13992. public:
  13993. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13994. const char *client_ca_cert_file_path,
  13995. const char *client_ca_cert_dir_path = nullptr)
  13996. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13997. client_ca_cert_dir_path),
  13998. stop_(false) {}
  13999. std::atomic_bool stop_;
  14000. private:
  14001. bool process_and_close_socket(socket_t /*sock*/) override {
  14002. // Don't create SSL context
  14003. while (!stop_.load()) {
  14004. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14005. }
  14006. return true;
  14007. }
  14008. };
  14009. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14010. CLIENT_CA_CERT_FILE);
  14011. ASSERT_TRUE(svr.is_valid());
  14012. svr.Get("/test", [&](const Request &, Response &res) {
  14013. res.set_content("test", "text/plain");
  14014. });
  14015. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14016. auto se = detail::scope_exit([&] {
  14017. svr.stop_ = true;
  14018. svr.stop();
  14019. t.join();
  14020. ASSERT_FALSE(svr.is_running());
  14021. });
  14022. svr.wait_until_ready();
  14023. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14024. cli.enable_server_certificate_verification(false);
  14025. cli.set_connection_timeout(1);
  14026. auto res = cli.Get("/test");
  14027. ASSERT_TRUE(!res);
  14028. EXPECT_EQ(Error::SSLConnection, res.error());
  14029. // Timeout results in WantRead error code (maps to backend-specific value)
  14030. EXPECT_NE(0, res.ssl_error());
  14031. }
  14032. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14033. // Test SSLServer with client certificate verification using the standard
  14034. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14036. CLIENT_CA_CERT_DIR);
  14037. ASSERT_TRUE(svr.is_valid());
  14038. svr.Get("/test", [&](const Request &req, Response &res) {
  14039. res.set_content("test", "text/plain");
  14040. auto cert = req.peer_cert();
  14041. ASSERT_TRUE(static_cast<bool>(cert));
  14042. auto common_name = cert.subject_cn();
  14043. EXPECT_EQ("Common Name", common_name);
  14044. });
  14045. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14046. auto se = detail::scope_exit([&] {
  14047. svr.stop();
  14048. t.join();
  14049. ASSERT_FALSE(svr.is_running());
  14050. });
  14051. svr.wait_until_ready();
  14052. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14053. cli.enable_server_certificate_verification(false);
  14054. cli.set_connection_timeout(30);
  14055. auto res = cli.Get("/test");
  14056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14057. ASSERT_EQ(StatusCode::OK_200, res->status);
  14058. }
  14059. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14060. // Verifies that wildcard matching and exact matching work consistently
  14061. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14062. using namespace httplib::tls;
  14063. // We need a running server to test against
  14064. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14065. ASSERT_TRUE(svr.is_valid());
  14066. svr.Get("/test", [](const Request &, Response &res) {
  14067. res.set_content("ok", "text/plain");
  14068. });
  14069. thread t([&]() { svr.listen(HOST, PORT); });
  14070. auto se = detail::scope_exit([&] {
  14071. svr.stop();
  14072. t.join();
  14073. });
  14074. svr.wait_until_ready();
  14075. bool verify_callback_called = false;
  14076. bool verify_result_wrong = false;
  14077. SSLClient cli(HOST, PORT);
  14078. cli.enable_server_certificate_verification(true);
  14079. cli.set_ca_cert_path(CA_CERT_FILE);
  14080. cli.set_connection_timeout(5);
  14081. // Note: Test certificate has CN="Common Name", not "localhost"
  14082. bool verify_result_cn = false;
  14083. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14084. verify_callback_called = true;
  14085. if (!ctx.cert) return false;
  14086. // Test 1: "Common Name" should match (our test server cert CN)
  14087. verify_result_cn = ctx.check_hostname("Common Name");
  14088. // Test 2: wrong hostname should not match
  14089. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14090. return true; // Accept for the purpose of this test
  14091. });
  14092. auto res = cli.Get("/test");
  14093. // The request may succeed or fail depending on cert configuration
  14094. // but the callback should have been called
  14095. ASSERT_TRUE(verify_callback_called)
  14096. << "Verify callback should have been called";
  14097. // CN="Common Name" should match our test certificate
  14098. //
  14099. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14100. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14101. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14102. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14103. // <openssl/base.h>, which is included transitively when
  14104. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14105. #if defined(OPENSSL_IS_BORINGSSL)
  14106. EXPECT_FALSE(verify_result_cn)
  14107. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14108. #else
  14109. EXPECT_TRUE(verify_result_cn)
  14110. << "verify_hostname should match 'Common Name' (certificate CN)";
  14111. #endif
  14112. // Wrong hostname should not match
  14113. EXPECT_FALSE(verify_result_wrong)
  14114. << "verify_hostname should not match 'wronghost.example.com'";
  14115. }
  14116. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14117. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14118. // X509_check_ip behavior and must hold for every backend.
  14119. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14120. using namespace httplib::tls;
  14121. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14122. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14123. ASSERT_TRUE(svr.is_valid());
  14124. svr.Get("/test", [](const Request &, Response &res) {
  14125. res.set_content("ok", "text/plain");
  14126. });
  14127. thread t([&]() { svr.listen(HOST, PORT); });
  14128. auto se = detail::scope_exit([&] {
  14129. svr.stop();
  14130. t.join();
  14131. });
  14132. svr.wait_until_ready();
  14133. bool verify_callback_called = false;
  14134. bool ip_matched_via_cn = true;
  14135. SSLClient cli(HOST, PORT);
  14136. cli.enable_server_certificate_verification(true);
  14137. cli.set_ca_cert_path(CA_CERT_FILE);
  14138. cli.set_connection_timeout(5);
  14139. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14140. verify_callback_called = true;
  14141. if (!ctx.cert) return false;
  14142. // The IP appears only in the CN, so it must NOT be accepted.
  14143. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14144. return true; // Accept for the purpose of this test
  14145. });
  14146. cli.Get("/test");
  14147. ASSERT_TRUE(verify_callback_called)
  14148. << "Verify callback should have been called";
  14149. EXPECT_FALSE(ip_matched_via_cn)
  14150. << "An IP host must not be authenticated via the certificate CN";
  14151. }
  14152. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14153. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14154. using namespace httplib::tls;
  14155. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14156. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14157. ASSERT_TRUE(svr.is_valid());
  14158. svr.Get("/test", [](const Request &, Response &res) {
  14159. res.set_content("ok", "text/plain");
  14160. });
  14161. thread t([&]() { svr.listen(HOST, PORT); });
  14162. auto se = detail::scope_exit([&] {
  14163. svr.stop();
  14164. t.join();
  14165. });
  14166. svr.wait_until_ready();
  14167. bool verify_callback_called = false;
  14168. bool san_matched = false;
  14169. bool wrong_ipv6_matched = true;
  14170. bool cn_ipv6_matched = true;
  14171. SSLClient cli(HOST, PORT);
  14172. cli.enable_server_certificate_verification(true);
  14173. cli.set_ca_cert_path(CA_CERT_FILE);
  14174. cli.set_connection_timeout(5);
  14175. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14176. verify_callback_called = true;
  14177. if (!ctx.cert) return false;
  14178. // Matches the IPv6 iPAddress SAN.
  14179. san_matched = ctx.check_hostname("2001:db8::1");
  14180. // A different IPv6 address must not match.
  14181. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14182. // "::1" lives only in the CN, so it must not be accepted.
  14183. cn_ipv6_matched = ctx.check_hostname("::1");
  14184. return true; // Accept for the purpose of this test
  14185. });
  14186. cli.Get("/test");
  14187. ASSERT_TRUE(verify_callback_called)
  14188. << "Verify callback should have been called";
  14189. EXPECT_TRUE(san_matched)
  14190. << "verify_hostname should match an IPv6 iPAddress SAN";
  14191. EXPECT_FALSE(wrong_ipv6_matched)
  14192. << "verify_hostname should not match a non-matching IPv6 address";
  14193. EXPECT_FALSE(cn_ipv6_matched)
  14194. << "An IPv6 host must not be authenticated via the certificate CN";
  14195. }
  14196. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14197. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14198. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14199. using namespace httplib::tls;
  14200. // SANs: DNS:a.zz, IP:42.46.122.122
  14201. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14202. ASSERT_TRUE(svr.is_valid());
  14203. svr.Get("/test", [](const Request &, Response &res) {
  14204. res.set_content("ok", "text/plain");
  14205. });
  14206. auto port = svr.bind_to_any_port(HOST);
  14207. thread t([&]() { svr.listen_after_bind(); });
  14208. auto se = detail::scope_exit([&] {
  14209. svr.stop();
  14210. t.join();
  14211. });
  14212. svr.wait_until_ready();
  14213. bool verify_callback_called = false;
  14214. bool dns_san_matched = false;
  14215. bool ip_san_matched = false;
  14216. bool ip_matched_via_dns_san = true;
  14217. bool dns_matched_via_ip_san = true;
  14218. bool cn_matched_next_to_dns_san = true;
  14219. SSLClient cli(HOST, port);
  14220. cli.enable_server_certificate_verification(true);
  14221. cli.set_ca_cert_path(CA_CERT_FILE);
  14222. cli.set_connection_timeout(5);
  14223. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14224. verify_callback_called = true;
  14225. if (!ctx.cert) return false;
  14226. dns_san_matched = ctx.check_hostname("a.zz");
  14227. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14228. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14229. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14230. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14231. return true; // Accept for the purpose of this test
  14232. });
  14233. cli.Get("/test");
  14234. ASSERT_TRUE(verify_callback_called)
  14235. << "Verify callback should have been called";
  14236. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14237. EXPECT_TRUE(ip_san_matched)
  14238. << "verify_hostname should match an iPAddress SAN";
  14239. EXPECT_FALSE(ip_matched_via_dns_san)
  14240. << "An IP host must not be authenticated via a dNSName SAN";
  14241. EXPECT_FALSE(dns_matched_via_ip_san)
  14242. << "A DNS host must not be authenticated via an iPAddress SAN";
  14243. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14244. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14245. }
  14246. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14247. // "www.*.example.test" names one host and not every host under example.test.
  14248. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14249. using namespace httplib::tls;
  14250. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14251. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14252. ASSERT_TRUE(svr.is_valid());
  14253. svr.Get("/test", [](const Request &, Response &res) {
  14254. res.set_content("ok", "text/plain");
  14255. });
  14256. auto port = svr.bind_to_any_port(HOST);
  14257. thread t([&]() { svr.listen_after_bind(); });
  14258. auto se = detail::scope_exit([&] {
  14259. svr.stop();
  14260. t.join();
  14261. });
  14262. svr.wait_until_ready();
  14263. bool verify_callback_called = false;
  14264. bool leftmost_wildcard_matched = false;
  14265. bool wildcard_spanned_labels = true;
  14266. bool inner_wildcard_matched = true;
  14267. SSLClient cli(HOST, port);
  14268. cli.enable_server_certificate_verification(true);
  14269. cli.set_ca_cert_path(CA_CERT_FILE);
  14270. cli.set_connection_timeout(5);
  14271. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14272. verify_callback_called = true;
  14273. if (!ctx.cert) return false;
  14274. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14275. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14276. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14277. return true; // Accept for the purpose of this test
  14278. });
  14279. cli.Get("/test");
  14280. ASSERT_TRUE(verify_callback_called)
  14281. << "Verify callback should have been called";
  14282. EXPECT_TRUE(leftmost_wildcard_matched)
  14283. << "A leftmost wildcard should match a single label";
  14284. EXPECT_FALSE(wildcard_spanned_labels)
  14285. << "A wildcard label must not match more than one label";
  14286. EXPECT_FALSE(inner_wildcard_matched)
  14287. << "A wildcard outside the leftmost label must not be honoured";
  14288. }
  14289. // sans() must report each SAN entry under its own type.
  14290. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14291. using namespace httplib::tls;
  14292. // SANs: DNS:a.zz, IP:42.46.122.122
  14293. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14294. ASSERT_TRUE(svr.is_valid());
  14295. svr.Get("/test", [](const Request &, Response &res) {
  14296. res.set_content("ok", "text/plain");
  14297. });
  14298. auto port = svr.bind_to_any_port(HOST);
  14299. thread t([&]() { svr.listen_after_bind(); });
  14300. auto se = detail::scope_exit([&] {
  14301. svr.stop();
  14302. t.join();
  14303. });
  14304. svr.wait_until_ready();
  14305. bool verify_callback_called = false;
  14306. std::vector<SanEntry> sans;
  14307. SSLClient cli(HOST, port);
  14308. cli.enable_server_certificate_verification(true);
  14309. cli.set_ca_cert_path(CA_CERT_FILE);
  14310. cli.set_connection_timeout(5);
  14311. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14312. verify_callback_called = true;
  14313. if (!ctx.cert) return false;
  14314. sans = ctx.sans();
  14315. return true; // Accept for the purpose of this test
  14316. });
  14317. cli.Get("/test");
  14318. ASSERT_TRUE(verify_callback_called)
  14319. << "Verify callback should have been called";
  14320. auto has_san = [&](SanType type, const std::string &value) {
  14321. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14322. return san.type == type && san.value == value;
  14323. });
  14324. };
  14325. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14326. << "sans() should report the dNSName SAN";
  14327. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14328. << "sans() should report the iPAddress SAN";
  14329. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14330. << "sans() must not report the dNSName SAN as an address";
  14331. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14332. << "sans() must not report the iPAddress SAN as a DNS name";
  14333. }
  14334. #endif
  14335. // mbedTLS-specific callback constructor test
  14336. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14337. #ifdef CPPHTTPLIB_SSL_ENABLED
  14338. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14339. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14340. ASSERT_TRUE(svr.is_valid());
  14341. // Set up a handler to verify client certificate is present
  14342. bool client_cert_verified = false;
  14343. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14344. // Verify that client certificate was provided
  14345. client_cert_verified = true;
  14346. res.set_content("success", "text/plain");
  14347. });
  14348. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14349. auto se = detail::scope_exit([&] {
  14350. svr.stop();
  14351. t.join();
  14352. ASSERT_FALSE(svr.is_running());
  14353. });
  14354. svr.wait_until_ready();
  14355. // Client with certificate
  14356. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14357. cli.enable_server_certificate_verification(false);
  14358. cli.set_connection_timeout(30);
  14359. auto res = cli.Get("/test");
  14360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14361. ASSERT_EQ(StatusCode::OK_200, res->status);
  14362. ASSERT_TRUE(client_cert_verified);
  14363. EXPECT_EQ("success", res->body);
  14364. }
  14365. #endif
  14366. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14367. // backends
  14368. #ifdef CPPHTTPLIB_SSL_ENABLED
  14369. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14370. using namespace httplib::tls;
  14371. // Test that when client CA cert file is provided,
  14372. // the server properly requests and validates client certificates
  14373. // Create a server with client authentication
  14374. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14375. ASSERT_TRUE(svr.is_valid());
  14376. bool handler_called = false;
  14377. svr.Get("/test", [&](const Request &req, Response &res) {
  14378. handler_called = true;
  14379. // Verify that a client certificate was provided
  14380. auto cert = req.peer_cert();
  14381. ASSERT_TRUE(static_cast<bool>(cert));
  14382. // Get the issuer name
  14383. std::string issuer_str = cert.issuer_name();
  14384. ASSERT_FALSE(issuer_str.empty());
  14385. // The client certificate should be issued by our test CA
  14386. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14387. res.set_content("authenticated", "text/plain");
  14388. });
  14389. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14390. auto se = detail::scope_exit([&] {
  14391. svr.stop();
  14392. t.join();
  14393. ASSERT_FALSE(svr.is_running());
  14394. });
  14395. svr.wait_until_ready();
  14396. // Connect with a client certificate issued by the CA
  14397. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14398. cli.enable_server_certificate_verification(false);
  14399. cli.set_connection_timeout(30);
  14400. auto res = cli.Get("/test");
  14401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14402. ASSERT_EQ(StatusCode::OK_200, res->status);
  14403. ASSERT_TRUE(handler_called);
  14404. EXPECT_EQ("authenticated", res->body);
  14405. }
  14406. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14407. using namespace httplib::tls;
  14408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14409. ASSERT_TRUE(svr.is_valid());
  14410. svr.Get("/test", [](const Request &, Response &res) {
  14411. res.set_content("ok", "text/plain");
  14412. });
  14413. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14414. auto se = detail::scope_exit([&] {
  14415. svr.stop();
  14416. t.join();
  14417. });
  14418. svr.wait_until_ready();
  14419. SSLClient cli(HOST, PORT);
  14420. cli.enable_server_certificate_verification(false);
  14421. cli.set_connection_timeout(30);
  14422. bool cert_checked = false;
  14423. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14424. if (ctx.cert) {
  14425. auto sans = ctx.sans();
  14426. // Test certificate may or may not have SANs - just verify the API
  14427. // works If SANs exist, verify the types are valid
  14428. for (const auto &san : sans) {
  14429. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14430. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14431. san.type == SanType::OTHER);
  14432. EXPECT_FALSE(san.value.empty());
  14433. }
  14434. cert_checked = true;
  14435. }
  14436. return true;
  14437. });
  14438. auto res = cli.Get("/test");
  14439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14440. EXPECT_TRUE(cert_checked);
  14441. }
  14442. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14443. using namespace httplib::tls;
  14444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14445. ASSERT_TRUE(svr.is_valid());
  14446. svr.Get("/test", [](const Request &, Response &res) {
  14447. res.set_content("ok", "text/plain");
  14448. });
  14449. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14450. auto se = detail::scope_exit([&] {
  14451. svr.stop();
  14452. t.join();
  14453. });
  14454. svr.wait_until_ready();
  14455. SSLClient cli(HOST, PORT);
  14456. cli.enable_server_certificate_verification(false);
  14457. cli.set_connection_timeout(30);
  14458. bool validity_checked = false;
  14459. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14460. if (ctx.cert) {
  14461. time_t not_before = 0, not_after = 0;
  14462. bool result = ctx.validity(not_before, not_after);
  14463. EXPECT_TRUE(result);
  14464. // Verify that not_before < now < not_after for a valid cert
  14465. time_t now = time(nullptr);
  14466. EXPECT_LT(not_before, now);
  14467. EXPECT_GT(not_after, now);
  14468. validity_checked = true;
  14469. }
  14470. return true;
  14471. });
  14472. auto res = cli.Get("/test");
  14473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14474. EXPECT_TRUE(validity_checked);
  14475. }
  14476. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14477. using namespace httplib::tls;
  14478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14479. ASSERT_TRUE(svr.is_valid());
  14480. svr.Get("/test", [](const Request &, Response &res) {
  14481. res.set_content("ok", "text/plain");
  14482. });
  14483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14484. auto se = detail::scope_exit([&] {
  14485. svr.stop();
  14486. t.join();
  14487. });
  14488. svr.wait_until_ready();
  14489. SSLClient cli(HOST, PORT);
  14490. cli.enable_server_certificate_verification(false);
  14491. cli.set_connection_timeout(30);
  14492. bool serial_checked = false;
  14493. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14494. if (ctx.cert) {
  14495. std::string serial = ctx.serial();
  14496. EXPECT_FALSE(serial.empty());
  14497. // Serial should be a hex string
  14498. for (char c : serial) {
  14499. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14500. (c >= 'a' && c <= 'f'));
  14501. }
  14502. serial_checked = true;
  14503. }
  14504. return true;
  14505. });
  14506. auto res = cli.Get("/test");
  14507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14508. EXPECT_TRUE(serial_checked);
  14509. }
  14510. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14511. // Test 1: Valid CA file - no error should be recorded
  14512. {
  14513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14514. CLIENT_CA_CERT_FILE);
  14515. ASSERT_TRUE(svr.is_valid());
  14516. // With valid setup, last_ssl_error should be 0
  14517. EXPECT_EQ(0, svr.ssl_last_error());
  14518. }
  14519. // Test 2: Invalid CA file content
  14520. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14521. {
  14522. // Create a temporary file with completely invalid content
  14523. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14524. {
  14525. std::ofstream ofs(temp_invalid_ca);
  14526. ofs << "This is not a certificate file at all\n";
  14527. ofs << "Just plain text content\n";
  14528. }
  14529. // Create server with invalid CA file
  14530. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14531. // Clean up temporary file
  14532. std::remove(temp_invalid_ca);
  14533. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14534. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14535. // Note: SSL_CTX_load_verify_locations typically fails first,
  14536. // but our error handling code path is still exercised
  14537. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14538. }
  14539. }
  14540. TEST(VerifyCallbackTest, VerifyContextFields) {
  14541. using namespace httplib::tls;
  14542. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14543. ASSERT_TRUE(svr.is_valid());
  14544. svr.Get("/test", [](const Request &, Response &res) {
  14545. res.set_content("ok", "text/plain");
  14546. });
  14547. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14548. auto se = detail::scope_exit([&] {
  14549. svr.stop();
  14550. t.join();
  14551. });
  14552. svr.wait_until_ready();
  14553. SSLClient cli(HOST, PORT);
  14554. cli.enable_server_certificate_verification(false);
  14555. cli.set_connection_timeout(30);
  14556. int callback_count = 0;
  14557. bool saw_leaf_cert = false;
  14558. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14559. if (ctx.cert) {
  14560. callback_count++;
  14561. // We should see at least one certificate (the leaf)
  14562. std::string cn = ctx.subject_cn();
  14563. if (!cn.empty()) { saw_leaf_cert = true; }
  14564. // Verify context fields are populated
  14565. EXPECT_NE(ctx.session, nullptr);
  14566. EXPECT_GE(ctx.depth, 0);
  14567. }
  14568. return true;
  14569. });
  14570. auto res = cli.Get("/test");
  14571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14572. EXPECT_GT(callback_count, 0);
  14573. EXPECT_TRUE(saw_leaf_cert);
  14574. }
  14575. // A verifier that accepts runs alongside the built-in verification, and is the
  14576. // only check once that is turned off.
  14577. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14578. using namespace httplib::tls;
  14579. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14580. ASSERT_TRUE(svr.is_valid());
  14581. svr.Get("/test", [](const Request &, Response &res) {
  14582. res.set_content("ok", "text/plain");
  14583. });
  14584. auto port = svr.bind_to_any_port(HOST);
  14585. thread t([&]() { svr.listen_after_bind(); });
  14586. auto se = detail::scope_exit([&] {
  14587. svr.stop();
  14588. t.join();
  14589. });
  14590. svr.wait_until_ready();
  14591. SSLClient cli(HOST, port);
  14592. cli.enable_server_hostname_verification(false);
  14593. auto calls = 0;
  14594. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14595. calls++;
  14596. return true;
  14597. });
  14598. // cert.pem is not trusted
  14599. auto res = cli.Get("/test");
  14600. ASSERT_FALSE(res);
  14601. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14602. EXPECT_GT(calls, 0);
  14603. cli.enable_server_certificate_verification(false);
  14604. res = cli.Get("/test");
  14605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14606. EXPECT_EQ("ok", res->body);
  14607. }
  14608. // A verifier belongs to the client that set it, not to the thread that set it.
  14609. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14610. using namespace httplib::tls;
  14611. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14612. ASSERT_TRUE(svr.is_valid());
  14613. svr.Get("/test", [](const Request &, Response &res) {
  14614. res.set_content("ok", "text/plain");
  14615. });
  14616. auto port = svr.bind_to_any_port(HOST);
  14617. thread t([&]() { svr.listen_after_bind(); });
  14618. auto se = detail::scope_exit([&] {
  14619. svr.stop();
  14620. t.join();
  14621. });
  14622. svr.wait_until_ready();
  14623. auto rejecting_calls = 0;
  14624. SSLClient rejecting(HOST, port);
  14625. rejecting.enable_server_certificate_verification(false);
  14626. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14627. rejecting_calls++;
  14628. return false;
  14629. });
  14630. auto accepting_calls = 0;
  14631. SSLClient accepting(HOST, port);
  14632. accepting.enable_server_certificate_verification(false);
  14633. // Set on another thread than the requests below.
  14634. thread([&]() {
  14635. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14636. accepting_calls++;
  14637. return true;
  14638. });
  14639. }).join();
  14640. // Requested on another thread than the verifier was set on.
  14641. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14642. EXPECT_GT(rejecting_calls, 0);
  14643. auto res = accepting.Get("/test");
  14644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14645. EXPECT_GT(accepting_calls, 0);
  14646. }
  14647. // A verifier replaced while a handshake runs it lives until it returns.
  14648. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14649. using namespace httplib::tls;
  14650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14651. ASSERT_TRUE(svr.is_valid());
  14652. svr.Get("/test", [](const Request &, Response &res) {
  14653. res.set_content("ok", "text/plain");
  14654. });
  14655. auto port = svr.bind_to_any_port(HOST);
  14656. thread t([&]() { svr.listen_after_bind(); });
  14657. auto se = detail::scope_exit([&] {
  14658. svr.stop();
  14659. t.join();
  14660. });
  14661. svr.wait_until_ready();
  14662. SSLClient cli(HOST, port);
  14663. cli.enable_server_certificate_verification(false);
  14664. std::promise<void> entered;
  14665. std::promise<void> replaced;
  14666. auto replaced_future = replaced.get_future();
  14667. auto first_call = true;
  14668. // Long enough to live on the heap
  14669. std::string expected(64, 'v');
  14670. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14671. if (first_call) {
  14672. first_call = false;
  14673. entered.set_value();
  14674. replaced_future.wait();
  14675. }
  14676. return expected == std::string(64, 'v');
  14677. });
  14678. thread request([&]() {
  14679. auto res = cli.Get("/test");
  14680. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14681. });
  14682. entered.get_future().wait();
  14683. cli.set_server_certificate_verifier(
  14684. [](const VerifyContext &) { return true; });
  14685. replaced.set_value();
  14686. request.join();
  14687. }
  14688. // VerifyContext::session is the same handle the other tls:: functions take.
  14689. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14690. using namespace httplib::tls;
  14691. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14692. ASSERT_TRUE(svr.is_valid());
  14693. svr.Get("/test", [](const Request &, Response &res) {
  14694. res.set_content("ok", "text/plain");
  14695. });
  14696. auto port = svr.bind_to_any_port(HOST);
  14697. thread t([&]() { svr.listen_after_bind(); });
  14698. auto se = detail::scope_exit([&] {
  14699. svr.stop();
  14700. t.join();
  14701. });
  14702. svr.wait_until_ready();
  14703. SSLClient cli(HOST, port);
  14704. cli.enable_server_certificate_verification(false);
  14705. session_t verifier_session = nullptr;
  14706. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14707. verifier_session = ctx.session;
  14708. return true;
  14709. });
  14710. session_t session_verifier_session = nullptr;
  14711. cli.set_session_verifier([&](session_t session) {
  14712. session_verifier_session = session;
  14713. return SSLVerifierResponse::NoDecisionMade;
  14714. });
  14715. auto res = cli.Get("/test");
  14716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14717. EXPECT_NE(nullptr, verifier_session);
  14718. EXPECT_EQ(session_verifier_session, verifier_session);
  14719. }
  14720. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14721. using httplib::tls::TlsError;
  14722. // Test that verify_error_to_string returns empty for success
  14723. std::string success_str = TlsError::verify_error_to_string(0);
  14724. EXPECT_TRUE(success_str.empty());
  14725. // Test that verify_error_to_string returns non-empty for error codes
  14726. // Using a common error code (certificate expired)
  14727. std::string error_str =
  14728. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14729. EXPECT_FALSE(error_str.empty());
  14730. }
  14731. TEST(SessionVerifierTest, CertificateAccepted) {
  14732. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14733. ASSERT_TRUE(svr.is_valid());
  14734. svr.Get("/test", [](const Request &, Response &res) {
  14735. res.set_content("ok", "text/plain");
  14736. });
  14737. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14738. auto se = detail::scope_exit([&] {
  14739. svr.stop();
  14740. t.join();
  14741. });
  14742. svr.wait_until_ready();
  14743. SSLClient cli(HOST, PORT);
  14744. cli.enable_server_certificate_verification(false);
  14745. cli.set_connection_timeout(30);
  14746. bool callback_called = false;
  14747. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14748. EXPECT_NE(session, nullptr);
  14749. callback_called = true;
  14750. return SSLVerifierResponse::CertificateAccepted;
  14751. });
  14752. auto res = cli.Get("/test");
  14753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14754. EXPECT_EQ(200, res->status);
  14755. EXPECT_TRUE(callback_called);
  14756. }
  14757. TEST(SessionVerifierTest, CertificateRejected) {
  14758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14759. ASSERT_TRUE(svr.is_valid());
  14760. svr.Get("/test", [](const Request &, Response &res) {
  14761. res.set_content("ok", "text/plain");
  14762. });
  14763. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  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_certificate_verification(false);
  14771. cli.set_connection_timeout(30);
  14772. bool callback_called = false;
  14773. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14774. EXPECT_NE(session, nullptr);
  14775. callback_called = true;
  14776. return SSLVerifierResponse::CertificateRejected;
  14777. });
  14778. auto res = cli.Get("/test");
  14779. EXPECT_FALSE(res);
  14780. EXPECT_TRUE(callback_called);
  14781. }
  14782. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14784. ASSERT_TRUE(svr.is_valid());
  14785. svr.Get("/test", [](const Request &, Response &res) {
  14786. res.set_content("ok", "text/plain");
  14787. });
  14788. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14789. auto se = detail::scope_exit([&] {
  14790. svr.stop();
  14791. t.join();
  14792. });
  14793. svr.wait_until_ready();
  14794. // NoDecisionMade with verification disabled should succeed (no default check)
  14795. SSLClient cli(HOST, PORT);
  14796. cli.enable_server_certificate_verification(false);
  14797. cli.set_connection_timeout(30);
  14798. bool callback_called = false;
  14799. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14800. EXPECT_NE(session, nullptr);
  14801. callback_called = true;
  14802. return SSLVerifierResponse::NoDecisionMade;
  14803. });
  14804. auto res = cli.Get("/test");
  14805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14806. EXPECT_EQ(200, res->status);
  14807. EXPECT_TRUE(callback_called);
  14808. }
  14809. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14810. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14811. ASSERT_TRUE(svr.is_valid());
  14812. svr.Get("/test", [](const Request &, Response &res) {
  14813. res.set_content("ok", "text/plain");
  14814. });
  14815. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14816. auto se = detail::scope_exit([&] {
  14817. svr.stop();
  14818. t.join();
  14819. });
  14820. svr.wait_until_ready();
  14821. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14822. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14823. // so we only check that the request fails, not whether the callback was
  14824. // called.
  14825. SSLClient cli(HOST, PORT);
  14826. cli.enable_server_certificate_verification(true);
  14827. cli.set_connection_timeout(30);
  14828. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14829. EXPECT_NE(session, nullptr);
  14830. return SSLVerifierResponse::NoDecisionMade;
  14831. });
  14832. auto res = cli.Get("/test");
  14833. EXPECT_FALSE(res);
  14834. }
  14835. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14836. // Test SSL server using PemMemory constructor with client CA certificates
  14837. // Read PEM files
  14838. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14839. read_file(SERVER_CERT_FILE, server_cert_pem);
  14840. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14841. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14842. // Create SSLServer with PemMemory constructor including client CA
  14843. SSLServer::PemMemory server_pem = {
  14844. server_cert_pem.c_str(),
  14845. server_cert_pem.size(),
  14846. server_key_pem.c_str(),
  14847. server_key_pem.size(),
  14848. client_ca_pem.c_str(),
  14849. client_ca_pem.size(),
  14850. nullptr // no password for server key
  14851. };
  14852. SSLServer svr(server_pem);
  14853. ASSERT_TRUE(svr.is_valid());
  14854. // No SSL error should be recorded for valid setup
  14855. EXPECT_EQ(0, svr.ssl_last_error());
  14856. // Set up server endpoints
  14857. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14858. res.set_content("ok", "text/plain");
  14859. });
  14860. // Start server in a thread
  14861. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14862. svr.wait_until_ready();
  14863. // Connect with client certificate (using constructor with paths)
  14864. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14865. cli.enable_server_certificate_verification(false);
  14866. auto res = cli.Get("/test-pem-ca");
  14867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14868. EXPECT_EQ(200, res->status);
  14869. EXPECT_EQ("ok", res->body);
  14870. svr.stop();
  14871. server_thread.join();
  14872. }
  14873. #endif
  14874. #ifdef _WIN32
  14875. TEST(CleanupTest, WSACleanup) {
  14876. int ret = WSACleanup();
  14877. ASSERT_EQ(0, ret);
  14878. }
  14879. #endif
  14880. #ifndef CPPHTTPLIB_SSL_ENABLED
  14881. TEST(NoSSLSupport, SimpleInterface) {
  14882. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14883. }
  14884. #endif
  14885. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14886. TEST(InvalidScheme, SimpleInterface) {
  14887. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14888. }
  14889. #endif
  14890. TEST(NoScheme, SimpleInterface) {
  14891. Client cli("yahoo.com:80");
  14892. ASSERT_TRUE(cli.is_valid());
  14893. }
  14894. TEST(SendAPI, SimpleInterface_Online) {
  14895. Client cli("http://yahoo.com");
  14896. Request req;
  14897. req.method = "GET";
  14898. req.path = "/";
  14899. auto res = cli.send(req);
  14900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14901. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14902. }
  14903. TEST(SendAPI, WithParamsInRequest) {
  14904. Server svr;
  14905. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14906. EXPECT_TRUE(req.has_param("test"));
  14907. EXPECT_EQ("test_value", req.get_param_value("test"));
  14908. });
  14909. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14910. auto se = detail::scope_exit([&] {
  14911. svr.stop();
  14912. t.join();
  14913. ASSERT_FALSE(svr.is_running());
  14914. });
  14915. svr.wait_until_ready();
  14916. Client cli(HOST, PORT);
  14917. {
  14918. Request req;
  14919. req.method = "GET";
  14920. req.path = "/";
  14921. req.params.emplace("test", "test_value");
  14922. auto res = cli.send(req);
  14923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14924. }
  14925. {
  14926. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14928. }
  14929. }
  14930. TEST(ClientImplMethods, GetSocketTest) {
  14931. httplib::Server svr;
  14932. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14933. res.status = StatusCode::OK_200;
  14934. });
  14935. auto port = svr.bind_to_any_port("127.0.0.1");
  14936. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14937. auto se = detail::scope_exit([&] {
  14938. svr.stop();
  14939. thread.join();
  14940. ASSERT_FALSE(svr.is_running());
  14941. });
  14942. svr.wait_until_ready();
  14943. {
  14944. httplib::Client cli("127.0.0.1", port);
  14945. cli.set_keep_alive(true);
  14946. // Use the behavior of cpp-httplib of opening the connection
  14947. // only when the first request happens. If that changes,
  14948. // this test would be obsolete.
  14949. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14950. // This also implicitly tests the server. But other tests would fail much
  14951. // earlier than this one to be considered.
  14952. auto res = cli.Get("/");
  14953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14954. EXPECT_EQ(StatusCode::OK_200, res->status);
  14955. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14956. }
  14957. }
  14958. #ifdef CPPHTTPLIB_SSL_ENABLED
  14959. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14960. Client cli("http://yahoo.com");
  14961. auto res = cli.Get("/");
  14962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14963. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14964. cli.set_follow_location(true);
  14965. res = cli.Get("/");
  14966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14967. EXPECT_EQ(StatusCode::OK_200, res->status);
  14968. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14969. }
  14970. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14971. Client cli("https://yahoo.com");
  14972. auto res = cli.Get("/");
  14973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14974. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14975. cli.set_follow_location(true);
  14976. res = cli.Get("/");
  14977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14978. EXPECT_EQ(StatusCode::OK_200, res->status);
  14979. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14980. }
  14981. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14982. Client cli("https://yahoo.com");
  14983. auto res = cli.Get("/");
  14984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14985. ASSERT_FALSE(!res);
  14986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14987. ASSERT_FALSE(res == nullptr);
  14988. ASSERT_TRUE(res != nullptr);
  14989. EXPECT_EQ(Error::Success, res.error());
  14990. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14991. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14992. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14993. cli.set_follow_location(true);
  14994. res = cli.Get("/");
  14995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14996. EXPECT_EQ(Error::Success, res.error());
  14997. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14998. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14999. EXPECT_EQ(StatusCode::OK_200, res->status);
  15000. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15001. }
  15002. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15003. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15004. Client cli("https://cdnjs.cloudflare.com");
  15005. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15006. Headers{{"Accept-Encoding", "br"}});
  15007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15008. EXPECT_EQ(StatusCode::OK_200, res->status);
  15009. EXPECT_EQ(287630U, res->body.size());
  15010. EXPECT_EQ("application/javascript; charset=utf-8",
  15011. res->get_header_value("Content-Type"));
  15012. }
  15013. #endif
  15014. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15015. #undef REDIR_HOST // Silence compiler warning
  15016. #define REDIR_HOST "https://httpbingo.org"
  15017. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15018. Client cli(REDIR_HOST);
  15019. cli.set_follow_location(true);
  15020. auto res =
  15021. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15023. EXPECT_EQ(StatusCode::OK_200, res->status);
  15024. }
  15025. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15026. Client cli(REDIR_HOST);
  15027. cli.set_follow_location(true);
  15028. Params params;
  15029. params.emplace("url", "http://example.com");
  15030. params.emplace("status_code", "302");
  15031. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15033. EXPECT_EQ(StatusCode::OK_200, res->status);
  15034. }
  15035. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15036. Client cli(REDIR_HOST);
  15037. cli.set_follow_location(true);
  15038. Params params;
  15039. params.emplace("url", "http://example.com");
  15040. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15042. EXPECT_EQ(StatusCode::OK_200, res->status);
  15043. }
  15044. TEST(HttpToHttpsRedirectTest, CertFile) {
  15045. auto ssl_port = PORT + 1;
  15046. Server svr;
  15047. ASSERT_TRUE(svr.is_valid());
  15048. svr.Get("/index", [&](const Request &, Response &res) {
  15049. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15050. "/index");
  15051. svr.stop();
  15052. });
  15053. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15054. ASSERT_TRUE(ssl_svr.is_valid());
  15055. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15056. res.set_content("test", "text/plain");
  15057. ssl_svr.stop();
  15058. });
  15059. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15060. thread t2 =
  15061. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15062. auto se = detail::scope_exit([&] {
  15063. t2.join();
  15064. t.join();
  15065. ASSERT_FALSE(svr.is_running());
  15066. });
  15067. svr.wait_until_ready();
  15068. ssl_svr.wait_until_ready();
  15069. Client cli("127.0.0.1", PORT);
  15070. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15071. cli.enable_server_certificate_verification(true);
  15072. cli.set_follow_location(true);
  15073. cli.set_connection_timeout(30);
  15074. auto res = cli.Get("/index");
  15075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15076. ASSERT_EQ(StatusCode::OK_200, res->status);
  15077. }
  15078. TEST(SSLClientRedirectTest, CertFile) {
  15079. auto ssl_port = PORT + 1;
  15080. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15081. ASSERT_TRUE(ssl_svr1.is_valid());
  15082. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15083. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15084. "/index");
  15085. ssl_svr1.stop();
  15086. });
  15087. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15088. ASSERT_TRUE(ssl_svr2.is_valid());
  15089. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15090. res.set_content("test", "text/plain");
  15091. ssl_svr2.stop();
  15092. });
  15093. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15094. thread t2 =
  15095. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15096. auto se = detail::scope_exit([&] {
  15097. t2.join();
  15098. t.join();
  15099. ASSERT_FALSE(ssl_svr1.is_running());
  15100. });
  15101. ssl_svr1.wait_until_ready();
  15102. ssl_svr2.wait_until_ready();
  15103. SSLClient cli("127.0.0.1", PORT);
  15104. std::string cert;
  15105. read_file(SERVER_CERT2_FILE, cert);
  15106. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15107. cli.enable_server_certificate_verification(true);
  15108. cli.set_follow_location(true);
  15109. cli.set_connection_timeout(30);
  15110. auto res = cli.Get("/index");
  15111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15112. ASSERT_EQ(StatusCode::OK_200, res->status);
  15113. }
  15114. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15115. // another port, so the client follows it with a new client.
  15116. static Result GetThroughTlsRedirectToDifferentPort(
  15117. const std::function<void(SSLClient &)> &setup,
  15118. const char *target_cert = SERVER_CERT2_FILE,
  15119. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15120. auto ssl_port = PORT + 1;
  15121. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15122. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15123. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15124. "/index");
  15125. });
  15126. SSLServer ssl_svr2(target_cert, target_key);
  15127. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15128. res.set_content("test", "text/plain");
  15129. });
  15130. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15131. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15132. auto se = detail::scope_exit([&] {
  15133. ssl_svr2.stop();
  15134. ssl_svr1.stop();
  15135. t2.join();
  15136. t.join();
  15137. });
  15138. ssl_svr1.wait_until_ready();
  15139. ssl_svr2.wait_until_ready();
  15140. SSLClient cli("127.0.0.1", PORT);
  15141. cli.set_follow_location(true);
  15142. cli.set_connection_timeout(30);
  15143. setup(cli);
  15144. return cli.Get("/index");
  15145. }
  15146. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15147. auto calls = 0;
  15148. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15149. cli.enable_server_certificate_verification(false);
  15150. // Accept the first server only.
  15151. cli.set_session_verifier([&](tls::session_t) {
  15152. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15153. : SSLVerifierResponse::CertificateRejected;
  15154. });
  15155. });
  15156. ASSERT_FALSE(res);
  15157. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15158. EXPECT_EQ(2, calls);
  15159. }
  15160. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15161. std::string pinned;
  15162. auto res = GetThroughTlsRedirectToDifferentPort(
  15163. [&](SSLClient &cli) {
  15164. cli.enable_server_certificate_verification(false);
  15165. // Pin the first certificate seen.
  15166. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15167. if (pinned.empty()) { pinned = ctx.serial(); }
  15168. return ctx.serial() == pinned;
  15169. });
  15170. },
  15171. // A certificate other than the first server's.
  15172. SERVER_CERT_FILE);
  15173. EXPECT_FALSE(res);
  15174. EXPECT_FALSE(pinned.empty());
  15175. }
  15176. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15177. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15178. std::string cert;
  15179. read_file(SERVER_CERT2_FILE, cert);
  15180. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15181. });
  15182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15183. EXPECT_EQ(StatusCode::OK_200, res->status);
  15184. }
  15185. // The target's certificate is signed by the root CA, which the first server's
  15186. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15187. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15188. auto res = GetThroughTlsRedirectToDifferentPort(
  15189. [](SSLClient &cli) {
  15190. std::string root_ca, cert;
  15191. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15192. read_file(SERVER_CERT2_FILE, cert);
  15193. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15194. cli.load_ca_cert_store(cert.data(), cert.size());
  15195. cli.enable_server_hostname_verification(false);
  15196. },
  15197. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15199. EXPECT_EQ(StatusCode::OK_200, res->status);
  15200. }
  15201. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15202. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15203. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15204. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15205. auto res = GetThroughTlsRedirectToDifferentPort(
  15206. [](SSLClient &cli) {
  15207. std::string root_ca, cert;
  15208. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15209. read_file(SERVER_CERT2_FILE, cert);
  15210. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15211. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15212. cli.enable_server_hostname_verification(false);
  15213. },
  15214. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15215. ASSERT_FALSE(res);
  15216. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15217. }
  15218. #endif
  15219. #endif
  15220. #ifdef CPPHTTPLIB_SSL_ENABLED
  15221. // Test that set_ca_cert_store() skips system certs (consistent with
  15222. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15223. // should be trusted - system certs should NOT be loaded.
  15224. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15225. // Load a specific cert that is NOT a system CA cert
  15226. std::string cert;
  15227. read_file(SERVER_CERT2_FILE, cert);
  15228. SSLClient cli("google.com");
  15229. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15230. cli.enable_server_certificate_verification(true);
  15231. // This should FAIL because:
  15232. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15233. // 2. System certs should NOT be loaded when custom store is set
  15234. // If system certs WERE loaded, this would succeed
  15235. auto res = cli.Get("/");
  15236. ASSERT_FALSE(res);
  15237. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15238. }
  15239. // Same as above, but through the native store handle path. Regression test:
  15240. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15241. // merged system certs into the user-provided store.
  15242. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15243. std::string cert;
  15244. read_file(SERVER_CERT2_FILE, cert);
  15245. SSLClient cli("google.com");
  15246. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15247. cli.enable_server_certificate_verification(true);
  15248. auto res = cli.Get("/");
  15249. ASSERT_FALSE(res);
  15250. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15251. }
  15252. // A custom store set via the native handle must still verify a server whose
  15253. // cert it does contain.
  15254. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15255. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15256. ASSERT_TRUE(svr.is_valid());
  15257. svr.Get("/test", [&](const Request &, Response &res) {
  15258. res.set_content("test", "text/plain");
  15259. });
  15260. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15261. auto se = detail::scope_exit([&] {
  15262. svr.stop();
  15263. t.join();
  15264. ASSERT_FALSE(svr.is_running());
  15265. });
  15266. svr.wait_until_ready();
  15267. SSLClient cli("127.0.0.1", PORT);
  15268. std::string cert;
  15269. read_file(SERVER_CERT2_FILE, cert);
  15270. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15271. cli.enable_server_certificate_verification(true);
  15272. cli.set_connection_timeout(30);
  15273. auto res = cli.Get("/test");
  15274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15275. ASSERT_EQ(StatusCode::OK_200, res->status);
  15276. }
  15277. // CA certs loaded through the universal Client must be transferred to the
  15278. // client created internally for following an HTTPS redirect. Regression test:
  15279. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15280. // the CA data for redirect transfer.
  15281. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15282. auto ssl_port = PORT + 1;
  15283. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15284. ASSERT_TRUE(ssl_svr1.is_valid());
  15285. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15286. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15287. "/index");
  15288. });
  15289. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15290. ASSERT_TRUE(ssl_svr2.is_valid());
  15291. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15292. res.set_content("test", "text/plain");
  15293. });
  15294. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15295. thread t2 =
  15296. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15297. auto se = detail::scope_exit([&] {
  15298. ssl_svr2.stop();
  15299. ssl_svr1.stop();
  15300. t2.join();
  15301. t.join();
  15302. ASSERT_FALSE(ssl_svr1.is_running());
  15303. });
  15304. ssl_svr1.wait_until_ready();
  15305. ssl_svr2.wait_until_ready();
  15306. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15307. std::string cert;
  15308. read_file(SERVER_CERT2_FILE, cert);
  15309. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15310. cli.enable_server_certificate_verification(true);
  15311. cli.set_follow_location(true);
  15312. cli.set_connection_timeout(30);
  15313. auto res = cli.Get("/index");
  15314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15315. ASSERT_EQ(StatusCode::OK_200, res->status);
  15316. }
  15317. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15318. // so a host signed by a system CA verifies even though a custom CA is set
  15319. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15320. std::string cert;
  15321. read_file(SERVER_CERT2_FILE, cert);
  15322. SSLClient cli("google.com");
  15323. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15324. cli.enable_system_ca(true);
  15325. cli.enable_server_certificate_verification(true);
  15326. auto res = cli.Get("/");
  15327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15328. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15329. }
  15330. // The custom CA remains effective when combined with the system CA
  15331. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15332. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15333. ASSERT_TRUE(svr.is_valid());
  15334. svr.Get("/test", [&](const Request &, Response &res) {
  15335. res.set_content("test", "text/plain");
  15336. });
  15337. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15338. auto se = detail::scope_exit([&] {
  15339. svr.stop();
  15340. t.join();
  15341. ASSERT_FALSE(svr.is_running());
  15342. });
  15343. svr.wait_until_ready();
  15344. SSLClient cli("127.0.0.1", PORT);
  15345. std::string cert;
  15346. read_file(SERVER_CERT2_FILE, cert);
  15347. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15348. cli.enable_system_ca(true);
  15349. cli.enable_server_certificate_verification(true);
  15350. cli.set_connection_timeout(30);
  15351. auto res = cli.Get("/test");
  15352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15353. ASSERT_EQ(StatusCode::OK_200, res->status);
  15354. }
  15355. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15356. // skip chain verification entirely (only the certificate identity was
  15357. // checked), so a server presenting an untrusted certificate with a matching
  15358. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15359. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15360. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15361. ASSERT_TRUE(svr.is_valid());
  15362. svr.Get("/test", [&](const Request &, Response &res) {
  15363. res.set_content("test", "text/plain");
  15364. });
  15365. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15366. auto se = detail::scope_exit([&] {
  15367. svr.stop();
  15368. t.join();
  15369. ASSERT_FALSE(svr.is_running());
  15370. });
  15371. svr.wait_until_ready();
  15372. SSLClient cli("127.0.0.1", PORT);
  15373. std::string cert;
  15374. // A trusted CA that did not sign the server certificate. The server cert
  15375. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15376. // this connection.
  15377. read_file(CLIENT_CA_CERT_FILE, cert);
  15378. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15379. cli.enable_server_certificate_verification(true);
  15380. cli.set_connection_timeout(30);
  15381. auto res = cli.Get("/test");
  15382. ASSERT_FALSE(res);
  15383. }
  15384. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15385. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15386. // CA that failed to come through fails verification instead of trusting them.
  15387. // (wolfSSL does not list the system CAs it loaded.)
  15388. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15389. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15390. ASSERT_TRUE(svr.is_valid());
  15391. auto port = svr.bind_to_any_port("127.0.0.1");
  15392. ASSERT_LT(0, port);
  15393. thread t = thread([&] { svr.listen_after_bind(); });
  15394. auto se = detail::scope_exit([&] {
  15395. svr.stop();
  15396. t.join();
  15397. ASSERT_FALSE(svr.is_running());
  15398. });
  15399. svr.wait_until_ready();
  15400. // The CAs a client trusts once its first request has loaded them
  15401. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15402. Client cli("https://127.0.0.1:" + std::to_string(port));
  15403. setup(cli);
  15404. cli.Get("/");
  15405. return tls::get_ca_names(cli.tls_context()).size();
  15406. };
  15407. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15408. EXPECT_EQ(0u,
  15409. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15410. }
  15411. #endif
  15412. // A TLS setting changed between requests applies to the next one, not just to
  15413. // the next connection
  15414. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15415. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15416. ASSERT_TRUE(svr.is_valid());
  15417. svr.Get("/", [](const Request &req, Response &res) {
  15418. res.set_content(std::to_string(req.remote_port), "text/plain");
  15419. });
  15420. auto port = svr.bind_to_any_port("127.0.0.1");
  15421. ASSERT_LT(0, port);
  15422. thread t = thread([&] { svr.listen_after_bind(); });
  15423. auto se = detail::scope_exit([&] {
  15424. svr.stop();
  15425. t.join();
  15426. ASSERT_FALSE(svr.is_running());
  15427. });
  15428. svr.wait_until_ready();
  15429. SSLClient cli("127.0.0.1", port);
  15430. cli.set_keep_alive(true);
  15431. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15432. cli.enable_server_certificate_verification(false);
  15433. // The port the request went out from, so a new one means a new connection
  15434. auto client_port = [&] {
  15435. auto res = cli.Get("/");
  15436. return res ? res->body : std::string();
  15437. };
  15438. auto last = client_port();
  15439. ASSERT_FALSE(last.empty());
  15440. // Setting a value it already has keeps the connection
  15441. cli.enable_server_certificate_verification(false);
  15442. cli.enable_server_hostname_verification(true);
  15443. EXPECT_EQ(last, client_port());
  15444. cli.enable_server_certificate_verification(true);
  15445. auto res = cli.Get("/");
  15446. EXPECT_FALSE(res);
  15447. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15448. std::string ca;
  15449. read_file(SERVER_CERT2_FILE, ca);
  15450. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15451. last = client_port();
  15452. ASSERT_FALSE(last.empty());
  15453. std::vector<std::function<void()>> setters = {
  15454. [&] { cli.enable_server_hostname_verification(false); },
  15455. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15456. [&] {
  15457. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15458. },
  15459. [&] {
  15460. cli.set_server_certificate_verifier(
  15461. [](const tls::VerifyContext &) { return true; });
  15462. },
  15463. [&] {
  15464. cli.set_session_verifier(
  15465. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15466. },
  15467. };
  15468. for (const auto &setter : setters) {
  15469. setter();
  15470. auto next = client_port();
  15471. ASSERT_FALSE(next.empty());
  15472. EXPECT_NE(last, next);
  15473. last = next;
  15474. }
  15475. cli.set_session_verifier(
  15476. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15477. auto handle = cli.open_stream("GET", "/");
  15478. EXPECT_FALSE(handle.is_valid());
  15479. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15480. }
  15481. // A PEM given to create_ca_store() needs no NUL after it
  15482. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15483. std::string pem;
  15484. read_file(SERVER_CERT2_FILE, pem);
  15485. auto buf = pem + "X";
  15486. auto store = tls::create_ca_store(buf.data(), pem.size());
  15487. EXPECT_TRUE(store != nullptr);
  15488. SSLClient cli("localhost");
  15489. cli.set_ca_cert_store(store);
  15490. }
  15491. // enable_system_ca(false) prevents system CA loading entirely
  15492. TEST(SSLClientTest, DisableSystemCa_Online) {
  15493. SSLClient cli("google.com");
  15494. cli.enable_system_ca(false);
  15495. cli.enable_server_certificate_verification(true);
  15496. auto res = cli.Get("/");
  15497. ASSERT_FALSE(res);
  15498. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15499. // itself when the CA chain is empty
  15500. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15501. res.error() == Error::SSLConnection);
  15502. }
  15503. // The universal Client forwards enable_system_ca()
  15504. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15505. std::string cert;
  15506. read_file(SERVER_CERT2_FILE, cert);
  15507. Client cli("https://google.com");
  15508. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15509. cli.enable_system_ca(true);
  15510. cli.enable_server_certificate_verification(true);
  15511. auto res = cli.Get("/");
  15512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15513. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15514. }
  15515. // The system CA policy must carry over to the client created internally for
  15516. // following a cross-host HTTPS redirect
  15517. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15518. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15519. ASSERT_TRUE(svr.is_valid());
  15520. svr.Get("/index", [&](const Request &, Response &res) {
  15521. res.set_redirect("https://www.google.com/");
  15522. });
  15523. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15524. auto se = detail::scope_exit([&] {
  15525. svr.stop();
  15526. t.join();
  15527. ASSERT_FALSE(svr.is_running());
  15528. });
  15529. svr.wait_until_ready();
  15530. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15531. std::string cert;
  15532. read_file(SERVER_CERT2_FILE, cert);
  15533. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15534. cli.enable_system_ca(true);
  15535. cli.enable_server_certificate_verification(true);
  15536. cli.set_follow_location(true);
  15537. cli.set_connection_timeout(30);
  15538. // Receiving any response proves the redirect client completed the TLS
  15539. // handshake with a system-CA-signed host
  15540. auto res = cli.Get("/index");
  15541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15542. }
  15543. TEST(MultipartFormDataTest, LargeData) {
  15544. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15545. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15546. const ContentReader &content_reader) {
  15547. if (req.is_multipart_form_data()) {
  15548. std::vector<FormData> items;
  15549. content_reader(
  15550. [&](const FormData &file) {
  15551. items.push_back(file);
  15552. return true;
  15553. },
  15554. [&](const char *data, size_t data_length) {
  15555. items.back().content.append(data, data_length);
  15556. return true;
  15557. });
  15558. EXPECT_TRUE(std::string(items[0].name) == "document");
  15559. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15560. EXPECT_TRUE(items[0].filename == "2MB_data");
  15561. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15562. EXPECT_TRUE(items[1].name == "hello");
  15563. EXPECT_TRUE(items[1].content == "world");
  15564. EXPECT_TRUE(items[1].filename == "");
  15565. EXPECT_TRUE(items[1].content_type == "");
  15566. } else {
  15567. std::string body;
  15568. content_reader([&](const char *data, size_t data_length) {
  15569. body.append(data, data_length);
  15570. return true;
  15571. });
  15572. }
  15573. });
  15574. auto port = svr.bind_to_any_port(HOST);
  15575. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15576. auto se = detail::scope_exit([&] {
  15577. svr.stop();
  15578. t.join();
  15579. ASSERT_FALSE(svr.is_running());
  15580. });
  15581. svr.wait_until_ready();
  15582. {
  15583. std::string data(1024 * 1024 * 2, '.');
  15584. std::stringstream buffer;
  15585. buffer << data;
  15586. SSLClient cli(HOST, port);
  15587. cli.enable_server_certificate_verification(false);
  15588. UploadFormDataItems items{
  15589. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15590. {"hello", "world", "", ""},
  15591. };
  15592. auto res = cli.Post("/post", items);
  15593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15594. ASSERT_EQ(StatusCode::OK_200, res->status);
  15595. }
  15596. }
  15597. TEST(MultipartFormDataTest, DataProviderItems) {
  15598. std::random_device seed_gen;
  15599. std::mt19937 random(seed_gen());
  15600. std::string rand1;
  15601. rand1.resize(1000);
  15602. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15603. std::string rand2;
  15604. rand2.resize(3000);
  15605. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15606. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15607. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15608. const ContentReader &content_reader) {
  15609. ASSERT_FALSE(req.is_multipart_form_data());
  15610. std::string body;
  15611. content_reader([&](const char *data, size_t data_length) {
  15612. body.append(data, data_length);
  15613. return true;
  15614. });
  15615. EXPECT_EQ(body, "");
  15616. });
  15617. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15618. const ContentReader &content_reader) {
  15619. ASSERT_TRUE(req.is_multipart_form_data());
  15620. std::vector<FormData> items;
  15621. content_reader(
  15622. [&](const FormData &file) {
  15623. items.push_back(file);
  15624. return true;
  15625. },
  15626. [&](const char *data, size_t data_length) {
  15627. items.back().content.append(data, data_length);
  15628. return true;
  15629. });
  15630. ASSERT_TRUE(items.size() == 2);
  15631. EXPECT_EQ(std::string(items[0].name), "name1");
  15632. EXPECT_EQ(items[0].content, "Testing123");
  15633. EXPECT_EQ(items[0].filename, "filename1");
  15634. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15635. EXPECT_EQ(items[1].name, "name2");
  15636. EXPECT_EQ(items[1].content, "Testing456");
  15637. EXPECT_EQ(items[1].filename, "");
  15638. EXPECT_EQ(items[1].content_type, "");
  15639. });
  15640. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15641. const ContentReader &content_reader) {
  15642. ASSERT_TRUE(req.is_multipart_form_data());
  15643. std::vector<FormData> items;
  15644. content_reader(
  15645. [&](const FormData &file) {
  15646. items.push_back(file);
  15647. return true;
  15648. },
  15649. [&](const char *data, size_t data_length) {
  15650. items.back().content.append(data, data_length);
  15651. return true;
  15652. });
  15653. ASSERT_TRUE(items.size() == 2);
  15654. EXPECT_EQ(items[0].name, "name3");
  15655. EXPECT_EQ(items[0].content, rand1);
  15656. EXPECT_EQ(items[0].filename, "filename3");
  15657. EXPECT_EQ(items[0].content_type, "");
  15658. EXPECT_EQ(items[1].name, "name4");
  15659. EXPECT_EQ(items[1].content, rand2);
  15660. EXPECT_EQ(items[1].filename, "filename4");
  15661. EXPECT_EQ(items[1].content_type, "");
  15662. });
  15663. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15664. const ContentReader &content_reader) {
  15665. ASSERT_TRUE(req.is_multipart_form_data());
  15666. std::vector<FormData> items;
  15667. content_reader(
  15668. [&](const FormData &file) {
  15669. items.push_back(file);
  15670. return true;
  15671. },
  15672. [&](const char *data, size_t data_length) {
  15673. items.back().content.append(data, data_length);
  15674. return true;
  15675. });
  15676. ASSERT_TRUE(items.size() == 4);
  15677. EXPECT_EQ(std::string(items[0].name), "name1");
  15678. EXPECT_EQ(items[0].content, "Testing123");
  15679. EXPECT_EQ(items[0].filename, "filename1");
  15680. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15681. EXPECT_EQ(items[1].name, "name2");
  15682. EXPECT_EQ(items[1].content, "Testing456");
  15683. EXPECT_EQ(items[1].filename, "");
  15684. EXPECT_EQ(items[1].content_type, "");
  15685. EXPECT_EQ(items[2].name, "name3");
  15686. EXPECT_EQ(items[2].content, rand1);
  15687. EXPECT_EQ(items[2].filename, "filename3");
  15688. EXPECT_EQ(items[2].content_type, "");
  15689. EXPECT_EQ(items[3].name, "name4");
  15690. EXPECT_EQ(items[3].content, rand2);
  15691. EXPECT_EQ(items[3].filename, "filename4");
  15692. EXPECT_EQ(items[3].content_type, "");
  15693. });
  15694. auto port = svr.bind_to_any_port("localhost");
  15695. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15696. auto se = detail::scope_exit([&] {
  15697. svr.stop();
  15698. t.join();
  15699. ASSERT_FALSE(svr.is_running());
  15700. });
  15701. svr.wait_until_ready();
  15702. {
  15703. SSLClient cli("localhost", port);
  15704. cli.enable_server_certificate_verification(false);
  15705. UploadFormDataItems items{
  15706. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15707. {"name2", "Testing456", "", ""}, // not a file
  15708. };
  15709. {
  15710. auto res = cli.Post("/post-none", {}, {}, {});
  15711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15712. ASSERT_EQ(StatusCode::OK_200, res->status);
  15713. }
  15714. FormDataProviderItems providers;
  15715. {
  15716. auto res =
  15717. cli.Post("/post-items", {}, items, providers); // empty providers
  15718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15719. ASSERT_EQ(StatusCode::OK_200, res->status);
  15720. }
  15721. providers.push_back({"name3",
  15722. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15723. // test the offset is given correctly at each step
  15724. if (!offset)
  15725. sink.os.write(rand1.data(), 30);
  15726. else if (offset == 30)
  15727. sink.os.write(rand1.data() + 30, 300);
  15728. else if (offset == 330)
  15729. sink.os.write(rand1.data() + 330, 670);
  15730. else if (offset == rand1.size())
  15731. sink.done();
  15732. return true;
  15733. },
  15734. "filename3",
  15735. {}});
  15736. providers.push_back({"name4",
  15737. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15738. // test the offset is given correctly at each step
  15739. if (!offset)
  15740. sink.os.write(rand2.data(), 2000);
  15741. else if (offset == 2000)
  15742. sink.os.write(rand2.data() + 2000, 1);
  15743. else if (offset == 2001)
  15744. sink.os.write(rand2.data() + 2001, 999);
  15745. else if (offset == rand2.size())
  15746. sink.done();
  15747. return true;
  15748. },
  15749. "filename4",
  15750. {}});
  15751. {
  15752. auto res = cli.Post("/post-providers", {}, {}, providers);
  15753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15754. ASSERT_EQ(StatusCode::OK_200, res->status);
  15755. }
  15756. {
  15757. auto res = cli.Post("/post-both", {}, items, providers);
  15758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15759. ASSERT_EQ(StatusCode::OK_200, res->status);
  15760. }
  15761. }
  15762. }
  15763. TEST(MultipartFormDataTest, BadHeader) {
  15764. Server svr;
  15765. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15766. res.set_content("ok", "text/plain");
  15767. });
  15768. thread t = thread([&] { svr.listen(HOST, PORT); });
  15769. auto se = detail::scope_exit([&] {
  15770. svr.stop();
  15771. t.join();
  15772. ASSERT_FALSE(svr.is_running());
  15773. });
  15774. svr.wait_until_ready();
  15775. const std::string body =
  15776. "This is the preamble. It is to be ignored, though it\r\n"
  15777. "is a handy place for composition agents to include an\r\n"
  15778. "explanatory note to non-MIME conformant readers.\r\n"
  15779. "\r\n"
  15780. "\r\n"
  15781. "--simple boundary\r\n"
  15782. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15783. ": BAD...\r\n"
  15784. "\r\n"
  15785. "value1\r\n"
  15786. "--simple boundary\r\n"
  15787. "Content-Disposition: form-data; name=\"field2\"; "
  15788. "filename=\"example.txt\"\r\n"
  15789. "\r\n"
  15790. "value2\r\n"
  15791. "--simple boundary--\r\n"
  15792. "This is the epilogue. It is also to be ignored.\r\n";
  15793. std::string content_type =
  15794. R"(multipart/form-data; boundary="simple boundary")";
  15795. Client cli(HOST, PORT);
  15796. auto res = cli.Post("/post", body, content_type.c_str());
  15797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15798. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15799. }
  15800. TEST(MultipartFormDataTest, WithPreamble) {
  15801. Server svr;
  15802. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15803. res.set_content("ok", "text/plain");
  15804. });
  15805. thread t = thread([&] { svr.listen(HOST, PORT); });
  15806. auto se = detail::scope_exit([&] {
  15807. svr.stop();
  15808. t.join();
  15809. ASSERT_FALSE(svr.is_running());
  15810. });
  15811. svr.wait_until_ready();
  15812. const std::string body =
  15813. "This is the preamble. It is to be ignored, though it\r\n"
  15814. "is a handy place for composition agents to include an\r\n"
  15815. "explanatory note to non-MIME conformant readers.\r\n"
  15816. "\r\n"
  15817. "\r\n"
  15818. "--simple boundary\r\n"
  15819. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15820. "\r\n"
  15821. "value1\r\n"
  15822. "--simple boundary\r\n"
  15823. "Content-Disposition: form-data; name=\"field2\"; "
  15824. "filename=\"example.txt\"\r\n"
  15825. "\r\n"
  15826. "value2\r\n"
  15827. "--simple boundary--\r\n"
  15828. "This is the epilogue. It is also to be ignored.\r\n";
  15829. std::string content_type =
  15830. R"(multipart/form-data; boundary="simple boundary")";
  15831. Client cli(HOST, PORT);
  15832. auto res = cli.Post("/post", body, content_type.c_str());
  15833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15834. EXPECT_EQ(StatusCode::OK_200, res->status);
  15835. }
  15836. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15838. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15839. const ContentReader &content_reader) {
  15840. if (req.is_multipart_form_data()) {
  15841. std::vector<FormData> items;
  15842. content_reader(
  15843. [&](const FormData &file) {
  15844. items.push_back(file);
  15845. return true;
  15846. },
  15847. [&](const char *data, size_t data_length) {
  15848. items.back().content.append(data, data_length);
  15849. return true;
  15850. });
  15851. EXPECT_TRUE(std::string(items[0].name) == "document");
  15852. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15853. EXPECT_TRUE(items[0].filename == "2MB_data");
  15854. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15855. EXPECT_TRUE(items[1].name == "hello");
  15856. EXPECT_TRUE(items[1].content == "world");
  15857. EXPECT_TRUE(items[1].filename == "");
  15858. EXPECT_TRUE(items[1].content_type == "");
  15859. } else {
  15860. std::string body;
  15861. content_reader([&](const char *data, size_t data_length) {
  15862. body.append(data, data_length);
  15863. return true;
  15864. });
  15865. }
  15866. });
  15867. auto port = svr.bind_to_any_port("localhost");
  15868. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15869. auto se = detail::scope_exit([&] {
  15870. svr.stop();
  15871. t.join();
  15872. ASSERT_FALSE(svr.is_running());
  15873. });
  15874. svr.wait_until_ready();
  15875. {
  15876. std::string data(1024 * 1024 * 2, '.');
  15877. std::stringstream buffer;
  15878. buffer << data;
  15879. SSLClient cli("localhost", port);
  15880. cli.enable_server_certificate_verification(false);
  15881. UploadFormDataItems items{
  15882. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15883. {"hello", "world", "", ""},
  15884. };
  15885. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15887. ASSERT_EQ(StatusCode::OK_200, res->status);
  15888. }
  15889. }
  15890. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15891. std::string data(1024 * 1024 * 2, '&');
  15892. std::stringstream buffer;
  15893. buffer << data;
  15894. Client cli("https://localhost:8080");
  15895. UploadFormDataItems items{
  15896. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15897. {"hello", "world", "", ""},
  15898. };
  15899. for (const char &c : " \t\r\n") {
  15900. auto res =
  15901. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15902. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15903. ASSERT_FALSE(res);
  15904. }
  15905. }
  15906. TEST(MultipartFormDataTest, PutFormData) {
  15907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15908. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15909. const ContentReader &content_reader) {
  15910. if (req.is_multipart_form_data()) {
  15911. std::vector<FormData> items;
  15912. content_reader(
  15913. [&](const FormData &file) {
  15914. items.push_back(file);
  15915. return true;
  15916. },
  15917. [&](const char *data, size_t data_length) {
  15918. items.back().content.append(data, data_length);
  15919. return true;
  15920. });
  15921. EXPECT_TRUE(std::string(items[0].name) == "document");
  15922. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15923. EXPECT_TRUE(items[0].filename == "2MB_data");
  15924. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15925. EXPECT_TRUE(items[1].name == "hello");
  15926. EXPECT_TRUE(items[1].content == "world");
  15927. EXPECT_TRUE(items[1].filename == "");
  15928. EXPECT_TRUE(items[1].content_type == "");
  15929. } else {
  15930. std::string body;
  15931. content_reader([&](const char *data, size_t data_length) {
  15932. body.append(data, data_length);
  15933. return true;
  15934. });
  15935. }
  15936. });
  15937. auto port = svr.bind_to_any_port("localhost");
  15938. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15939. auto se = detail::scope_exit([&] {
  15940. svr.stop();
  15941. t.join();
  15942. ASSERT_FALSE(svr.is_running());
  15943. });
  15944. svr.wait_until_ready();
  15945. {
  15946. std::string data(1024 * 1024 * 2, '&');
  15947. std::stringstream buffer;
  15948. buffer << data;
  15949. SSLClient cli("localhost", port);
  15950. cli.enable_server_certificate_verification(false);
  15951. UploadFormDataItems items{
  15952. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15953. {"hello", "world", "", ""},
  15954. };
  15955. auto res = cli.Put("/put", items);
  15956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15957. ASSERT_EQ(StatusCode::OK_200, res->status);
  15958. }
  15959. }
  15960. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15962. svr.Put("/put_customboundary",
  15963. [&](const Request &req, const Response & /*res*/,
  15964. const ContentReader &content_reader) {
  15965. if (req.is_multipart_form_data()) {
  15966. std::vector<FormData> items;
  15967. content_reader(
  15968. [&](const FormData &file) {
  15969. items.push_back(file);
  15970. return true;
  15971. },
  15972. [&](const char *data, size_t data_length) {
  15973. items.back().content.append(data, data_length);
  15974. return true;
  15975. });
  15976. EXPECT_TRUE(std::string(items[0].name) == "document");
  15977. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15978. EXPECT_TRUE(items[0].filename == "2MB_data");
  15979. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15980. EXPECT_TRUE(items[1].name == "hello");
  15981. EXPECT_TRUE(items[1].content == "world");
  15982. EXPECT_TRUE(items[1].filename == "");
  15983. EXPECT_TRUE(items[1].content_type == "");
  15984. } else {
  15985. std::string body;
  15986. content_reader([&](const char *data, size_t data_length) {
  15987. body.append(data, data_length);
  15988. return true;
  15989. });
  15990. }
  15991. });
  15992. auto port = svr.bind_to_any_port("localhost");
  15993. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15994. auto se = detail::scope_exit([&] {
  15995. svr.stop();
  15996. t.join();
  15997. ASSERT_FALSE(svr.is_running());
  15998. });
  15999. svr.wait_until_ready();
  16000. {
  16001. std::string data(1024 * 1024 * 2, '&');
  16002. std::stringstream buffer;
  16003. buffer << data;
  16004. SSLClient cli("localhost", port);
  16005. cli.enable_server_certificate_verification(false);
  16006. UploadFormDataItems items{
  16007. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16008. {"hello", "world", "", ""},
  16009. };
  16010. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16012. ASSERT_EQ(StatusCode::OK_200, res->status);
  16013. }
  16014. }
  16015. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16016. std::string data(1024 * 1024 * 2, '&');
  16017. std::stringstream buffer;
  16018. buffer << data;
  16019. Client cli("https://localhost:8080");
  16020. cli.enable_server_certificate_verification(false);
  16021. UploadFormDataItems items{
  16022. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16023. {"hello", "world", "", ""},
  16024. };
  16025. for (const char &c : " \t\r\n") {
  16026. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16027. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16028. ASSERT_FALSE(res);
  16029. }
  16030. }
  16031. TEST(MultipartFormDataTest, AlternateFilename) {
  16032. auto handled = false;
  16033. Server svr;
  16034. svr.Post("/test", [&](const Request &req, Response &res) {
  16035. ASSERT_EQ(2u, req.form.files.size());
  16036. ASSERT_EQ(1u, req.form.fields.size());
  16037. // Test files
  16038. const auto &file1 = req.form.get_file("file1");
  16039. ASSERT_EQ("file1", file1.name);
  16040. ASSERT_EQ("A.txt", file1.filename);
  16041. ASSERT_EQ("text/plain", file1.content_type);
  16042. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16043. const auto &file2 = req.form.get_file("file2");
  16044. ASSERT_EQ("file2", file2.name);
  16045. ASSERT_EQ("a.html", file2.filename);
  16046. ASSERT_EQ("text/html", file2.content_type);
  16047. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16048. file2.content);
  16049. // Test text field
  16050. const auto &text = req.form.get_field("text");
  16051. ASSERT_EQ("text default", text);
  16052. res.set_content("ok", "text/plain");
  16053. handled = true;
  16054. });
  16055. thread t = thread([&] { svr.listen(HOST, PORT); });
  16056. auto se = detail::scope_exit([&] {
  16057. svr.stop();
  16058. t.join();
  16059. ASSERT_FALSE(svr.is_running());
  16060. ASSERT_TRUE(handled);
  16061. });
  16062. svr.wait_until_ready();
  16063. auto req = "POST /test HTTP/1.1\r\n"
  16064. "Host: localhost\r\n"
  16065. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16066. "Content-Length: 399\r\n"
  16067. "\r\n"
  16068. "----------\r\n"
  16069. "Content-Disposition: form-data; name=\"text\"\r\n"
  16070. "\r\n"
  16071. "text default\r\n"
  16072. "----------\r\n"
  16073. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16074. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16075. "Content-Type: text/plain\r\n"
  16076. "\r\n"
  16077. "Content of a.txt.\r\n"
  16078. "\r\n"
  16079. "----------\r\n"
  16080. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16081. "\"a.html\"\r\n"
  16082. "Content-Type: text/html\r\n"
  16083. "\r\n"
  16084. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16085. "\r\n"
  16086. "------------\r\n";
  16087. ASSERT_TRUE(send_request(1, req));
  16088. }
  16089. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16090. auto handled = false;
  16091. Server svr;
  16092. svr.Post("/test", [&](const Request &req, Response &res) {
  16093. // Case-insensitive "utf-8''" prefix with a long value
  16094. const auto &file = req.form.get_file("file1");
  16095. ASSERT_EQ("file1", file.name);
  16096. // 8000 chars exercises both the Content-Disposition parser and the
  16097. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16098. // Prior to the fix, std::regex_match on this header would cause O(N)
  16099. // stack recursion in libstdc++, leading to SIGSEGV.
  16100. std::string expected_filename(8000, 'A');
  16101. ASSERT_EQ(expected_filename, file.filename);
  16102. res.set_content("ok", "text/plain");
  16103. handled = true;
  16104. });
  16105. thread t = thread([&] { svr.listen(HOST, PORT); });
  16106. auto se = detail::scope_exit([&] {
  16107. svr.stop();
  16108. t.join();
  16109. ASSERT_FALSE(svr.is_running());
  16110. ASSERT_TRUE(handled);
  16111. });
  16112. svr.wait_until_ready();
  16113. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16114. // Regression test for GHSA-qq6v-r583-3h69
  16115. std::string long_filename(8000, 'A');
  16116. std::string body = "----------\r\n"
  16117. "Content-Disposition: form-data; name=\"file1\"; "
  16118. "filename*=\"Utf-8''" +
  16119. long_filename +
  16120. "\"\r\n"
  16121. "\r\n"
  16122. "hello\r\n"
  16123. "------------\r\n";
  16124. auto req = "POST /test HTTP/1.1\r\n"
  16125. "Host: localhost\r\n"
  16126. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16127. "Content-Length: " +
  16128. std::to_string(body.size()) + "\r\n\r\n" + body;
  16129. ASSERT_TRUE(send_request(1, req));
  16130. }
  16131. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16132. auto handled = false;
  16133. Server svr;
  16134. svr.Post("/test", [&](const Request &req, Response &) {
  16135. ASSERT_EQ(2u, req.form.fields.size());
  16136. const auto &text1 = req.form.get_field("text1");
  16137. ASSERT_EQ("text1", text1);
  16138. const auto &text2 = req.form.get_field("text2");
  16139. ASSERT_EQ("text2", text2);
  16140. handled = true;
  16141. });
  16142. thread t = thread([&] { svr.listen(HOST, PORT); });
  16143. auto se = detail::scope_exit([&] {
  16144. svr.stop();
  16145. t.join();
  16146. ASSERT_FALSE(svr.is_running());
  16147. ASSERT_TRUE(handled);
  16148. });
  16149. svr.wait_until_ready();
  16150. auto req = "POST /test HTTP/1.1\r\n"
  16151. "Host: localhost\r\n"
  16152. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16153. "Content-Length: 146\r\n"
  16154. "\r\n----------\r\n"
  16155. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16156. "\r\n"
  16157. "text1"
  16158. "\r\n----------\r\n"
  16159. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16160. "\r\n"
  16161. "text2"
  16162. "\r\n------------";
  16163. std::string response;
  16164. ASSERT_TRUE(send_request(1, req, &response));
  16165. ASSERT_EQ("200", response.substr(9, 3));
  16166. }
  16167. TEST(MultipartFormDataTest, ContentLength) {
  16168. auto handled = false;
  16169. Server svr;
  16170. svr.Post("/test", [&](const Request &req, Response &) {
  16171. ASSERT_EQ(2u, req.form.fields.size());
  16172. const auto &text1 = req.form.get_field("text1");
  16173. ASSERT_EQ("text1", text1);
  16174. const auto &text2 = req.form.get_field("text2");
  16175. ASSERT_EQ("text2", text2);
  16176. handled = true;
  16177. });
  16178. thread t = thread([&] { svr.listen(HOST, PORT); });
  16179. auto se = detail::scope_exit([&] {
  16180. svr.stop();
  16181. t.join();
  16182. ASSERT_FALSE(svr.is_running());
  16183. ASSERT_TRUE(handled);
  16184. });
  16185. svr.wait_until_ready();
  16186. auto req = "POST /test HTTP/1.1\r\n"
  16187. "Host: localhost\r\n"
  16188. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16189. "Content-Length: 167\r\n"
  16190. "\r\n----------\r\n"
  16191. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16192. "Content-Length: 5\r\n"
  16193. "\r\n"
  16194. "text1"
  16195. "\r\n----------\r\n"
  16196. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16197. "\r\n"
  16198. "text2"
  16199. "\r\n------------\r\n";
  16200. std::string response;
  16201. ASSERT_TRUE(send_request(1, req, &response));
  16202. ASSERT_EQ("200", response.substr(9, 3));
  16203. }
  16204. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16205. auto handled = false;
  16206. Server svr;
  16207. svr.Post("/test", [&](const Request &req, Response &) {
  16208. ASSERT_EQ(2u, req.form.fields.size());
  16209. const auto &text1 = req.form.get_field("text1");
  16210. ASSERT_EQ("text1", text1);
  16211. // TODO: Add header access for text fields if needed
  16212. const auto &text2 = req.form.get_field("text2");
  16213. ASSERT_EQ("text2", text2);
  16214. // TODO: Header access for text fields needs to be implemented
  16215. // auto &headers = it->second.headers;
  16216. // ASSERT_EQ(3U, headers.size());
  16217. // auto custom_header = headers.find("x-whatever");
  16218. // ASSERT_TRUE(custom_header != headers.end());
  16219. // ASSERT_NE("customvalue", custom_header->second);
  16220. // ASSERT_EQ("CustomValue", custom_header->second);
  16221. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16222. handled = true;
  16223. });
  16224. thread t = thread([&] { svr.listen(HOST, PORT); });
  16225. auto se = detail::scope_exit([&] {
  16226. svr.stop();
  16227. t.join();
  16228. ASSERT_FALSE(svr.is_running());
  16229. ASSERT_TRUE(handled);
  16230. });
  16231. svr.wait_until_ready();
  16232. auto req = "POST /test HTTP/1.1\r\n"
  16233. "Host: localhost\r\n"
  16234. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16235. "Content-Length: 232\r\n"
  16236. "\r\n----------\r\n"
  16237. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16238. "Content-Length: 5\r\n"
  16239. "X-Test: 1\r\n"
  16240. "\r\n"
  16241. "text1"
  16242. "\r\n----------\r\n"
  16243. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16244. "Content-Type: text/plain\r\n"
  16245. "X-Whatever: CustomValue\r\n"
  16246. "\r\n"
  16247. "text2"
  16248. "\r\n------------\r\n"
  16249. "That should be disregarded. Not even read";
  16250. std::string response;
  16251. ASSERT_TRUE(send_request(1, req, &response));
  16252. ASSERT_EQ("200", response.substr(9, 3));
  16253. }
  16254. TEST(MultipartFormDataTest, LargeHeader) {
  16255. auto handled = false;
  16256. Server svr;
  16257. svr.Post("/test", [&](const Request &req, Response &) {
  16258. ASSERT_EQ(1u, req.form.fields.size());
  16259. const auto &text = req.form.get_field("name1");
  16260. ASSERT_EQ("text1", text);
  16261. handled = true;
  16262. });
  16263. thread t = thread([&] { svr.listen(HOST, PORT); });
  16264. auto se = detail::scope_exit([&] {
  16265. svr.stop();
  16266. t.join();
  16267. ASSERT_FALSE(svr.is_running());
  16268. ASSERT_TRUE(handled);
  16269. });
  16270. svr.wait_until_ready();
  16271. auto boundary = std::string("cpp-httplib-multipart-data");
  16272. std::string content = "--" + boundary +
  16273. "\r\n"
  16274. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16275. "\r\n"
  16276. "text1\r\n"
  16277. "--" +
  16278. boundary + "--\r\n";
  16279. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16280. "Host: localhost\r\n"
  16281. "Content-Type: multipart/form-data;boundary=" +
  16282. boundary +
  16283. "\r\n"
  16284. "Content-Length: " +
  16285. std::to_string(content.size()) +
  16286. "\r\n"
  16287. "Dummy-Header: ";
  16288. std::string header_suffix = "\r\n"
  16289. "\r\n";
  16290. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16291. size_t header_dummy_size =
  16292. read_buff_size -
  16293. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16294. auto header_dummy = std::string(header_dummy_size, '@');
  16295. auto req = header_prefix + header_dummy + header_suffix + content;
  16296. std::string response;
  16297. ASSERT_TRUE(send_request(1, req, &response));
  16298. ASSERT_EQ("200", response.substr(9, 3));
  16299. }
  16300. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16301. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16302. // (not chunked Transfer-Encoding) after the streaming refactor.
  16303. auto handled = false;
  16304. Server svr;
  16305. svr.Post("/upload", [&](const Request &req, Response &res) {
  16306. auto cl_it = req.headers.find("Content-Length");
  16307. EXPECT_TRUE(cl_it != req.headers.end());
  16308. auto te_it = req.headers.find("Transfer-Encoding");
  16309. EXPECT_TRUE(te_it == req.headers.end());
  16310. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16311. res.set_content("ok", "text/plain");
  16312. handled = true;
  16313. });
  16314. auto port = svr.bind_to_any_port(HOST);
  16315. auto t = thread([&] { svr.listen_after_bind(); });
  16316. auto se = detail::scope_exit([&] {
  16317. svr.stop();
  16318. t.join();
  16319. ASSERT_FALSE(svr.is_running());
  16320. ASSERT_TRUE(handled);
  16321. });
  16322. svr.wait_until_ready();
  16323. UploadFormDataItems items = {
  16324. {"field1", "hello", "", "text/plain"},
  16325. {"file1", "world", "test.txt", "application/octet-stream"},
  16326. };
  16327. Client cli(HOST, port);
  16328. auto res = cli.Post("/upload", {}, items);
  16329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16330. EXPECT_EQ(StatusCode::OK_200, res->status);
  16331. }
  16332. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16333. // Verify that make_multipart_content_provider coalesces many small segments
  16334. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16335. constexpr size_t kItemCount = 1000;
  16336. UploadFormDataItems items;
  16337. items.reserve(kItemCount);
  16338. for (size_t i = 0; i < kItemCount; i++) {
  16339. items.push_back(
  16340. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16341. }
  16342. const std::string boundary = "----test-boundary";
  16343. auto content_length = detail::get_multipart_content_length(items, boundary);
  16344. auto provider = detail::make_multipart_content_provider(items, boundary);
  16345. // Drive the provider the same way write_content_with_progress does
  16346. size_t write_count = 0;
  16347. size_t total_bytes = 0;
  16348. DataSink sink;
  16349. size_t offset = 0;
  16350. sink.write = [&](const char *d, size_t l) -> bool {
  16351. (void)d;
  16352. write_count++;
  16353. total_bytes += l;
  16354. offset += l;
  16355. return true;
  16356. };
  16357. sink.is_writable = []() -> bool { return true; };
  16358. while (offset < content_length) {
  16359. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16360. }
  16361. EXPECT_EQ(content_length, total_bytes);
  16362. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16363. // With buffering into 64KB blocks, write_count should be much smaller.
  16364. auto segment_count = 3 * kItemCount + 1;
  16365. EXPECT_LT(write_count, segment_count / 10);
  16366. }
  16367. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16368. // Integration test: send many UploadFormDataItems and verify the server
  16369. // receives all of them correctly (#2410).
  16370. constexpr size_t kItemCount = 500;
  16371. auto handled = false;
  16372. Server svr;
  16373. svr.Post("/upload", [&](const Request &req, Response &res) {
  16374. EXPECT_EQ(kItemCount, req.form.fields.size());
  16375. for (size_t i = 0; i < kItemCount; i++) {
  16376. auto key = "field" + std::to_string(i);
  16377. auto val = "value" + std::to_string(i);
  16378. auto it = req.form.fields.find(key);
  16379. if (it != req.form.fields.end()) {
  16380. EXPECT_EQ(val, it->second.content);
  16381. } else {
  16382. ADD_FAILURE() << "Missing field: " << key;
  16383. }
  16384. }
  16385. res.set_content("ok", "text/plain");
  16386. handled = true;
  16387. });
  16388. auto port = svr.bind_to_any_port(HOST);
  16389. auto t = thread([&] { svr.listen_after_bind(); });
  16390. auto se = detail::scope_exit([&] {
  16391. svr.stop();
  16392. t.join();
  16393. ASSERT_FALSE(svr.is_running());
  16394. ASSERT_TRUE(handled);
  16395. });
  16396. svr.wait_until_ready();
  16397. UploadFormDataItems items;
  16398. items.reserve(kItemCount);
  16399. for (size_t i = 0; i < kItemCount; i++) {
  16400. items.push_back(
  16401. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16402. }
  16403. Client cli(HOST, port);
  16404. auto res = cli.Post("/upload", items);
  16405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16406. EXPECT_EQ(StatusCode::OK_200, res->status);
  16407. }
  16408. TEST(MultipartFormDataTest, MakeFileProvider) {
  16409. // Verify make_file_provider sends a file's contents correctly.
  16410. const std::string file_content(4096, 'Z');
  16411. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16412. {
  16413. std::ofstream ofs(tmp_path, std::ios::binary);
  16414. ofs.write(file_content.data(),
  16415. static_cast<std::streamsize>(file_content.size()));
  16416. }
  16417. auto handled = false;
  16418. Server svr;
  16419. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16420. const ContentReader &content_reader) {
  16421. ASSERT_TRUE(req.is_multipart_form_data());
  16422. std::vector<FormData> items;
  16423. content_reader(
  16424. [&](const FormData &file) {
  16425. items.push_back(file);
  16426. return true;
  16427. },
  16428. [&](const char *data, size_t data_length) {
  16429. items.back().content.append(data, data_length);
  16430. return true;
  16431. });
  16432. ASSERT_EQ(1u, items.size());
  16433. EXPECT_EQ("myfile", items[0].name);
  16434. EXPECT_EQ("data.bin", items[0].filename);
  16435. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16436. EXPECT_EQ(file_content, items[0].content);
  16437. handled = true;
  16438. });
  16439. auto port = svr.bind_to_any_port(HOST);
  16440. auto t = thread([&] { svr.listen_after_bind(); });
  16441. auto se = detail::scope_exit([&] {
  16442. svr.stop();
  16443. t.join();
  16444. ASSERT_FALSE(svr.is_running());
  16445. ASSERT_TRUE(handled);
  16446. std::remove(tmp_path.c_str());
  16447. });
  16448. svr.wait_until_ready();
  16449. FormDataProviderItems providers;
  16450. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16451. "application/octet-stream"));
  16452. Client cli(HOST, port);
  16453. auto res = cli.Post("/upload", {}, {}, providers);
  16454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16455. EXPECT_EQ(StatusCode::OK_200, res->status);
  16456. }
  16457. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16458. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16459. // (100) headers is rejected with a 400 Bad Request response.
  16460. Server svr;
  16461. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16462. res.set_content("ok", "text/plain");
  16463. });
  16464. thread t = thread([&] { svr.listen(HOST, PORT); });
  16465. auto se = detail::scope_exit([&] {
  16466. svr.stop();
  16467. t.join();
  16468. ASSERT_FALSE(svr.is_running());
  16469. });
  16470. svr.wait_until_ready();
  16471. // Build a multipart part with 101 custom headers (exceeding
  16472. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16473. std::stringstream body;
  16474. body << "--simpleboundary\r\n"
  16475. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16476. for (int i = 0; i < 101; i++) {
  16477. body << "X-Custom-Header-" << i << ": value\r\n";
  16478. }
  16479. body << "\r\n"
  16480. << "value1\r\n"
  16481. << "--simpleboundary--\r\n";
  16482. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16483. Client cli(HOST, PORT);
  16484. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16486. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16487. }
  16488. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16489. // A body that never contains the declared boundary must not be accumulated
  16490. // while the parser waits for it. Buffering it would also make every read
  16491. // rescan everything seen so far, which is quadratic in the body size.
  16492. Server svr;
  16493. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16494. res.set_content("ok", "text/plain");
  16495. });
  16496. auto port = svr.bind_to_any_port(HOST);
  16497. thread t = thread([&] { svr.listen_after_bind(); });
  16498. auto se = detail::scope_exit([&] {
  16499. svr.stop();
  16500. t.join();
  16501. ASSERT_FALSE(svr.is_running());
  16502. });
  16503. svr.wait_until_ready();
  16504. Client cli(HOST, port);
  16505. cli.set_read_timeout(60, 0);
  16506. cli.set_write_timeout(60, 0);
  16507. // '-' is the worst case: it matches the first character of the boundary, so
  16508. // every position has to be checked against it.
  16509. auto post_dashes = [&](size_t size) {
  16510. const std::string body(size, '-');
  16511. auto start = std::chrono::steady_clock::now();
  16512. auto res =
  16513. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16514. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16515. std::chrono::steady_clock::now() - start)
  16516. .count();
  16517. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16518. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16519. return ms;
  16520. };
  16521. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16522. // Windows.
  16523. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16524. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16525. // Comparing the two sizes rather than checking an absolute duration keeps
  16526. // this meaningful across build types and CI load, both of which move the
  16527. // absolute numbers by more than an order of magnitude. Four times the bytes
  16528. // costs about four times the time when parsing is linear, and about sixteen
  16529. // times when the body is buffered and rescanned.
  16530. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16531. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16532. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16533. << "ms, which suggests the body is being buffered and rescanned";
  16534. }
  16535. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16536. // A boundary can only be followed by CRLF or by "--", so anything else is
  16537. // malformed no matter what comes next. The parser must say so right away
  16538. // instead of buffering the rest of the declared body.
  16539. Server svr;
  16540. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16541. res.set_content("ok", "text/plain");
  16542. });
  16543. auto port = svr.bind_to_any_port(HOST);
  16544. thread t = thread([&] { svr.listen_after_bind(); });
  16545. auto se = detail::scope_exit([&] {
  16546. svr.stop();
  16547. t.join();
  16548. ASSERT_FALSE(svr.is_running());
  16549. });
  16550. svr.wait_until_ready();
  16551. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16552. // buffers instead of failing would still be waiting for the remaining bytes.
  16553. const std::string body = "--zzzz\r\n"
  16554. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16555. "\r\n"
  16556. "text1"
  16557. "\r\n--zzzzXX";
  16558. const std::string req = "POST /post HTTP/1.1\r\n"
  16559. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16560. "Content-Length: 1048576\r\n"
  16561. "\r\n" +
  16562. body;
  16563. std::string response;
  16564. ASSERT_TRUE(send_request(3, req, &response, port));
  16565. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16566. EXPECT_EQ("400", response.substr(9, 3));
  16567. }
  16568. // Posts a multipart body split into two writes, so that the server sees the
  16569. // split at whatever offset the caller chose, and expects the single "text1"
  16570. // field to come through.
  16571. static void expect_split_multipart_ok(const std::string &body1,
  16572. const std::string &body2) {
  16573. auto handled = false;
  16574. Server svr;
  16575. svr.Post("/post", [&](const Request &req, Response &) {
  16576. EXPECT_EQ(1u, req.form.fields.size());
  16577. EXPECT_EQ("text1", req.form.get_field("text1"));
  16578. handled = true;
  16579. });
  16580. auto port = svr.bind_to_any_port(HOST);
  16581. thread t = thread([&] { svr.listen_after_bind(); });
  16582. auto se = detail::scope_exit([&] {
  16583. svr.stop();
  16584. t.join();
  16585. ASSERT_FALSE(svr.is_running());
  16586. ASSERT_TRUE(handled);
  16587. });
  16588. svr.wait_until_ready();
  16589. // "Connection: close" makes the server close once it has answered, so the
  16590. // response drain ends immediately instead of idling until the read timeout.
  16591. const std::string head =
  16592. "POST /post HTTP/1.1\r\n"
  16593. "Host: localhost\r\n"
  16594. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16595. "Connection: close\r\n"
  16596. "Content-Length: " +
  16597. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16598. std::string response;
  16599. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16600. ASSERT_GE(response.size(), 12u) << "no response";
  16601. EXPECT_EQ("200", response.substr(9, 3));
  16602. }
  16603. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16604. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16605. // ignored, including when it does not arrive in the same read as the
  16606. // close-delimiter itself.
  16607. expect_split_multipart_ok("--zzzz\r\n"
  16608. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16609. "\r\n"
  16610. "text1"
  16611. "\r\n--zzzz--",
  16612. "\r\nthis epilogue must be ignored\r\n");
  16613. }
  16614. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16615. // The initial boundary may be preceded by a preamble of any length and may
  16616. // straddle a read boundary. Discarding data while waiting for it must not
  16617. // throw away a partial boundary sitting at the end of the buffer.
  16618. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16619. "zz\r\n"
  16620. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16621. "\r\n"
  16622. "text1"
  16623. "\r\n--zzzz--\r\n");
  16624. }
  16625. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16626. // The received boundary was only checked for being non-empty, so it could be
  16627. // as long as a header is allowed to be. The parser scans the body for
  16628. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16629. // costs a nearly full comparison at nearly every position, making the
  16630. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16631. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16632. Server svr;
  16633. svr.Post("/post", [](const Request &req, Response &res) {
  16634. EXPECT_EQ(1u, req.form.fields.size());
  16635. EXPECT_EQ("text1", req.form.get_field("text1"));
  16636. res.set_content("ok", "text/plain");
  16637. });
  16638. auto port = svr.bind_to_any_port(HOST);
  16639. thread t = thread([&] { svr.listen_after_bind(); });
  16640. auto se = detail::scope_exit([&] {
  16641. svr.stop();
  16642. t.join();
  16643. ASSERT_FALSE(svr.is_running());
  16644. });
  16645. svr.wait_until_ready();
  16646. Client cli(HOST, port);
  16647. auto post_with_boundary_of_length = [&](size_t len) {
  16648. const std::string boundary(len, 'a');
  16649. const std::string body =
  16650. "--" + boundary +
  16651. "\r\n"
  16652. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16653. "\r\n"
  16654. "text1"
  16655. "\r\n--" +
  16656. boundary + "--\r\n";
  16657. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16658. };
  16659. auto res = post_with_boundary_of_length(70);
  16660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16661. EXPECT_EQ(StatusCode::OK_200, res->status);
  16662. res = post_with_boundary_of_length(71);
  16663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16664. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16665. }
  16666. TEST(MakeFileBodyTest, Basic) {
  16667. const std::string file_content(4096, 'Z');
  16668. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16669. {
  16670. std::ofstream ofs(tmp_path, std::ios::binary);
  16671. ofs.write(file_content.data(),
  16672. static_cast<std::streamsize>(file_content.size()));
  16673. }
  16674. auto handled = false;
  16675. Server svr;
  16676. svr.Post("/upload", [&](const Request &req, Response &res) {
  16677. EXPECT_EQ(file_content, req.body);
  16678. handled = true;
  16679. res.status = StatusCode::OK_200;
  16680. });
  16681. auto port = svr.bind_to_any_port(HOST);
  16682. auto t = thread([&] { svr.listen_after_bind(); });
  16683. auto se = detail::scope_exit([&] {
  16684. svr.stop();
  16685. t.join();
  16686. ASSERT_FALSE(svr.is_running());
  16687. ASSERT_TRUE(handled);
  16688. std::remove(tmp_path.c_str());
  16689. });
  16690. svr.wait_until_ready();
  16691. auto fb = make_file_body(tmp_path);
  16692. ASSERT_GT(fb.first, 0u);
  16693. Client cli(HOST, port);
  16694. auto res =
  16695. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16697. EXPECT_EQ(StatusCode::OK_200, res->status);
  16698. }
  16699. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16700. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16701. {
  16702. std::ofstream ofs(path, std::ios::binary);
  16703. const std::string content(100, 'A');
  16704. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16705. }
  16706. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16707. auto body = make_file_body(path);
  16708. ASSERT_EQ(100u, body.first);
  16709. ASSERT_TRUE(static_cast<bool>(body.second));
  16710. // Rewritten shorter after its length was measured - and, on a server, after
  16711. // that length has already gone out as Content-Length.
  16712. {
  16713. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16714. const std::string content(10, 'A');
  16715. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16716. }
  16717. std::string written;
  16718. DataSink sink;
  16719. sink.write = [&](const char *d, size_t l) {
  16720. written.append(d, l);
  16721. return true;
  16722. };
  16723. // The provider has to report failure. write_content_with_progress() advances
  16724. // its offset only by what was written, so a provider that returns true
  16725. // without completing the length it promised is called again straight away,
  16726. // and again.
  16727. EXPECT_FALSE(body.second(0, body.first, sink));
  16728. EXPECT_EQ(std::string(10, 'A'), written);
  16729. }
  16730. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16731. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16732. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16733. {
  16734. std::ofstream ofs(path, std::ios::binary);
  16735. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16736. }
  16737. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16738. auto body = make_file_body(path);
  16739. ASSERT_EQ(content.size(), body.first);
  16740. ASSERT_TRUE(static_cast<bool>(body.second));
  16741. std::string written;
  16742. DataSink sink;
  16743. sink.write = [&](const char *d, size_t l) {
  16744. written.append(d, l);
  16745. return true;
  16746. };
  16747. EXPECT_TRUE(body.second(0, body.first, sink));
  16748. EXPECT_EQ(content, written);
  16749. }
  16750. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16751. static constexpr unsigned int number_of_tasks{1000000};
  16752. std::atomic_uint count{0};
  16753. std::unique_ptr<TaskQueue> task_queue{
  16754. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16755. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16756. auto queued = task_queue->enqueue(
  16757. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16758. EXPECT_TRUE(queued);
  16759. }
  16760. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16761. task_queue->shutdown();
  16762. #else
  16763. EXPECT_NO_THROW(task_queue->shutdown());
  16764. #endif
  16765. EXPECT_EQ(number_of_tasks, count.load());
  16766. }
  16767. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16768. static constexpr unsigned int number_of_tasks{1000000};
  16769. static constexpr unsigned int qlimit{2};
  16770. unsigned int queued_count{0};
  16771. std::atomic_uint count{0};
  16772. std::unique_ptr<TaskQueue> task_queue{
  16773. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16774. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16775. if (task_queue->enqueue(
  16776. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16777. queued_count++;
  16778. }
  16779. }
  16780. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16781. task_queue->shutdown();
  16782. #else
  16783. EXPECT_NO_THROW(task_queue->shutdown());
  16784. #endif
  16785. EXPECT_EQ(queued_count, count.load());
  16786. EXPECT_TRUE(queued_count <= number_of_tasks);
  16787. EXPECT_TRUE(queued_count >= qlimit);
  16788. }
  16789. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16790. // Use a short idle timeout so a dynamic thread spawns, times out and
  16791. // exits during the test, and the pool keeps working afterwards.
  16792. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16793. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16794. /*idle_timeout_sec=*/1}};
  16795. std::atomic_uint count{0};
  16796. std::condition_variable cv;
  16797. std::mutex mtx;
  16798. bool release = false;
  16799. // Block the base thread so the second task spawns a dynamic thread.
  16800. EXPECT_TRUE(task_queue->enqueue([&] {
  16801. std::unique_lock<std::mutex> lock(mtx);
  16802. while (!release) {
  16803. cv.wait(lock);
  16804. }
  16805. count++;
  16806. }));
  16807. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16808. // Let the dynamic thread finish its task and exceed the idle timeout.
  16809. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16810. {
  16811. std::unique_lock<std::mutex> lock(mtx);
  16812. release = true;
  16813. }
  16814. cv.notify_all();
  16815. // The pool must still accept and run tasks after the dynamic thread exited.
  16816. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16817. task_queue->shutdown();
  16818. EXPECT_EQ(3u, count.load());
  16819. }
  16820. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16821. static constexpr size_t number_of_tasks{32};
  16822. std::unique_ptr<TaskQueue> task_queue{
  16823. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16824. // Let the base threads go idle so the burst below finds them waiting.
  16825. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16826. std::mutex mtx;
  16827. std::condition_variable cv;
  16828. size_t running = 0;
  16829. bool release = false;
  16830. for (size_t i = 0; i < number_of_tasks; i++) {
  16831. EXPECT_TRUE(task_queue->enqueue([&] {
  16832. std::unique_lock<std::mutex> lock(mtx);
  16833. running++;
  16834. cv.notify_all();
  16835. cv.wait(lock, [&] { return release; });
  16836. }));
  16837. }
  16838. {
  16839. std::unique_lock<std::mutex> lock(mtx);
  16840. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16841. [&] { return running == number_of_tasks; }));
  16842. release = true;
  16843. }
  16844. cv.notify_all();
  16845. task_queue->shutdown();
  16846. }
  16847. TEST(TaskQueueTest, MaxQueuedRequests) {
  16848. static constexpr unsigned int qlimit{3};
  16849. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16850. std::condition_variable sem_cv;
  16851. std::mutex sem_mtx;
  16852. int credits = 0;
  16853. bool queued;
  16854. /* Fill up the queue with tasks that will block until we give them credits to
  16855. * complete. */
  16856. for (unsigned int n = 0; n <= qlimit;) {
  16857. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16858. std::unique_lock<std::mutex> lock(sem_mtx);
  16859. while (credits <= 0) {
  16860. sem_cv.wait(lock);
  16861. }
  16862. /* Consume the credit and signal the test code if they are all gone. */
  16863. if (--credits == 0) { sem_cv.notify_one(); }
  16864. });
  16865. if (n < qlimit) {
  16866. /* The first qlimit enqueues must succeed. */
  16867. EXPECT_TRUE(queued);
  16868. } else {
  16869. /* The last one will succeed only when the worker thread
  16870. * starts and dequeues the first blocking task. Although
  16871. * not necessary for the correctness of this test, we sleep for
  16872. * a short while to avoid busy waiting. */
  16873. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16874. }
  16875. if (queued) { n++; }
  16876. }
  16877. /* Further enqueues must fail since the queue is full. */
  16878. for (auto i = 0; i < 4; i++) {
  16879. queued = task_queue->enqueue([] {});
  16880. EXPECT_FALSE(queued);
  16881. }
  16882. /* Give the credits to allow the previous tasks to complete. */
  16883. {
  16884. std::unique_lock<std::mutex> lock(sem_mtx);
  16885. credits += qlimit + 1;
  16886. }
  16887. sem_cv.notify_all();
  16888. /* Wait for all the credits to be consumed. */
  16889. {
  16890. std::unique_lock<std::mutex> lock(sem_mtx);
  16891. while (credits > 0) {
  16892. sem_cv.wait(lock);
  16893. }
  16894. }
  16895. /* Check that we are able again to enqueue at least qlimit tasks. */
  16896. for (unsigned int i = 0; i < qlimit; i++) {
  16897. queued = task_queue->enqueue([] {});
  16898. EXPECT_TRUE(queued);
  16899. }
  16900. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16901. task_queue->shutdown();
  16902. #else
  16903. EXPECT_NO_THROW(task_queue->shutdown());
  16904. #endif
  16905. }
  16906. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16907. Server svr;
  16908. std::string method;
  16909. std::string body;
  16910. auto has_content_length = false;
  16911. auto has_transfer_encoding = false;
  16912. std::atomic<int> bad_requests{0};
  16913. // Leftover body bytes get parsed as a malformed request and answered with
  16914. // 400
  16915. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16916. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16917. });
  16918. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16919. res.set_redirect("/down", StatusCode::SeeOther_303);
  16920. });
  16921. svr.Get("/down", [&](const Request &req, Response &res) {
  16922. method = req.method;
  16923. body = req.body;
  16924. has_content_length = req.has_header("Content-Length");
  16925. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16926. res.set_content("ok", "text/plain");
  16927. });
  16928. auto port = svr.bind_to_any_port(HOST);
  16929. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16930. auto se = detail::scope_exit([&] {
  16931. svr.stop();
  16932. thread.join();
  16933. ASSERT_FALSE(svr.is_running());
  16934. });
  16935. svr.wait_until_ready();
  16936. const std::string payload = "SECRET-BODY";
  16937. auto check = [&](Client &cli, const Result &res) {
  16938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16939. EXPECT_EQ(StatusCode::OK_200, res->status);
  16940. EXPECT_EQ("ok", res->body);
  16941. EXPECT_EQ("GET", method);
  16942. EXPECT_TRUE(body.empty());
  16943. EXPECT_FALSE(has_content_length);
  16944. EXPECT_FALSE(has_transfer_encoding);
  16945. // Nothing of the original body may be left on the connection
  16946. auto res2 = cli.Get("/down");
  16947. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16948. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16949. EXPECT_EQ("ok", res2->body);
  16950. EXPECT_EQ(0, bad_requests);
  16951. };
  16952. // With content length
  16953. {
  16954. Client cli(HOST, port);
  16955. cli.set_keep_alive(true);
  16956. cli.set_follow_location(true);
  16957. auto res = cli.Post(
  16958. "/up", payload.size(),
  16959. [&](size_t offset, size_t length, DataSink &sink) {
  16960. return sink.write(payload.data() + offset, length);
  16961. },
  16962. "text/plain");
  16963. check(cli, res);
  16964. }
  16965. // Without content length (chunked)
  16966. {
  16967. Client cli(HOST, port);
  16968. cli.set_keep_alive(true);
  16969. cli.set_follow_location(true);
  16970. auto res = cli.Post(
  16971. "/up",
  16972. [&](size_t /*offset*/, DataSink &sink) {
  16973. sink.write(payload.data(), payload.size());
  16974. sink.done();
  16975. return true;
  16976. },
  16977. "text/plain");
  16978. check(cli, res);
  16979. }
  16980. }
  16981. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16982. Server svr;
  16983. std::string target;
  16984. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16985. // Echo the still-encoded name back in the Location
  16986. const std::string prefix = "/start/";
  16987. res.status = StatusCode::Found_302;
  16988. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16989. });
  16990. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16991. target = req.target;
  16992. res.set_content("ok", "text/plain");
  16993. });
  16994. auto port = svr.bind_to_any_port(HOST);
  16995. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16996. auto se = detail::scope_exit([&] {
  16997. svr.stop();
  16998. thread.join();
  16999. ASSERT_FALSE(svr.is_running());
  17000. });
  17001. svr.wait_until_ready();
  17002. // Decoding the Location path would turn the first four into a path
  17003. // separator, a query delimiter, a fragment delimiter and a different
  17004. // percent-encoded octet. The rest must keep reaching the server as they are.
  17005. const std::vector<std::string> names = {
  17006. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17007. };
  17008. for (auto path_encode : {true, false}) {
  17009. Client cli(HOST, port);
  17010. cli.set_follow_location(true);
  17011. cli.set_path_encode(path_encode);
  17012. for (const auto &name : names) {
  17013. target.clear();
  17014. auto res = cli.Get("/start/" + name);
  17015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17016. EXPECT_EQ(StatusCode::OK_200, res->status);
  17017. EXPECT_EQ("/dest/" + name, target);
  17018. }
  17019. }
  17020. }
  17021. TEST(RedirectTest, NotModifiedIsReturned) {
  17022. Server svr;
  17023. svr.Get("/cached", [](const Request &, Response &res) {
  17024. res.status = StatusCode::NotModified_304;
  17025. });
  17026. auto port = svr.bind_to_any_port(HOST);
  17027. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17028. auto se = detail::scope_exit([&] {
  17029. svr.stop();
  17030. thread.join();
  17031. ASSERT_FALSE(svr.is_running());
  17032. });
  17033. svr.wait_until_ready();
  17034. Client cli(HOST, port);
  17035. cli.set_follow_location(true);
  17036. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17038. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17039. }
  17040. TEST(RedirectTest, NoLocationIsReturned) {
  17041. Server svr;
  17042. svr.Get("/no-location", [](const Request &, Response &res) {
  17043. res.status = StatusCode::Found_302;
  17044. res.set_content("no location", "text/plain");
  17045. });
  17046. auto port = svr.bind_to_any_port(HOST);
  17047. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17048. auto se = detail::scope_exit([&] {
  17049. svr.stop();
  17050. thread.join();
  17051. ASSERT_FALSE(svr.is_running());
  17052. });
  17053. svr.wait_until_ready();
  17054. Client cli(HOST, port);
  17055. cli.set_follow_location(true);
  17056. auto res = cli.Get("/no-location");
  17057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17058. EXPECT_EQ(StatusCode::Found_302, res->status);
  17059. EXPECT_EQ("no location", res->body);
  17060. // The callbacks see the body of the response that is returned
  17061. auto handler_called = false;
  17062. auto progress_called = false;
  17063. std::string body;
  17064. auto res2 = cli.Get(
  17065. "/no-location",
  17066. [&](const Response &) {
  17067. handler_called = true;
  17068. return true;
  17069. },
  17070. [&](const char *data, size_t data_length) {
  17071. body.append(data, data_length);
  17072. return true;
  17073. },
  17074. [&](size_t, size_t) {
  17075. progress_called = true;
  17076. return true;
  17077. });
  17078. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17079. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17080. EXPECT_TRUE(handler_called);
  17081. EXPECT_TRUE(progress_called);
  17082. EXPECT_EQ("no location", body);
  17083. }
  17084. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17085. Server svr;
  17086. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17087. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17088. });
  17089. svr.Get("/hello", [](const Request &req, Response &res) {
  17090. res.set_content(req.get_param_value("key"), "text/plain");
  17091. });
  17092. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17093. auto se = detail::scope_exit([&] {
  17094. svr.stop();
  17095. thread.join();
  17096. ASSERT_FALSE(svr.is_running());
  17097. });
  17098. svr.wait_until_ready();
  17099. {
  17100. Client cli(HOST, PORT);
  17101. cli.set_follow_location(true);
  17102. auto res = cli.Get("/");
  17103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17104. EXPECT_EQ(StatusCode::OK_200, res->status);
  17105. EXPECT_EQ("val&key2=val2", res->body);
  17106. }
  17107. }
  17108. #endif
  17109. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17110. Server svr;
  17111. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17112. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17113. });
  17114. svr.Get("/hello", [](const Request &req, Response &res) {
  17115. res.set_content(req.get_param_value("key"), "text/plain");
  17116. });
  17117. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17118. auto se = detail::scope_exit([&] {
  17119. svr.stop();
  17120. thread.join();
  17121. ASSERT_FALSE(svr.is_running());
  17122. });
  17123. svr.wait_until_ready();
  17124. {
  17125. Client cli(HOST, PORT);
  17126. cli.set_follow_location(true);
  17127. auto res = cli.Get("/");
  17128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17129. EXPECT_EQ(StatusCode::OK_200, res->status);
  17130. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17131. }
  17132. }
  17133. TEST(RedirectTest, RedirectWithPlusInPath) {
  17134. Server svr;
  17135. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17136. res.set_redirect("/a+b");
  17137. });
  17138. // Route pattern uses regex; escape + as \\+
  17139. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17140. res.set_content(req.path, "text/plain");
  17141. });
  17142. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17143. auto se = detail::scope_exit([&] {
  17144. svr.stop();
  17145. thread.join();
  17146. ASSERT_FALSE(svr.is_running());
  17147. });
  17148. svr.wait_until_ready();
  17149. {
  17150. Client cli(HOST, PORT);
  17151. cli.set_follow_location(true);
  17152. auto res = cli.Get("/");
  17153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17154. EXPECT_EQ(StatusCode::OK_200, res->status);
  17155. EXPECT_EQ("/a+b", res->body);
  17156. }
  17157. }
  17158. TEST(RedirectTest, ResolveRelativeLocation) {
  17159. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17160. const std::vector<std::pair<std::string, std::string>> cases = {
  17161. {"g", "/b/c/g"},
  17162. {"./g", "/b/c/g"},
  17163. {"g/", "/b/c/g/"},
  17164. {"?y", "/b/c/d;p?y"},
  17165. {"g?y", "/b/c/g?y"},
  17166. {"#s", "/b/c/d;p?q#s"},
  17167. {"g#s", "/b/c/g#s"},
  17168. {"g?y#s", "/b/c/g?y#s"},
  17169. {";x", "/b/c/;x"},
  17170. {"g;x", "/b/c/g;x"},
  17171. {".", "/b/c/"},
  17172. {"./", "/b/c/"},
  17173. {"..", "/b/"},
  17174. {"../", "/b/"},
  17175. {"../g", "/b/g"},
  17176. {"../..", "/"},
  17177. {"../../", "/"},
  17178. {"../../g", "/g"},
  17179. {"../../../g", "/g"},
  17180. {"g.", "/b/c/g."},
  17181. {".g", "/b/c/.g"},
  17182. {"g..", "/b/c/g.."},
  17183. {"..g", "/b/c/..g"},
  17184. {"./../g", "/b/g"},
  17185. {"./g/.", "/b/c/g/"},
  17186. {"g/./h", "/b/c/g/h"},
  17187. {"g/../h", "/b/c/h"},
  17188. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17189. {"g;x=1/../y", "/b/c/y"},
  17190. {"g?y/./x", "/b/c/g?y/./x"},
  17191. {"g#s/../x", "/b/c/g#s/../x"},
  17192. // Not relative-path references, so left for parse_url.
  17193. {"/g", "/g"},
  17194. {"//g", "//g"},
  17195. {"http://g/x", "http://g/x"},
  17196. {"g:h", "g:h"},
  17197. };
  17198. for (const auto &c : cases) {
  17199. EXPECT_EQ(c.second,
  17200. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17201. << c.first;
  17202. }
  17203. }
  17204. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17205. Server svr;
  17206. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17207. res.set_redirect(req.get_param_value("to"));
  17208. });
  17209. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17210. res.set_content(req.target, "text/plain");
  17211. });
  17212. svr.Get("/other", [](const Request &req, Response &res) {
  17213. res.set_content(req.target, "text/plain");
  17214. });
  17215. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17216. auto se = detail::scope_exit([&] {
  17217. svr.stop();
  17218. thread.join();
  17219. ASSERT_FALSE(svr.is_running());
  17220. });
  17221. svr.wait_until_ready();
  17222. const std::vector<std::pair<std::string, std::string>> cases = {
  17223. {"next", "/dir/next"},
  17224. {"./next?x=1", "/dir/next?x=1"},
  17225. {"../other", "/other"},
  17226. };
  17227. for (const auto &c : cases) {
  17228. Client cli(HOST, PORT);
  17229. cli.set_follow_location(true);
  17230. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17231. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17232. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17233. EXPECT_EQ(c.second, res->body) << c.first;
  17234. }
  17235. }
  17236. #ifdef CPPHTTPLIB_SSL_ENABLED
  17237. TEST(RedirectTest, Issue2185_Online) {
  17238. SSLClient client("github.com");
  17239. client.set_follow_location(true);
  17240. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17241. "Coollab-Windows.zip");
  17242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17243. EXPECT_EQ(StatusCode::OK_200, res->status);
  17244. EXPECT_EQ(9920427U, res->body.size());
  17245. }
  17246. #endif
  17247. TEST(VulnerabilityTest, CRLFInjection) {
  17248. Server svr;
  17249. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17250. res.set_content("Hello 1", "text/plain");
  17251. });
  17252. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17253. res.set_content("Hello 2", "text/plain");
  17254. });
  17255. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17256. res.set_content("Hello 3", "text/plain");
  17257. });
  17258. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17259. res.set_content("Hello 4", "text/plain");
  17260. });
  17261. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17262. for (const auto &x : req.headers) {
  17263. auto key = x.first;
  17264. EXPECT_STRNE("evil", key.c_str());
  17265. }
  17266. });
  17267. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17268. auto se = detail::scope_exit([&] {
  17269. svr.stop();
  17270. thread.join();
  17271. ASSERT_FALSE(svr.is_running());
  17272. });
  17273. svr.wait_until_ready();
  17274. {
  17275. Client cli(HOST, PORT);
  17276. cli.Post("/test1", "A=B",
  17277. "application/x-www-form-urlencoded\r\nevil: hello1");
  17278. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17279. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17280. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17281. }
  17282. }
  17283. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17284. auto server_thread = std::thread([] {
  17285. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17286. default_socket_options(srv);
  17287. sockaddr_in addr{};
  17288. addr.sin_family = AF_INET;
  17289. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17290. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17291. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17292. ::listen(srv, 1);
  17293. sockaddr_in cli_addr{};
  17294. socklen_t cli_len = sizeof(cli_addr);
  17295. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17296. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17297. std::string buf_all;
  17298. char buf[2048];
  17299. ssize_t n;
  17300. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17301. buf_all.append(buf, static_cast<size_t>(n));
  17302. size_t pos;
  17303. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17304. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17305. auto e = request_block.find("\r\n");
  17306. if (e != std::string::npos) {
  17307. auto request_line = request_block.substr(0, e);
  17308. std::string msg =
  17309. "CRLF injection detected in request line: '" + request_line + "'";
  17310. EXPECT_FALSE(true) << msg;
  17311. }
  17312. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17313. ::send(cli,
  17314. #ifdef _WIN32
  17315. static_cast<const char *>(resp.c_str()),
  17316. static_cast<int>(resp.size()),
  17317. #else
  17318. resp.c_str(), resp.size(),
  17319. #endif
  17320. 0);
  17321. buf_all.erase(0, pos + 4);
  17322. }
  17323. }
  17324. detail::close_socket(cli);
  17325. detail::close_socket(srv);
  17326. });
  17327. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17328. auto cli = Client("127.0.0.1", PORT + 1);
  17329. auto headers = Headers{
  17330. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17331. {"Connection", "keep-alive"}};
  17332. auto res = cli.Get("/hi", headers);
  17333. EXPECT_FALSE(res);
  17334. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17335. server_thread.join();
  17336. }
  17337. // A request rejected before any byte reaches the socket must fail right away
  17338. // instead of waiting for a response the server will never send.
  17339. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17340. // The kernel completes the TCP handshake from the listen backlog, so the
  17341. // client connects, but nothing ever reads, responds or closes.
  17342. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17343. default_socket_options(srv);
  17344. sockaddr_in addr{};
  17345. addr.sin_family = AF_INET;
  17346. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17347. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17348. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17349. ASSERT_EQ(0, ::listen(srv, 8));
  17350. auto cli = Client("127.0.0.1", PORT + 1);
  17351. cli.set_read_timeout(10, 0);
  17352. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17353. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17354. std::chrono::steady_clock::now() - start)
  17355. .count();
  17356. };
  17357. {
  17358. Request req;
  17359. req.method = "GE T";
  17360. req.path = "/";
  17361. auto start = std::chrono::steady_clock::now();
  17362. auto res = cli.send(req);
  17363. EXPECT_FALSE(res);
  17364. EXPECT_EQ(Error::Write, res.error());
  17365. EXPECT_LT(elapsed_ms(start), 1000);
  17366. }
  17367. {
  17368. auto start = std::chrono::steady_clock::now();
  17369. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17370. EXPECT_FALSE(res);
  17371. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17372. EXPECT_LT(elapsed_ms(start), 1000);
  17373. }
  17374. EXPECT_FALSE(cli.is_socket_open());
  17375. detail::close_socket(srv);
  17376. }
  17377. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17378. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17379. default_socket_options(srv);
  17380. sockaddr_in addr{};
  17381. addr.sin_family = AF_INET;
  17382. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17383. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17384. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17385. ASSERT_EQ(0, ::listen(srv, 1));
  17386. std::string received;
  17387. auto server_thread = std::thread([&] {
  17388. auto sock = ::accept(srv, nullptr, nullptr);
  17389. if (sock == INVALID_SOCKET) { return; }
  17390. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17391. char buf[2048];
  17392. ssize_t n;
  17393. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17394. received.append(buf, static_cast<size_t>(n));
  17395. }
  17396. detail::close_socket(sock);
  17397. });
  17398. {
  17399. auto cli = Client("127.0.0.1", PORT + 1);
  17400. // "Z" sorts after the default headers, so writing straight to the socket
  17401. // would have sent the request line and those headers before the rejection.
  17402. auto handle =
  17403. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17404. EXPECT_FALSE(handle.is_valid());
  17405. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17406. }
  17407. server_thread.join();
  17408. detail::close_socket(srv);
  17409. EXPECT_TRUE(received.empty()) << received;
  17410. }
  17411. TEST(PathParamsTest, StaticMatch) {
  17412. const auto pattern = "/users/all";
  17413. detail::PathParamsMatcher matcher(pattern);
  17414. Request request;
  17415. request.path = "/users/all";
  17416. ASSERT_TRUE(matcher.match(request));
  17417. std::unordered_map<std::string, std::string> expected_params = {};
  17418. EXPECT_EQ(request.path_params, expected_params);
  17419. }
  17420. TEST(PathParamsTest, StaticMismatch) {
  17421. const auto pattern = "/users/all";
  17422. detail::PathParamsMatcher matcher(pattern);
  17423. Request request;
  17424. request.path = "/users/1";
  17425. ASSERT_FALSE(matcher.match(request));
  17426. }
  17427. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17428. const auto pattern = "/users/:id/subscriptions";
  17429. detail::PathParamsMatcher matcher(pattern);
  17430. Request request;
  17431. request.path = "/users/42/subscriptions";
  17432. ASSERT_TRUE(matcher.match(request));
  17433. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17434. EXPECT_EQ(request.path_params, expected_params);
  17435. }
  17436. TEST(PathParamsTest, SingleParamInTheEnd) {
  17437. const auto pattern = "/users/:id";
  17438. detail::PathParamsMatcher matcher(pattern);
  17439. Request request;
  17440. request.path = "/users/24";
  17441. ASSERT_TRUE(matcher.match(request));
  17442. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17443. EXPECT_EQ(request.path_params, expected_params);
  17444. }
  17445. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17446. const auto pattern = "/users/:id/";
  17447. detail::PathParamsMatcher matcher(pattern);
  17448. Request request;
  17449. request.path = "/users/42/";
  17450. ASSERT_TRUE(matcher.match(request));
  17451. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17452. EXPECT_EQ(request.path_params, expected_params);
  17453. }
  17454. TEST(PathParamsTest, EmptyParam) {
  17455. const auto pattern = "/users/:id/";
  17456. detail::PathParamsMatcher matcher(pattern);
  17457. Request request;
  17458. request.path = "/users//";
  17459. ASSERT_TRUE(matcher.match(request));
  17460. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17461. EXPECT_EQ(request.path_params, expected_params);
  17462. }
  17463. TEST(PathParamsTest, FragmentMismatch) {
  17464. const auto pattern = "/users/:id/";
  17465. detail::PathParamsMatcher matcher(pattern);
  17466. Request request;
  17467. request.path = "/admins/24/";
  17468. ASSERT_FALSE(matcher.match(request));
  17469. }
  17470. TEST(PathParamsTest, ExtraFragments) {
  17471. const auto pattern = "/users/:id";
  17472. detail::PathParamsMatcher matcher(pattern);
  17473. Request request;
  17474. request.path = "/users/42/subscriptions";
  17475. ASSERT_FALSE(matcher.match(request));
  17476. }
  17477. TEST(PathParamsTest, MissingTrailingParam) {
  17478. const auto pattern = "/users/:id";
  17479. detail::PathParamsMatcher matcher(pattern);
  17480. Request request;
  17481. request.path = "/users";
  17482. ASSERT_FALSE(matcher.match(request));
  17483. }
  17484. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17485. const auto pattern = "/users/:id/subscriptions";
  17486. detail::PathParamsMatcher matcher(pattern);
  17487. Request request;
  17488. request.path = "/users/subscriptions";
  17489. ASSERT_FALSE(matcher.match(request));
  17490. }
  17491. TEST(PathParamsTest, MultipleParams) {
  17492. const auto pattern = "/users/:userid/subscriptions/:subid";
  17493. detail::PathParamsMatcher matcher(pattern);
  17494. Request request;
  17495. request.path = "/users/42/subscriptions/2";
  17496. ASSERT_TRUE(matcher.match(request));
  17497. std::unordered_map<std::string, std::string> expected_params = {
  17498. {"userid", "42"}, {"subid", "2"}};
  17499. EXPECT_EQ(request.path_params, expected_params);
  17500. }
  17501. TEST(PathParamsTest, SequenceOfParams) {
  17502. const auto pattern = "/values/:x/:y/:z";
  17503. detail::PathParamsMatcher matcher(pattern);
  17504. Request request;
  17505. request.path = "/values/1/2/3";
  17506. ASSERT_TRUE(matcher.match(request));
  17507. std::unordered_map<std::string, std::string> expected_params = {
  17508. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17509. EXPECT_EQ(request.path_params, expected_params);
  17510. }
  17511. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17512. const auto pattern = "/prefix:suffix";
  17513. detail::PathParamsMatcher matcher(pattern);
  17514. Request request;
  17515. request.path = "/prefix:suffix";
  17516. ASSERT_TRUE(matcher.match(request));
  17517. const std::unordered_map<std::string, std::string> expected_params = {};
  17518. EXPECT_EQ(request.path_params, expected_params);
  17519. }
  17520. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17521. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17522. // calling thread's stack on a long enough path for a quantified pattern;
  17523. // RegexMatcher must refuse to run regex matching on paths beyond
  17524. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17525. detail::RegexMatcher matcher("/files/(.*)");
  17526. Request within_limit;
  17527. within_limit.path = "/files/" + std::string(10, 'A');
  17528. EXPECT_TRUE(matcher.match(within_limit));
  17529. Request over_limit;
  17530. over_limit.path =
  17531. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17532. EXPECT_FALSE(matcher.match(over_limit));
  17533. }
  17534. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17535. Server svr;
  17536. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17537. res.set_content("ok", "text/plain");
  17538. });
  17539. auto port = svr.bind_to_any_port(HOST);
  17540. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17541. auto se = detail::scope_exit([&] {
  17542. svr.stop();
  17543. thread.join();
  17544. ASSERT_FALSE(svr.is_running());
  17545. });
  17546. svr.wait_until_ready();
  17547. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17548. // request URI limit; this used to be able to crash the process.
  17549. std::string path =
  17550. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17551. std::string req = "GET " + path +
  17552. " HTTP/1.1\r\n"
  17553. "Host: " +
  17554. std::string(HOST) + ":" + std::to_string(port) +
  17555. "\r\n"
  17556. "Connection: close\r\n"
  17557. "\r\n";
  17558. std::string response;
  17559. ASSERT_TRUE(send_request(5, req, &response, port));
  17560. EXPECT_NE(std::string::npos, response.find("404"));
  17561. }
  17562. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17563. Server svr;
  17564. auto handler = [](const Request & /*req*/, Response &res) {
  17565. res.set_content("hit", "text/plain");
  17566. };
  17567. // No regex metacharacter, so this one is compared literally
  17568. svr.Get("/literal/route", handler);
  17569. // '.' is a regex metacharacter, so this one must keep regex semantics
  17570. svr.Get("/a.c", handler);
  17571. auto port = svr.bind_to_any_port(HOST);
  17572. std::thread t([&]() { svr.listen_after_bind(); });
  17573. auto se = detail::scope_exit([&] {
  17574. svr.stop();
  17575. t.join();
  17576. ASSERT_FALSE(svr.is_running());
  17577. });
  17578. svr.wait_until_ready();
  17579. Client cli(HOST, port);
  17580. struct {
  17581. const char *path;
  17582. int status;
  17583. } cases[] = {
  17584. {"/literal/route", StatusCode::OK_200},
  17585. {"/literal/routes", StatusCode::NotFound_404},
  17586. {"/literal/rout", StatusCode::NotFound_404},
  17587. {"/abc", StatusCode::OK_200},
  17588. {"/a.c", StatusCode::OK_200},
  17589. };
  17590. for (const auto &x : cases) {
  17591. auto res = cli.Get(x.path);
  17592. ASSERT_TRUE(res) << x.path;
  17593. EXPECT_EQ(x.status, res->status) << x.path;
  17594. }
  17595. }
  17596. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17597. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17598. // from exhausting the stack, so it must only constrain routes that actually
  17599. // run a regular expression. A literal route is matched by comparison and
  17600. // stays usable at any length.
  17601. Server svr;
  17602. const std::string pattern =
  17603. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17604. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17605. res.set_content("hit", "text/plain");
  17606. });
  17607. auto port = svr.bind_to_any_port(HOST);
  17608. std::thread t([&]() { svr.listen_after_bind(); });
  17609. auto se = detail::scope_exit([&] {
  17610. svr.stop();
  17611. t.join();
  17612. ASSERT_FALSE(svr.is_running());
  17613. });
  17614. svr.wait_until_ready();
  17615. Client cli(HOST, port);
  17616. auto res = cli.Get(pattern);
  17617. ASSERT_TRUE(res);
  17618. EXPECT_EQ(StatusCode::OK_200, res->status);
  17619. }
  17620. TEST(ParseUrlTest, VariousPatterns) {
  17621. {
  17622. detail::UrlComponents uc;
  17623. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17624. EXPECT_EQ("http", uc.scheme);
  17625. EXPECT_EQ("example.com", uc.host);
  17626. EXPECT_EQ("8080", uc.port);
  17627. EXPECT_EQ("/path", uc.path);
  17628. EXPECT_EQ("?q=1", uc.query);
  17629. }
  17630. {
  17631. detail::UrlComponents uc;
  17632. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17633. EXPECT_EQ("https", uc.scheme);
  17634. EXPECT_EQ("example.com", uc.host);
  17635. EXPECT_TRUE(uc.port.empty());
  17636. EXPECT_EQ("/path", uc.path);
  17637. }
  17638. {
  17639. detail::UrlComponents uc;
  17640. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17641. EXPECT_EQ("::1", uc.host);
  17642. EXPECT_EQ("8080", uc.port);
  17643. EXPECT_EQ("/path", uc.path);
  17644. }
  17645. {
  17646. detail::UrlComponents uc;
  17647. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17648. }
  17649. {
  17650. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17651. // the path while the connection still targets the bracketed host.
  17652. detail::UrlComponents uc;
  17653. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17654. }
  17655. {
  17656. detail::UrlComponents uc;
  17657. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17658. }
  17659. {
  17660. detail::UrlComponents uc;
  17661. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17662. EXPECT_EQ("::1", uc.host);
  17663. EXPECT_TRUE(uc.port.empty());
  17664. EXPECT_EQ("/path", uc.path);
  17665. }
  17666. {
  17667. detail::UrlComponents uc;
  17668. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17669. EXPECT_TRUE(uc.scheme.empty());
  17670. EXPECT_EQ("example.com", uc.host);
  17671. EXPECT_EQ("/path", uc.path);
  17672. EXPECT_EQ("?q=1", uc.query);
  17673. }
  17674. {
  17675. detail::UrlComponents uc;
  17676. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17677. EXPECT_TRUE(uc.host.empty());
  17678. EXPECT_EQ("/path", uc.path);
  17679. EXPECT_EQ("?q=1", uc.query);
  17680. }
  17681. {
  17682. detail::UrlComponents uc;
  17683. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17684. EXPECT_EQ("example.com", uc.host);
  17685. EXPECT_EQ("8080", uc.port);
  17686. }
  17687. {
  17688. // Unix socket path — must not be parsed as host
  17689. detail::UrlComponents uc;
  17690. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17691. EXPECT_TRUE(uc.host.empty());
  17692. }
  17693. {
  17694. detail::UrlComponents uc;
  17695. ASSERT_TRUE(detail::parse_url("", uc));
  17696. EXPECT_TRUE(uc.host.empty());
  17697. EXPECT_TRUE(uc.path.empty());
  17698. }
  17699. {
  17700. detail::UrlComponents uc;
  17701. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17702. }
  17703. {
  17704. detail::UrlComponents uc;
  17705. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17706. }
  17707. {
  17708. // Accepted by parse_url; callers restrict to http/https
  17709. detail::UrlComponents uc;
  17710. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17711. EXPECT_EQ("ftp", uc.scheme);
  17712. }
  17713. {
  17714. detail::UrlComponents uc;
  17715. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17716. }
  17717. {
  17718. detail::UrlComponents uc;
  17719. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17720. }
  17721. }
  17722. TEST(ParseUrlTest, FragmentHandling) {
  17723. {
  17724. detail::UrlComponents uc;
  17725. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17726. EXPECT_EQ("/path", uc.path);
  17727. EXPECT_TRUE(uc.query.empty());
  17728. }
  17729. {
  17730. detail::UrlComponents uc;
  17731. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17732. EXPECT_TRUE(uc.path.empty());
  17733. EXPECT_TRUE(uc.query.empty());
  17734. }
  17735. }
  17736. TEST(ParseUrlTest, UserinfoHandling) {
  17737. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17738. // parsers would see evil.com as the host.
  17739. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17740. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17741. for (auto url : urls) {
  17742. detail::UrlComponents uc;
  17743. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17744. }
  17745. }
  17746. TEST(ParseUrlTest, IPv6EdgeCases) {
  17747. {
  17748. detail::UrlComponents uc;
  17749. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17750. EXPECT_TRUE(uc.scheme.empty());
  17751. EXPECT_EQ("::1", uc.host);
  17752. EXPECT_EQ("8080", uc.port);
  17753. }
  17754. {
  17755. // Zone ID '%25' is not in [a-fA-F0-9:]
  17756. detail::UrlComponents uc;
  17757. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17758. }
  17759. }
  17760. TEST(ParseUrlTest, SchemeEdgeCases) {
  17761. {
  17762. detail::UrlComponents uc;
  17763. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17764. }
  17765. {
  17766. detail::UrlComponents uc;
  17767. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17768. }
  17769. {
  17770. detail::UrlComponents uc;
  17771. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17772. }
  17773. }
  17774. TEST(ParseUrlTest, PortEdgeCases) {
  17775. {
  17776. detail::UrlComponents uc;
  17777. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17778. EXPECT_TRUE(uc.port.empty());
  17779. EXPECT_EQ("/path", uc.path);
  17780. }
  17781. {
  17782. // parse_url accepts any port string; validation is done by parse_port
  17783. detail::UrlComponents uc;
  17784. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17785. EXPECT_EQ("abc", uc.port);
  17786. }
  17787. }
  17788. TEST(ParseUrlTest, WebSocketPatterns) {
  17789. {
  17790. detail::UrlComponents uc;
  17791. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17792. EXPECT_EQ("ws", uc.scheme);
  17793. EXPECT_EQ("echo.example.com", uc.host);
  17794. EXPECT_EQ("8080", uc.port);
  17795. EXPECT_EQ("/ws", uc.path);
  17796. }
  17797. {
  17798. detail::UrlComponents uc;
  17799. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17800. EXPECT_EQ("wss", uc.scheme);
  17801. EXPECT_EQ("echo.example.com", uc.host);
  17802. EXPECT_TRUE(uc.port.empty());
  17803. EXPECT_EQ("/ws", uc.path);
  17804. }
  17805. }
  17806. TEST(ParseUrlTest, QueryOnly) {
  17807. detail::UrlComponents uc;
  17808. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17809. EXPECT_TRUE(uc.host.empty());
  17810. EXPECT_TRUE(uc.path.empty());
  17811. EXPECT_EQ("?q=1&r=2", uc.query);
  17812. }
  17813. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17814. detail::UrlComponents uc;
  17815. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17816. EXPECT_TRUE(uc.scheme.empty());
  17817. EXPECT_EQ("example.com", uc.host);
  17818. EXPECT_EQ("443", uc.port);
  17819. EXPECT_EQ("/path", uc.path);
  17820. }
  17821. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17822. // If ipv6 regex working, regex match codepath is taken.
  17823. // else port will default to 80 in Client impl
  17824. int clientImplMagicPort = 80;
  17825. int port = 4321;
  17826. // above ports must be different to avoid false negative
  17827. EXPECT_NE(clientImplMagicPort, port);
  17828. std::string ipV6TestURL = "http://[ff06::c3]";
  17829. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17830. CLIENT_PRIVATE_KEY_FILE);
  17831. EXPECT_EQ(cli.port(), port);
  17832. }
  17833. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17834. auto file_path = "./www/dir/index.html";
  17835. auto dir_path = "./www/dir";
  17836. detail::FileStat stat_file(file_path);
  17837. EXPECT_TRUE(stat_file.is_file());
  17838. EXPECT_FALSE(stat_file.is_dir());
  17839. detail::FileStat stat_dir(dir_path);
  17840. EXPECT_FALSE(stat_dir.is_file());
  17841. EXPECT_TRUE(stat_dir.is_dir());
  17842. }
  17843. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17844. // IPv4 with default HTTP port (80)
  17845. EXPECT_EQ("example.com",
  17846. detail::make_host_and_port_string("example.com", 80, false));
  17847. // IPv4 with default HTTPS port (443)
  17848. EXPECT_EQ("example.com",
  17849. detail::make_host_and_port_string("example.com", 443, true));
  17850. // IPv4 with non-default HTTP port
  17851. EXPECT_EQ("example.com:8080",
  17852. detail::make_host_and_port_string("example.com", 8080, false));
  17853. // IPv4 with non-default HTTPS port
  17854. EXPECT_EQ("example.com:8443",
  17855. detail::make_host_and_port_string("example.com", 8443, true));
  17856. // IPv6 with default HTTP port (80)
  17857. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17858. // IPv6 with default HTTPS port (443)
  17859. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17860. // IPv6 with non-default HTTP port
  17861. EXPECT_EQ("[::1]:8080",
  17862. detail::make_host_and_port_string("::1", 8080, false));
  17863. // IPv6 with non-default HTTPS port
  17864. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17865. // IPv6 full address with default port
  17866. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17867. detail::make_host_and_port_string(
  17868. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17869. // IPv6 full address with non-default port
  17870. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17871. detail::make_host_and_port_string(
  17872. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17873. // IPv6 localhost with non-default port
  17874. EXPECT_EQ("[::1]:3000",
  17875. detail::make_host_and_port_string("::1", 3000, false));
  17876. // IPv6 with zone ID (link-local address) with default port
  17877. EXPECT_EQ("[fe80::1%eth0]",
  17878. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17879. // IPv6 with zone ID (link-local address) with non-default port
  17880. EXPECT_EQ("[fe80::1%eth0]:8080",
  17881. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17882. // Edge case: Port 443 with is_ssl=false (should add port)
  17883. EXPECT_EQ("example.com:443",
  17884. detail::make_host_and_port_string("example.com", 443, false));
  17885. // Edge case: Port 80 with is_ssl=true (should add port)
  17886. EXPECT_EQ("example.com:80",
  17887. detail::make_host_and_port_string("example.com", 80, true));
  17888. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17889. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17890. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17891. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17892. // Security fix: Already bracketed IPv6 should not get double brackets
  17893. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17894. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17895. EXPECT_EQ("[::1]:8080",
  17896. detail::make_host_and_port_string("[::1]", 8080, false));
  17897. EXPECT_EQ("[2001:db8::1]:8080",
  17898. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17899. EXPECT_EQ("[fe80::1%eth0]",
  17900. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17901. EXPECT_EQ("[fe80::1%eth0]:8080",
  17902. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17903. // Edge case: Empty host (should return as-is)
  17904. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17905. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17906. // This is a known limitation but shouldn't crash
  17907. EXPECT_EQ("[host:name]",
  17908. detail::make_host_and_port_string("host:name", 80, false));
  17909. // Port number edge cases (no validation, but should not crash)
  17910. EXPECT_EQ("example.com:0",
  17911. detail::make_host_and_port_string("example.com", 0, false));
  17912. EXPECT_EQ("example.com:-1",
  17913. detail::make_host_and_port_string("example.com", -1, false));
  17914. EXPECT_EQ("example.com:65535",
  17915. detail::make_host_and_port_string("example.com", 65535, false));
  17916. EXPECT_EQ("example.com:65536",
  17917. detail::make_host_and_port_string("example.com", 65536, false));
  17918. }
  17919. #ifdef CPPHTTPLIB_SSL_ENABLED
  17920. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17921. httplib::SSLClient cli("roblox.com", 443);
  17922. cli.set_follow_location(true);
  17923. auto res = cli.Get("/");
  17924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17925. EXPECT_EQ(StatusCode::OK_200, res->status);
  17926. }
  17927. #endif
  17928. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17929. Server svr;
  17930. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17931. EXPECT_EQ(res.status, 400);
  17932. });
  17933. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17934. auto se = detail::scope_exit([&] {
  17935. svr.stop();
  17936. thread.join();
  17937. ASSERT_FALSE(svr.is_running());
  17938. });
  17939. svr.wait_until_ready();
  17940. Client cli(HOST, PORT);
  17941. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17942. }
  17943. TEST(InvalidHeaderCharsTest, is_field_name) {
  17944. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17945. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17946. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17947. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17948. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17949. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17950. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17951. EXPECT_FALSE(detail::fields::is_field_name(""));
  17952. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17953. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17954. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17955. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17956. }
  17957. TEST(InvalidHeaderCharsTest, is_field_value) {
  17958. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17959. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17960. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17961. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17962. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17963. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17964. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17965. EXPECT_TRUE(detail::fields::is_field_value(""));
  17966. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17967. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17968. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17969. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17970. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17971. }
  17972. TEST(InvalidHeaderCharsTest, OnServer) {
  17973. Server svr;
  17974. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17975. std::string header = "Not Set";
  17976. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17977. res.set_header(header, "value");
  17978. res.set_content("Page Content Page Content", "text/plain");
  17979. });
  17980. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17981. std::string header = "Not Set";
  17982. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17983. res.set_header("X-Test", header);
  17984. res.set_content("Page Content Page Content", "text/plain");
  17985. });
  17986. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17987. auto se = detail::scope_exit([&] {
  17988. svr.stop();
  17989. thread.join();
  17990. ASSERT_FALSE(svr.is_running());
  17991. });
  17992. svr.wait_until_ready();
  17993. Client cli(HOST, PORT);
  17994. {
  17995. auto res = cli.Get(
  17996. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17998. EXPECT_EQ("Page Content Page Content", res->body);
  17999. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18000. }
  18001. {
  18002. auto res = cli.Get(
  18003. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18005. EXPECT_EQ("Page Content Page Content", res->body);
  18006. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18007. }
  18008. }
  18009. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18010. auto handled = false;
  18011. Server svr;
  18012. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18013. thread t = thread([&] { svr.listen(HOST, PORT); });
  18014. auto se = detail::scope_exit([&] {
  18015. svr.stop();
  18016. t.join();
  18017. ASSERT_FALSE(svr.is_running());
  18018. ASSERT_FALSE(handled);
  18019. });
  18020. svr.wait_until_ready();
  18021. auto req = "POST /test HTTP/1.1\r\n"
  18022. "Content-Length: x\r\n"
  18023. "\r\n";
  18024. std::string response;
  18025. ASSERT_TRUE(send_request(1, req, &response));
  18026. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18027. response.substr(0, response.find("\r\n")));
  18028. }
  18029. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18030. // case-insensitive, and a server that receives a 100-continue expectation in
  18031. // an HTTP/1.0 request MUST ignore it.
  18032. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18033. std::string response;
  18034. ASSERT_TRUE(send_request(1, req, &response, port));
  18035. *got_100 = response.find("100 Continue") != std::string::npos;
  18036. }
  18037. class ExpectTokenTest : public ::testing::Test {
  18038. protected:
  18039. void SetUp() override {
  18040. svr_.Post("/p", [](const Request &, Response &res) {
  18041. res.set_content("ok", "text/plain");
  18042. });
  18043. port_ = svr_.bind_to_any_port(HOST);
  18044. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18045. svr_.wait_until_ready();
  18046. }
  18047. void TearDown() override {
  18048. svr_.stop();
  18049. if (thread_.joinable()) { thread_.join(); }
  18050. }
  18051. std::string request(const char *version, const char *expect_value) const {
  18052. return std::string("POST /p ") + version +
  18053. "\r\n"
  18054. "Host: localhost\r\n"
  18055. "Content-Length: 2\r\n"
  18056. "Connection: close\r\n"
  18057. "Expect: " +
  18058. expect_value +
  18059. "\r\n"
  18060. "\r\n"
  18061. "hi";
  18062. }
  18063. Server svr_;
  18064. int port_ = 0;
  18065. thread thread_;
  18066. };
  18067. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18068. bool got_100 = false;
  18069. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18070. EXPECT_TRUE(got_100);
  18071. }
  18072. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18073. bool got_100 = true;
  18074. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18075. EXPECT_FALSE(got_100);
  18076. }
  18077. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18078. bool got_100 = false;
  18079. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18080. EXPECT_TRUE(got_100);
  18081. }
  18082. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18083. bool got_100 = false;
  18084. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18085. EXPECT_TRUE(got_100);
  18086. }
  18087. // `100 Continue` is sent only when the server starts reading the body, so a
  18088. // request rejected before that never invites the client to send it. The
  18089. // requests below carry the expectation but withhold the body, as a client
  18090. // waiting for `100 Continue` would.
  18091. // A POST that expects `100 Continue` and withholds its two-byte body.
  18092. static std::string expect_headers_only(const std::string &path) {
  18093. return "POST " + path +
  18094. " HTTP/1.1\r\n"
  18095. "Host: localhost\r\n"
  18096. "Content-Length: 2\r\n"
  18097. "Expect: 100-continue\r\n"
  18098. "\r\n";
  18099. }
  18100. class ExpectLazyContinueTest : public ::testing::Test {
  18101. protected:
  18102. void SetUp() override {
  18103. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18104. if (req.path == "/pre-routing") {
  18105. res.status = StatusCode::Unauthorized_401;
  18106. return Server::HandlerResponse::Handled;
  18107. }
  18108. return Server::HandlerResponse::Unhandled;
  18109. });
  18110. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18111. if (req.matched_route == "/pre-request") {
  18112. res.status = StatusCode::Forbidden_403;
  18113. return Server::HandlerResponse::Handled;
  18114. }
  18115. return Server::HandlerResponse::Unhandled;
  18116. });
  18117. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18118. res.set_content("ok", "text/plain");
  18119. });
  18120. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18121. res.set_content("ok", "text/plain");
  18122. });
  18123. svr_.Post("/reader-used", [](const Request &, Response &res,
  18124. const ContentReader &content_reader) {
  18125. std::string body;
  18126. content_reader([&](const char *data, size_t len) {
  18127. body.append(data, len);
  18128. return true;
  18129. });
  18130. res.set_content(body, "text/plain");
  18131. });
  18132. svr_.Post("/reader-unused",
  18133. [](const Request &, Response &res, const ContentReader &) {
  18134. res.set_content("ignored", "text/plain");
  18135. });
  18136. port_ = svr_.bind_to_any_port(HOST);
  18137. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18138. svr_.wait_until_ready();
  18139. }
  18140. void TearDown() override {
  18141. svr_.stop();
  18142. if (thread_.joinable()) { thread_.join(); }
  18143. }
  18144. // Sends `req` and reads until the server closes the connection. Returns
  18145. // false if the read had to wait for the client-side timeout instead.
  18146. bool send_until_closed(const std::string &req, std::string *resp) const {
  18147. auto start = std::chrono::steady_clock::now();
  18148. if (!send_request(3, req, resp, port_)) { return false; }
  18149. auto elapsed = std::chrono::steady_clock::now() - start;
  18150. return elapsed < std::chrono::seconds(2);
  18151. }
  18152. // The final response comes without `100 Continue`, and the server closes
  18153. // the connection since the body may or may not follow.
  18154. void expect_final_without_interim(const std::string &path,
  18155. const char *status_line) const {
  18156. std::string resp;
  18157. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18158. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18159. EXPECT_EQ(0u, resp.find(status_line));
  18160. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18161. }
  18162. Server svr_;
  18163. int port_ = 0;
  18164. thread thread_;
  18165. };
  18166. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18167. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18168. }
  18169. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18170. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18171. }
  18172. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18173. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18174. }
  18175. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18176. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18177. }
  18178. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18179. // The body follows once `100 Continue` has had time to arrive.
  18180. auto req = expect_headers_only("/reader-used");
  18181. req.insert(req.size() - 2, "Connection: close\r\n");
  18182. std::string resp;
  18183. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18184. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18185. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18186. EXPECT_NE(std::string::npos, resp.find("hi"));
  18187. }
  18188. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18189. // Large enough for the client to add `Expect: 100-continue` itself.
  18190. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18191. std::atomic<bool> body_sent{false};
  18192. Client cli(HOST, port_);
  18193. auto res = cli.Post(
  18194. "/pre-request", length,
  18195. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18196. body_sent = true;
  18197. std::string chunk(len, 'x');
  18198. sink.write(chunk.data(), chunk.size());
  18199. return true;
  18200. },
  18201. "application/octet-stream");
  18202. ASSERT_TRUE(res);
  18203. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18204. EXPECT_FALSE(body_sent);
  18205. }
  18206. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18207. Server svr;
  18208. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18209. return StatusCode::ExpectationFailed_417;
  18210. });
  18211. svr.Post("/p", [](const Request &, Response &res) {
  18212. res.set_content("ok", "text/plain");
  18213. });
  18214. auto port = svr.bind_to_any_port(HOST);
  18215. thread t = thread([&] { svr.listen_after_bind(); });
  18216. auto se = detail::scope_exit([&] {
  18217. svr.stop();
  18218. t.join();
  18219. });
  18220. svr.wait_until_ready();
  18221. std::string resp;
  18222. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18223. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18224. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18225. // Exactly one response: the route handler must not run after the 417.
  18226. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18227. }
  18228. #ifndef _WIN32
  18229. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18230. static constexpr char reject[] = "Unauthorized";
  18231. static constexpr char accept[] = "Upload accepted";
  18232. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18233. Server svr;
  18234. svr.set_expect_100_continue_handler(
  18235. [](const Request & /*req*/, Response &res) {
  18236. res.status = StatusCode::Unauthorized_401;
  18237. res.set_content(reject, "text/plain");
  18238. return res.status;
  18239. });
  18240. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18241. res.set_content(accept, "text/plain");
  18242. });
  18243. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18244. auto se = detail::scope_exit([&] {
  18245. svr.stop();
  18246. thread.join();
  18247. ASSERT_FALSE(svr.is_running());
  18248. });
  18249. svr.wait_until_ready();
  18250. {
  18251. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18252. curl_easy_init(), &curl_easy_cleanup};
  18253. ASSERT_NE(curl, nullptr);
  18254. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18255. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18256. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18257. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18258. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18259. &curl_slist_free_all};
  18260. ASSERT_NE(list, nullptr);
  18261. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18262. struct read_data {
  18263. uint64_t read_size;
  18264. uint64_t total_size;
  18265. } data = {0, total_size};
  18266. using read_callback_t =
  18267. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18268. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18269. void *userdata) -> size_t {
  18270. read_data *d = (read_data *)userdata;
  18271. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18272. std::fill_n(ptr, size * nmemb, 'A');
  18273. d->read_size += size * nmemb;
  18274. return size * nmemb;
  18275. };
  18276. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18277. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18278. std::vector<char> buffer;
  18279. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18280. using write_callback_t =
  18281. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18282. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18283. void *userdata) -> size_t {
  18284. std::vector<char> *buf = (std::vector<char> *)userdata;
  18285. buf->reserve(buf->size() + size * nmemb + 1);
  18286. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18287. return size * nmemb;
  18288. };
  18289. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18290. {
  18291. const auto res = curl_easy_perform(curl.get());
  18292. ASSERT_EQ(res, CURLE_OK);
  18293. }
  18294. {
  18295. auto response_code = long{};
  18296. const auto res =
  18297. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18298. ASSERT_EQ(res, CURLE_OK);
  18299. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18300. }
  18301. {
  18302. auto dl = curl_off_t{};
  18303. const auto res =
  18304. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18305. ASSERT_EQ(res, CURLE_OK);
  18306. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18307. }
  18308. {
  18309. buffer.push_back('\0');
  18310. ASSERT_STRCASEEQ(buffer.data(), reject);
  18311. }
  18312. }
  18313. }
  18314. #endif
  18315. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18316. // Regression test for #2458.
  18317. //
  18318. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18319. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18320. // ticket can make the client socket spuriously readable during the
  18321. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18322. // the client withholds the body and then blocks reading a response that never
  18323. // comes, failing with `Failed to read connection`.
  18324. //
  18325. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18326. // within the timeout. This raw OpenSSL server deliberately never sends
  18327. // `100 Continue`; the client must still deliver the body and receive 200.
  18328. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18329. signal(SIGPIPE, SIG_IGN);
  18330. const auto port = PORT + 4;
  18331. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18332. ASSERT_NE(srv, INVALID_SOCKET);
  18333. int opt = 1;
  18334. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18335. sockaddr_in addr{};
  18336. addr.sin_family = AF_INET;
  18337. addr.sin_port = htons(static_cast<uint16_t>(port));
  18338. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18339. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18340. ASSERT_EQ(0, ::listen(srv, 1));
  18341. std::atomic<size_t> server_body_bytes{0};
  18342. auto server_thread = std::thread([&] {
  18343. sockaddr_in cli_addr{};
  18344. socklen_t cli_len = sizeof(cli_addr);
  18345. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18346. if (cli == INVALID_SOCKET) { return; }
  18347. // Bound the lifetime of the server side so a buggy client (which never
  18348. // sends the body) cannot make this thread block forever on join.
  18349. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18350. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18351. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18352. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18353. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18354. SSL *ssl = SSL_new(ctx);
  18355. SSL_set_fd(ssl, static_cast<int>(cli));
  18356. if (SSL_accept(ssl) > 0) {
  18357. // Read the request headers. Reading here also flushes the TLS 1.3
  18358. // session tickets to the client. Deliberately do NOT send
  18359. // `100 Continue`.
  18360. std::string buf;
  18361. char tmp[1024];
  18362. while (buf.find("\r\n\r\n") == std::string::npos) {
  18363. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18364. if (n <= 0) { break; }
  18365. buf.append(tmp, static_cast<size_t>(n));
  18366. }
  18367. // A correct client sends the body now; count what arrives.
  18368. auto pos = buf.find("\r\n\r\n");
  18369. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18370. while (body < 4096) {
  18371. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18372. if (n <= 0) { break; }
  18373. body += static_cast<size_t>(n);
  18374. }
  18375. server_body_bytes = body;
  18376. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18377. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18378. SSL_shutdown(ssl);
  18379. }
  18380. SSL_free(ssl);
  18381. detail::close_socket(cli);
  18382. SSL_CTX_free(ctx);
  18383. });
  18384. auto se = detail::scope_exit([&] {
  18385. server_thread.join();
  18386. detail::close_socket(srv);
  18387. });
  18388. SSLClient cli("127.0.0.1", port);
  18389. cli.enable_server_certificate_verification(false);
  18390. cli.set_connection_timeout(5, 0);
  18391. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18392. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18393. std::string body(4096, 'A');
  18394. auto res = cli.Put("/api/test", body, "application/json");
  18395. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18396. EXPECT_EQ(StatusCode::OK_200, res->status);
  18397. EXPECT_EQ(body.size(), server_body_bytes.load());
  18398. }
  18399. #endif
  18400. template <typename S, typename C>
  18401. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18402. svr.Get("/stream", [&](const Request &, Response &res) {
  18403. auto data = new std::string("01234567890123456789");
  18404. res.set_content_provider(
  18405. data->size(), "text/plain",
  18406. [&, data](size_t offset, size_t length, DataSink &sink) {
  18407. const size_t DATA_CHUNK_SIZE = 4;
  18408. const auto &d = *data;
  18409. std::this_thread::sleep_for(std::chrono::seconds(1));
  18410. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18411. return true;
  18412. },
  18413. [data](bool success) {
  18414. EXPECT_FALSE(success);
  18415. delete data;
  18416. });
  18417. });
  18418. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18419. auto i = new size_t(0);
  18420. res.set_content_provider(
  18421. "text/plain",
  18422. [i](size_t, DataSink &sink) {
  18423. if (*i < 5) {
  18424. std::this_thread::sleep_for(std::chrono::seconds(1));
  18425. sink.write("abcd", 4);
  18426. (*i)++;
  18427. } else {
  18428. sink.done();
  18429. }
  18430. return true;
  18431. },
  18432. [i](bool success) {
  18433. EXPECT_FALSE(success);
  18434. delete i;
  18435. });
  18436. });
  18437. svr.Get("/chunked", [&](const Request &, Response &res) {
  18438. auto i = new size_t(0);
  18439. res.set_chunked_content_provider(
  18440. "text/plain",
  18441. [i](size_t, DataSink &sink) {
  18442. if (*i < 5) {
  18443. std::this_thread::sleep_for(std::chrono::seconds(1));
  18444. sink.os << "abcd";
  18445. (*i)++;
  18446. } else {
  18447. sink.done();
  18448. }
  18449. return true;
  18450. },
  18451. [i](bool success) {
  18452. EXPECT_FALSE(success);
  18453. delete i;
  18454. });
  18455. });
  18456. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18457. auto se = detail::scope_exit([&] {
  18458. svr.stop();
  18459. listen_thread.join();
  18460. ASSERT_FALSE(svr.is_running());
  18461. });
  18462. svr.wait_until_ready();
  18463. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18464. {
  18465. auto start = std::chrono::steady_clock::now();
  18466. auto res = cli.Get("/stream");
  18467. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18468. std::chrono::steady_clock::now() - start)
  18469. .count();
  18470. ASSERT_FALSE(res);
  18471. EXPECT_EQ(Error::Read, res.error());
  18472. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18473. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18474. }
  18475. {
  18476. auto start = std::chrono::steady_clock::now();
  18477. auto res = cli.Get("/stream_without_length");
  18478. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18479. std::chrono::steady_clock::now() - start)
  18480. .count();
  18481. ASSERT_FALSE(res);
  18482. EXPECT_EQ(Error::Read, res.error());
  18483. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18484. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18485. }
  18486. {
  18487. auto start = std::chrono::steady_clock::now();
  18488. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18489. EXPECT_EQ("abcd", string(data, data_length));
  18490. return true;
  18491. });
  18492. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18493. std::chrono::steady_clock::now() - start)
  18494. .count();
  18495. ASSERT_FALSE(res);
  18496. EXPECT_EQ(Error::Read, res.error());
  18497. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18498. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18499. }
  18500. }
  18501. TEST(MaxTimeoutTest, ContentStream) {
  18502. time_t timeout = 2000;
  18503. time_t threshold = 200;
  18504. Server svr;
  18505. Client cli("localhost", PORT);
  18506. max_timeout_test(svr, cli, timeout, threshold);
  18507. }
  18508. #ifdef CPPHTTPLIB_SSL_ENABLED
  18509. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18510. time_t timeout = 2000;
  18511. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18513. SSLClient cli("localhost", PORT);
  18514. cli.enable_server_certificate_verification(false);
  18515. max_timeout_test(svr, cli, timeout, threshold);
  18516. }
  18517. #endif
  18518. class EventDispatcher {
  18519. public:
  18520. EventDispatcher() {}
  18521. bool wait_event(DataSink *sink) {
  18522. unique_lock<mutex> lk(m_);
  18523. int id = id_;
  18524. // Wait with timeout to prevent hanging if client disconnects
  18525. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18526. [&] { return cid_ == id; })) {
  18527. return false; // Timeout occurred
  18528. }
  18529. sink->write(message_.data(), message_.size());
  18530. return true;
  18531. }
  18532. void send_event(const string &message) {
  18533. lock_guard<mutex> lk(m_);
  18534. cid_ = id_++;
  18535. message_ = message;
  18536. cv_.notify_all();
  18537. }
  18538. private:
  18539. mutex m_;
  18540. condition_variable cv_;
  18541. atomic_int id_{0};
  18542. atomic_int cid_{-1};
  18543. string message_;
  18544. };
  18545. TEST(ClientInThreadTest, Issue2068) {
  18546. EventDispatcher ed;
  18547. Server svr;
  18548. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18549. res.set_chunked_content_provider("text/event-stream",
  18550. [&](size_t /*offset*/, DataSink &sink) {
  18551. return ed.wait_event(&sink);
  18552. });
  18553. });
  18554. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18555. svr.wait_until_ready();
  18556. thread event_thread([&] {
  18557. int id = 0;
  18558. while (svr.is_running()) {
  18559. this_thread::sleep_for(chrono::milliseconds(500));
  18560. std::stringstream ss;
  18561. ss << "data: " << id << "\n\n";
  18562. ed.send_event(ss.str());
  18563. id++;
  18564. }
  18565. });
  18566. auto se = detail::scope_exit([&] {
  18567. svr.stop();
  18568. listen_thread.join();
  18569. event_thread.join();
  18570. ASSERT_FALSE(svr.is_running());
  18571. });
  18572. {
  18573. auto client = detail::make_unique<Client>(HOST, PORT);
  18574. client->set_read_timeout(std::chrono::minutes(10));
  18575. std::atomic<bool> stop{false};
  18576. std::thread t([&] {
  18577. client->Get("/event1",
  18578. [&](const char *, size_t) -> bool { return !stop; });
  18579. });
  18580. std::this_thread::sleep_for(std::chrono::seconds(2));
  18581. stop = true;
  18582. client->stop();
  18583. t.join();
  18584. // Reset client after thread has finished
  18585. client.reset();
  18586. }
  18587. }
  18588. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18589. auto handled = false;
  18590. Server svr;
  18591. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18592. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18593. auto se = detail::scope_exit([&] {
  18594. svr.stop();
  18595. t.join();
  18596. ASSERT_FALSE(svr.is_running());
  18597. ASSERT_FALSE(handled);
  18598. });
  18599. svr.wait_until_ready();
  18600. // Two Content-Length headers with different values — must be rejected
  18601. auto req = "POST /test HTTP/1.1\r\n"
  18602. "Content-Length: 5\r\n"
  18603. "Content-Length: 10\r\n"
  18604. "\r\n"
  18605. "hello";
  18606. std::string response;
  18607. ASSERT_TRUE(send_request(1, req, &response));
  18608. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18609. response.substr(0, response.find("\r\n")));
  18610. }
  18611. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18612. auto handled = false;
  18613. Server svr;
  18614. svr.Post("/test", [&](const Request &, Response &res) {
  18615. handled = true;
  18616. res.set_content("ok", "text/plain");
  18617. });
  18618. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18619. auto se = detail::scope_exit([&] {
  18620. svr.stop();
  18621. t.join();
  18622. ASSERT_FALSE(svr.is_running());
  18623. ASSERT_TRUE(handled);
  18624. });
  18625. svr.wait_until_ready();
  18626. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18627. auto req = "POST /test HTTP/1.1\r\n"
  18628. "Host: localhost\r\n"
  18629. "Content-Length: 5\r\n"
  18630. "Content-Length: 5\r\n"
  18631. "\r\n"
  18632. "hello";
  18633. std::string response;
  18634. ASSERT_TRUE(send_request(1, req, &response));
  18635. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18636. }
  18637. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18638. Server svr;
  18639. svr.Get("/test", [](const Request &, Response &res) {
  18640. res.set_content("ok", "text/plain");
  18641. });
  18642. auto port = svr.bind_to_any_port(HOST);
  18643. thread t = thread([&] { svr.listen_after_bind(); });
  18644. auto se = detail::scope_exit([&] {
  18645. svr.stop();
  18646. t.join();
  18647. ASSERT_FALSE(svr.is_running());
  18648. });
  18649. svr.wait_until_ready();
  18650. auto status_line = [&](const std::string &host_lines) {
  18651. std::string res;
  18652. send_request(
  18653. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18654. &res, port);
  18655. return res.substr(0, res.find("\r\n"));
  18656. };
  18657. const char *accepted[] = {
  18658. "Host: localhost\r\n",
  18659. "Host: a.example:8080\r\n",
  18660. "Host: my_service\r\n",
  18661. "Host: [::1]:8080\r\n",
  18662. "Host: [fe80::1%25eth0]\r\n",
  18663. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18664. };
  18665. for (auto host_lines : accepted) {
  18666. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18667. }
  18668. const char *rejected[] = {
  18669. "Host: a.example\r\nHost: b.example\r\n",
  18670. "Host: a.example\r\nHost: a.example\r\n",
  18671. "Host: a@b.example\r\n",
  18672. "Host: a.example/b\r\n",
  18673. "Host: a.example\\b\r\n",
  18674. "Host: a.example?b\r\n",
  18675. "Host: a.example#b\r\n",
  18676. "Host: a.example b.example\r\n",
  18677. };
  18678. for (auto host_lines : rejected) {
  18679. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18680. << host_lines;
  18681. }
  18682. }
  18683. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18684. Server svr;
  18685. svr.Get("/", [](const Request &req, Response &res) {
  18686. EXPECT_EQ(2U, req.trailers.size());
  18687. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18688. // Denied
  18689. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18690. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18691. // Accepted
  18692. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18693. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18694. EXPECT_TRUE(req.has_trailer("X-World"));
  18695. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18696. res.set_content("ok", "text/plain");
  18697. });
  18698. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18699. auto se = detail::scope_exit([&] {
  18700. svr.stop();
  18701. t.join();
  18702. ASSERT_FALSE(svr.is_running());
  18703. });
  18704. svr.wait_until_ready();
  18705. const std::string req = "GET / HTTP/1.1\r\n"
  18706. "Transfer-Encoding: chunked\r\n"
  18707. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18708. "\r\n"
  18709. "0\r\n"
  18710. "Content-Length: 10\r\n"
  18711. "Host: internal.local\r\n"
  18712. "Content-Type: malicious/content\r\n"
  18713. "Cookie: any\r\n"
  18714. "Set-Cookie: any\r\n"
  18715. "X-Forwarded-For: attacker.com\r\n"
  18716. "X-Real-Ip: 1.1.1.1\r\n"
  18717. "X-Hello: hello\r\n"
  18718. "X-World: world\r\n"
  18719. "\r\n";
  18720. std::string res;
  18721. ASSERT_TRUE(send_request(1, req, &res));
  18722. }
  18723. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18724. // several field lines, and the combined value is what has to be parsed. A
  18725. // Trailer field split across lines therefore declares every name it lists;
  18726. // reading only the first line silently drops the trailers the later lines
  18727. // declare. The prohibited-trailer filter still applies to every line.
  18728. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18729. Server svr;
  18730. size_t observed_trailer_count = 0;
  18731. std::string observed_hello;
  18732. std::string observed_world;
  18733. bool observed_content_length = true;
  18734. svr.Get("/", [&](const Request &req, Response &res) {
  18735. observed_trailer_count = req.trailers.size();
  18736. observed_hello = req.get_trailer_value("X-Hello");
  18737. observed_world = req.get_trailer_value("X-World");
  18738. observed_content_length = req.has_trailer("Content-Length");
  18739. res.set_content("ok", "text/plain");
  18740. });
  18741. auto port = svr.bind_to_any_port(HOST);
  18742. thread t = thread([&]() { svr.listen_after_bind(); });
  18743. auto se = detail::scope_exit([&] {
  18744. svr.stop();
  18745. t.join();
  18746. ASSERT_FALSE(svr.is_running());
  18747. });
  18748. svr.wait_until_ready();
  18749. const std::string req = "GET / HTTP/1.1\r\n"
  18750. "Host: localhost\r\n"
  18751. "Transfer-Encoding: chunked\r\n"
  18752. "Trailer: X-Hello\r\n"
  18753. "Trailer: X-World, Content-Length\r\n"
  18754. "\r\n"
  18755. "0\r\n"
  18756. "X-Hello: hello\r\n"
  18757. "X-World: world\r\n"
  18758. "Content-Length: 10\r\n"
  18759. "\r\n";
  18760. std::string res;
  18761. ASSERT_TRUE(send_request(1, req, &res, port));
  18762. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18763. // Accepted: both field lines contribute to the declared set
  18764. EXPECT_EQ(2U, observed_trailer_count);
  18765. EXPECT_EQ(observed_hello, "hello");
  18766. EXPECT_EQ(observed_world, "world");
  18767. // Denied: a prohibited name stays prohibited on a later field line
  18768. EXPECT_FALSE(observed_content_length);
  18769. }
  18770. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18771. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18772. // unbounded run of fields that are never declared, because the counter would
  18773. // only advance for declared fields.
  18774. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18775. Server svr;
  18776. bool handler_called = false;
  18777. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18778. handler_called = true;
  18779. res.set_content("ok", "text/plain");
  18780. });
  18781. auto port = svr.bind_to_any_port(HOST);
  18782. thread t = thread([&]() { svr.listen_after_bind(); });
  18783. auto se = detail::scope_exit([&] {
  18784. svr.stop();
  18785. t.join();
  18786. ASSERT_FALSE(svr.is_running());
  18787. });
  18788. svr.wait_until_ready();
  18789. // Declare nothing, then send far more undeclared trailer fields than the
  18790. // header-count limit. Parsing must stop and reject the request rather than
  18791. // read every line.
  18792. std::string req = "GET / HTTP/1.1\r\n"
  18793. "Transfer-Encoding: chunked\r\n"
  18794. "\r\n"
  18795. "0\r\n";
  18796. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18797. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18798. }
  18799. req += "\r\n";
  18800. std::string res;
  18801. ASSERT_TRUE(send_request(1, req, &res, port));
  18802. // The request is rejected before the handler runs.
  18803. EXPECT_FALSE(handler_called);
  18804. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18805. }
  18806. // The set of declared trailer names is capped so a peer cannot grow it without
  18807. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18808. // declared past the cap is not honored, even if the field is actually sent.
  18809. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18810. Server svr;
  18811. // One name inside the cap and one past it, so the test tracks the cap rather
  18812. // than a fixed count.
  18813. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18814. const std::string within_cap_name = "X-T-0";
  18815. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18816. bool observed_within_cap = false;
  18817. bool observed_past_cap = false;
  18818. svr.Get("/", [&](const Request &req, Response &res) {
  18819. observed_within_cap = req.has_trailer(within_cap_name);
  18820. observed_past_cap = req.has_trailer(past_cap_name);
  18821. res.set_content("ok", "text/plain");
  18822. });
  18823. auto port = svr.bind_to_any_port(HOST);
  18824. thread t = thread([&]() { svr.listen_after_bind(); });
  18825. auto se = detail::scope_exit([&] {
  18826. svr.stop();
  18827. t.join();
  18828. ASSERT_FALSE(svr.is_running());
  18829. });
  18830. svr.wait_until_ready();
  18831. // Declare more trailer names than the cap in a single Trailer field, then
  18832. // actually send the first (within the cap) and the last (past it).
  18833. std::string trailer_decl = "Trailer: ";
  18834. for (int i = 0; i < declared_count; i++) {
  18835. if (i != 0) { trailer_decl += ", "; }
  18836. trailer_decl += "X-T-" + std::to_string(i);
  18837. }
  18838. trailer_decl += "\r\n";
  18839. const std::string req = "GET / HTTP/1.1\r\n"
  18840. "Host: localhost\r\n"
  18841. "Transfer-Encoding: chunked\r\n" +
  18842. trailer_decl +
  18843. "\r\n"
  18844. "0\r\n" +
  18845. within_cap_name + ": a\r\n" + past_cap_name +
  18846. ": b\r\n"
  18847. "\r\n";
  18848. std::string res;
  18849. ASSERT_TRUE(send_request(1, req, &res, port));
  18850. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18851. // A name within the cap is honored; one declared past the cap is dropped.
  18852. EXPECT_TRUE(observed_within_cap);
  18853. EXPECT_FALSE(observed_past_cap);
  18854. }
  18855. // A direct client that is not listed in trusted_proxies must not be able to
  18856. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18857. // the peer address on the actual TCP connection determines whether the
  18858. // header is honored.
  18859. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18860. Server svr;
  18861. // Deliberately does NOT include the loopback address the test client
  18862. // actually connects from, so the direct connection is not a trusted proxy.
  18863. svr.set_trusted_proxies({"203.0.113.66"});
  18864. std::string observed_remote_addr;
  18865. svr.Get("/ip", [&](const Request &req, Response &res) {
  18866. observed_remote_addr = req.remote_addr;
  18867. res.set_content("ok", "text/plain");
  18868. });
  18869. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18870. auto se = detail::scope_exit([&] {
  18871. svr.stop();
  18872. t.join();
  18873. ASSERT_FALSE(svr.is_running());
  18874. });
  18875. svr.wait_until_ready();
  18876. Client cli(HOST, PORT);
  18877. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18879. EXPECT_EQ(StatusCode::OK_200, res->status);
  18880. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18881. // ignored entirely and the real connection-level address retained.
  18882. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18883. observed_remote_addr == "127.0.0.1");
  18884. }
  18885. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18886. Server svr;
  18887. std::string observed_remote_addr;
  18888. std::string observed_xff;
  18889. svr.Get("/ip", [&](const Request &req, Response &res) {
  18890. observed_remote_addr = req.remote_addr;
  18891. observed_xff = req.get_header_value("X-Forwarded-For");
  18892. res.set_content("ok", "text/plain");
  18893. });
  18894. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18895. auto se = detail::scope_exit([&] {
  18896. svr.stop();
  18897. t.join();
  18898. ASSERT_FALSE(svr.is_running());
  18899. });
  18900. svr.wait_until_ready();
  18901. Client cli(HOST, PORT);
  18902. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18904. EXPECT_EQ(StatusCode::OK_200, res->status);
  18905. EXPECT_EQ(observed_xff, "203.0.113.66");
  18906. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18907. observed_remote_addr == "127.0.0.1");
  18908. }
  18909. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18910. Server svr;
  18911. svr.set_trusted_proxies({"203.0.113.66"});
  18912. std::string observed_remote_addr;
  18913. std::string observed_xff;
  18914. svr.Get("/ip", [&](const Request &req, Response &res) {
  18915. observed_remote_addr = req.remote_addr;
  18916. observed_xff = req.get_header_value("X-Forwarded-For");
  18917. res.set_content("ok", "text/plain");
  18918. });
  18919. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18920. auto se = detail::scope_exit([&] {
  18921. svr.stop();
  18922. t.join();
  18923. ASSERT_FALSE(svr.is_running());
  18924. });
  18925. svr.wait_until_ready();
  18926. Client cli(HOST, PORT);
  18927. auto res = cli.Get("/ip");
  18928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18929. EXPECT_EQ(StatusCode::OK_200, res->status);
  18930. EXPECT_EQ(observed_xff, "");
  18931. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18932. observed_remote_addr == "127.0.0.1");
  18933. }
  18934. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18935. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18936. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18937. Server svr;
  18938. svr.set_trusted_proxies({"127.0.0.1"});
  18939. svr.Get("/ip", [](const Request &req, Response &res) {
  18940. res.set_content(req.remote_addr, "text/plain");
  18941. });
  18942. auto port = svr.bind_to_any_port("::");
  18943. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18944. thread t = thread([&] { svr.listen_after_bind(); });
  18945. auto se = detail::scope_exit([&] {
  18946. svr.stop();
  18947. t.join();
  18948. ASSERT_FALSE(svr.is_running());
  18949. });
  18950. svr.wait_until_ready();
  18951. Client cli("127.0.0.1", port);
  18952. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  18953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18954. EXPECT_EQ("198.51.100.23", res->body);
  18955. }
  18956. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  18957. Server svr;
  18958. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18959. svr.Get("/ip", [](const Request &req, Response &res) {
  18960. res.set_content(req.remote_addr, "text/plain");
  18961. });
  18962. auto port = svr.bind_to_any_port(HOST);
  18963. ASSERT_GT(port, 0);
  18964. thread t = thread([&] { svr.listen_after_bind(); });
  18965. auto se = detail::scope_exit([&] {
  18966. svr.stop();
  18967. t.join();
  18968. ASSERT_FALSE(svr.is_running());
  18969. });
  18970. svr.wait_until_ready();
  18971. Client cli(HOST, port);
  18972. auto res = cli.Get(
  18973. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  18974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18975. EXPECT_EQ("198.51.100.23", res->body);
  18976. }
  18977. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18978. Server svr;
  18979. // Include the loopback address the test client actually connects from, so
  18980. // the direct connection itself is recognized as the trusted proxy hop.
  18981. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18982. std::string observed_remote_addr;
  18983. std::string observed_xff;
  18984. svr.Get("/ip", [&](const Request &req, Response &res) {
  18985. observed_remote_addr = req.remote_addr;
  18986. observed_xff = req.get_header_value("X-Forwarded-For");
  18987. res.set_content("ok", "text/plain");
  18988. });
  18989. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18990. auto se = detail::scope_exit([&] {
  18991. svr.stop();
  18992. t.join();
  18993. ASSERT_FALSE(svr.is_running());
  18994. });
  18995. svr.wait_until_ready();
  18996. Client cli(HOST, PORT);
  18997. auto res = cli.Get(
  18998. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19000. EXPECT_EQ(StatusCode::OK_200, res->status);
  19001. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19002. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19003. }
  19004. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19005. Server svr;
  19006. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19007. std::string observed_remote_addr;
  19008. std::string observed_xff;
  19009. svr.Get("/ip", [&](const Request &req, Response &res) {
  19010. observed_remote_addr = req.remote_addr;
  19011. observed_xff = req.get_header_value("X-Forwarded-For");
  19012. res.set_content("ok", "text/plain");
  19013. });
  19014. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19015. auto se = detail::scope_exit([&] {
  19016. svr.stop();
  19017. t.join();
  19018. ASSERT_FALSE(svr.is_running());
  19019. });
  19020. svr.wait_until_ready();
  19021. Client cli(HOST, PORT);
  19022. auto res = cli.Get(
  19023. "/ip",
  19024. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19026. EXPECT_EQ(StatusCode::OK_200, res->status);
  19027. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19028. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19029. }
  19030. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19031. Server svr;
  19032. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19033. std::string observed_remote_addr;
  19034. std::string observed_xff;
  19035. svr.Get("/ip", [&](const Request &req, Response &res) {
  19036. observed_remote_addr = req.remote_addr;
  19037. observed_xff = req.get_header_value("X-Forwarded-For");
  19038. res.set_content("ok", "text/plain");
  19039. });
  19040. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19041. auto se = detail::scope_exit([&] {
  19042. svr.stop();
  19043. t.join();
  19044. ASSERT_FALSE(svr.is_running());
  19045. });
  19046. svr.wait_until_ready();
  19047. Client cli(HOST, PORT);
  19048. auto res = cli.Get(
  19049. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19051. EXPECT_EQ(StatusCode::OK_200, res->status);
  19052. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19053. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19054. // and must not be selected.
  19055. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19056. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19057. }
  19058. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19059. Server svr;
  19060. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19061. std::string observed_remote_addr;
  19062. svr.Get("/ip", [&](const Request &req, Response &res) {
  19063. observed_remote_addr = req.remote_addr;
  19064. res.set_content("ok", "text/plain");
  19065. });
  19066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19067. auto se = detail::scope_exit([&] {
  19068. svr.stop();
  19069. t.join();
  19070. ASSERT_FALSE(svr.is_running());
  19071. });
  19072. svr.wait_until_ready();
  19073. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19074. // a forged address and the trusted proxy's own address; the forged value must
  19075. // not win over the address the trusted proxy actually recorded.
  19076. Client cli(HOST, PORT);
  19077. auto res = cli.Get(
  19078. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19080. EXPECT_EQ(StatusCode::OK_200, res->status);
  19081. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19082. }
  19083. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19084. Server svr;
  19085. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19086. std::string observed_remote_addr;
  19087. std::string observed_xff;
  19088. svr.Get("/ip", [&](const Request &req, Response &res) {
  19089. observed_remote_addr = req.remote_addr;
  19090. observed_xff = req.get_header_value("X-Forwarded-For");
  19091. res.set_content("ok", "text/plain");
  19092. });
  19093. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19094. auto se = detail::scope_exit([&] {
  19095. svr.stop();
  19096. t.join();
  19097. ASSERT_FALSE(svr.is_running());
  19098. });
  19099. svr.wait_until_ready();
  19100. Client cli(HOST, PORT);
  19101. auto res = cli.Get(
  19102. "/ip",
  19103. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19105. EXPECT_EQ(StatusCode::OK_200, res->status);
  19106. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19107. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19108. }
  19109. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19110. Server svr;
  19111. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19112. std::string observed_remote_addr;
  19113. std::string observed_xff;
  19114. svr.Get("/ip", [&](const Request &req, Response &res) {
  19115. observed_remote_addr = req.remote_addr;
  19116. observed_xff = req.get_header_value("X-Forwarded-For");
  19117. res.set_content("ok", "text/plain");
  19118. });
  19119. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19120. auto se = detail::scope_exit([&] {
  19121. svr.stop();
  19122. t.join();
  19123. ASSERT_FALSE(svr.is_running());
  19124. });
  19125. svr.wait_until_ready();
  19126. std::string raw_req =
  19127. "GET /ip HTTP/1.1\r\n"
  19128. "Host: localhost\r\n"
  19129. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19130. "Connection: close\r\n"
  19131. "\r\n";
  19132. std::string out;
  19133. ASSERT_TRUE(send_request(5, raw_req, &out));
  19134. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19135. // Header parser trims surrounding whitespace of the header value
  19136. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19137. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19138. }
  19139. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19140. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19141. // their own X-Forwarded-For as a separate field line rather than extending the
  19142. // one the client sent, so every occurrence has to be taken into account.
  19143. // Reading only the first one hands back the address the client chose.
  19144. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19145. Server svr;
  19146. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19147. std::string observed_remote_addr;
  19148. size_t observed_xff_count = 0;
  19149. svr.Get("/ip", [&](const Request &req, Response &res) {
  19150. observed_remote_addr = req.remote_addr;
  19151. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19152. res.set_content("ok", "text/plain");
  19153. });
  19154. auto port = svr.bind_to_any_port(HOST);
  19155. thread t = thread([&]() { svr.listen_after_bind(); });
  19156. auto se = detail::scope_exit([&] {
  19157. svr.stop();
  19158. t.join();
  19159. ASSERT_FALSE(svr.is_running());
  19160. });
  19161. svr.wait_until_ready();
  19162. // The client supplies the first field line; the trusted proxy appends the
  19163. // address it observed as a second one.
  19164. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19165. "Host: localhost\r\n"
  19166. "X-Forwarded-For: 1.2.3.4\r\n"
  19167. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19168. "Connection: close\r\n"
  19169. "\r\n";
  19170. std::string out;
  19171. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19172. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19173. EXPECT_EQ(observed_xff_count, 2U);
  19174. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19175. // The same chain spread over one field line per hop derives the same client
  19176. // address, i.e. the split and the comma-joined representations agree.
  19177. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19178. "Host: localhost\r\n"
  19179. "X-Forwarded-For: 1.2.3.4\r\n"
  19180. "X-Forwarded-For: 198.51.100.23\r\n"
  19181. "X-Forwarded-For: 192.0.2.45\r\n"
  19182. "Connection: close\r\n"
  19183. "\r\n";
  19184. out.clear();
  19185. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19186. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19187. EXPECT_EQ(observed_xff_count, 3U);
  19188. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19189. }
  19190. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19191. // crash the server (it used to call front() on an empty vector inside
  19192. // get_client_ip). The connection-level remote address must be retained instead.
  19193. static void run_malformed_xff_test(const std::string &xff_value) {
  19194. Server svr;
  19195. svr.set_trusted_proxies({"192.0.2.45"});
  19196. std::string observed_remote_addr;
  19197. svr.Get("/ip", [&](const Request &req, Response &res) {
  19198. observed_remote_addr = req.remote_addr;
  19199. res.set_content("ok", "text/plain");
  19200. });
  19201. int port = 0;
  19202. thread t = thread([&]() {
  19203. port = svr.bind_to_any_port(HOST);
  19204. svr.listen_after_bind();
  19205. });
  19206. auto se = detail::scope_exit([&] {
  19207. svr.stop();
  19208. t.join();
  19209. ASSERT_FALSE(svr.is_running());
  19210. });
  19211. svr.wait_until_ready();
  19212. Client cli(HOST, port);
  19213. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19215. EXPECT_EQ(StatusCode::OK_200, res->status);
  19216. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19217. observed_remote_addr == "127.0.0.1");
  19218. }
  19219. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19220. run_malformed_xff_test("");
  19221. }
  19222. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19223. run_malformed_xff_test(",");
  19224. }
  19225. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19226. run_malformed_xff_test(", , ,");
  19227. }
  19228. // The same rule applies to Accept: a request whose acceptable types are spread
  19229. // over several field lines must be negotiated against all of them.
  19230. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19231. // case-insensitive connection options. Comparing the whole field value against
  19232. // one option misses a client that sends several of them, and misses every
  19233. // casing but the one written in the comparison.
  19234. //
  19235. // Sends req, reads the response, then reuses the same socket for a second
  19236. // request to find out whether the server kept the connection.
  19237. static void probe_connection_reuse(int port, const std::string &req,
  19238. bool *announced_close, bool *reusable) {
  19239. auto error = Error::Success;
  19240. auto sock = detail::create_client_socket(
  19241. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19242. /*connection_timeout_sec=*/5, 0,
  19243. /*read_timeout_sec=*/1, 0,
  19244. /*write_timeout_sec=*/5, 0, std::string(), error);
  19245. ASSERT_NE(sock, INVALID_SOCKET);
  19246. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19247. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19248. "Host: localhost\r\n"
  19249. "Connection: close\r\n"
  19250. "\r\n";
  19251. std::string first_response;
  19252. std::string second_response;
  19253. detail::process_client_socket(
  19254. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19255. [&](Stream &strm) {
  19256. if (strm.write(req.data(), req.size()) !=
  19257. static_cast<ssize_t>(req.size())) {
  19258. return false;
  19259. }
  19260. char buf[512];
  19261. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19262. // Headers plus the two-byte body of the handler below
  19263. while (reader.getline()) {
  19264. first_response += reader.ptr();
  19265. if (first_response.find("ok") != std::string::npos) { break; }
  19266. }
  19267. if (strm.write(second.data(), second.size()) !=
  19268. static_cast<ssize_t>(second.size())) {
  19269. return true;
  19270. }
  19271. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19272. while (reader2.getline()) {
  19273. second_response += reader2.ptr();
  19274. if (second_response.find("ok") != std::string::npos) { break; }
  19275. }
  19276. return true;
  19277. });
  19278. *announced_close =
  19279. first_response.find("Connection: close") != std::string::npos;
  19280. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19281. }
  19282. class ConnectionTokenTest : public ::testing::Test {
  19283. protected:
  19284. void SetUp() override {
  19285. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19286. res.set_content("ok", "text/plain");
  19287. });
  19288. port_ = svr_.bind_to_any_port(HOST);
  19289. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19290. svr_.wait_until_ready();
  19291. }
  19292. void TearDown() override {
  19293. svr_.stop();
  19294. if (thread_.joinable()) { thread_.join(); }
  19295. }
  19296. Server svr_;
  19297. int port_ = 0;
  19298. thread thread_;
  19299. };
  19300. // "close" alongside another option still closes the connection, and the
  19301. // response says so rather than leaving the peer to discover it.
  19302. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19303. bool announced_close = false;
  19304. bool reusable = true;
  19305. probe_connection_reuse(port_,
  19306. "GET /keepalive HTTP/1.1\r\n"
  19307. "Host: localhost\r\n"
  19308. "Connection: keep-alive, close\r\n"
  19309. "\r\n",
  19310. &announced_close, &reusable);
  19311. EXPECT_TRUE(announced_close);
  19312. EXPECT_FALSE(reusable);
  19313. }
  19314. // "close" split over two field lines is the same list, so it is honored too.
  19315. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19316. bool announced_close = false;
  19317. bool reusable = true;
  19318. probe_connection_reuse(port_,
  19319. "GET /keepalive HTTP/1.1\r\n"
  19320. "Host: localhost\r\n"
  19321. "Connection: keep-alive\r\n"
  19322. "Connection: close\r\n"
  19323. "\r\n",
  19324. &announced_close, &reusable);
  19325. EXPECT_TRUE(announced_close);
  19326. EXPECT_FALSE(reusable);
  19327. }
  19328. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19329. // keep-alive in the spelling everyone actually sends keeps its connection.
  19330. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19331. bool announced_close = false;
  19332. bool reusable = false;
  19333. probe_connection_reuse(port_,
  19334. "GET /keepalive HTTP/1.0\r\n"
  19335. "Host: localhost\r\n"
  19336. "Connection: keep-alive\r\n"
  19337. "\r\n",
  19338. &announced_close, &reusable);
  19339. EXPECT_FALSE(announced_close);
  19340. EXPECT_TRUE(reusable);
  19341. }
  19342. // A token the value merely contains is not the token itself.
  19343. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19344. bool announced_close = false;
  19345. bool reusable = false;
  19346. probe_connection_reuse(port_,
  19347. "GET /keepalive HTTP/1.1\r\n"
  19348. "Host: localhost\r\n"
  19349. "Connection: notclose\r\n"
  19350. "\r\n",
  19351. &announced_close, &reusable);
  19352. EXPECT_FALSE(announced_close);
  19353. EXPECT_TRUE(reusable);
  19354. }
  19355. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19356. Server svr;
  19357. std::vector<std::string> observed_types;
  19358. svr.Get("/", [&](const Request &req, Response &res) {
  19359. observed_types = req.accept_content_types;
  19360. res.set_content("ok", "text/plain");
  19361. });
  19362. auto port = svr.bind_to_any_port(HOST);
  19363. thread t = thread([&]() { svr.listen_after_bind(); });
  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. Headers headers;
  19372. headers.emplace("Accept", "text/plain;q=0.5");
  19373. headers.emplace("Accept", "application/json");
  19374. auto res = cli.Get("/", headers);
  19375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19376. EXPECT_EQ(StatusCode::OK_200, res->status);
  19377. // Sorted by q-value, so the second field line's type comes first
  19378. ASSERT_EQ(2U, observed_types.size());
  19379. EXPECT_EQ("application/json", observed_types[0]);
  19380. EXPECT_EQ("text/plain", observed_types[1]);
  19381. }
  19382. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19383. // empty field line must not contribute a bare comma to the combined value.
  19384. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19385. Server svr;
  19386. std::vector<std::string> observed_types;
  19387. svr.Get("/", [&](const Request &req, Response &res) {
  19388. observed_types = req.accept_content_types;
  19389. res.set_content("ok", "text/plain");
  19390. });
  19391. auto port = svr.bind_to_any_port(HOST);
  19392. thread t = thread([&]() { svr.listen_after_bind(); });
  19393. auto se = detail::scope_exit([&] {
  19394. svr.stop();
  19395. t.join();
  19396. ASSERT_FALSE(svr.is_running());
  19397. });
  19398. svr.wait_until_ready();
  19399. // Empty first field line, then a real one
  19400. std::string raw_req = "GET / HTTP/1.1\r\n"
  19401. "Host: localhost\r\n"
  19402. "Accept:\r\n"
  19403. "Accept: application/json\r\n"
  19404. "Connection: close\r\n"
  19405. "\r\n";
  19406. std::string out;
  19407. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19408. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19409. ASSERT_EQ(1U, observed_types.size());
  19410. EXPECT_EQ("application/json", observed_types[0]);
  19411. }
  19412. // The skip in get_combined_header_value() is what keeps an empty field line
  19413. // from contributing a bare comma. Only a trailing empty field line exercises
  19414. // it: a leading one is already covered by the "combined is still empty" check,
  19415. // and parse_accept_header() now ignores the empty element either way, so the
  19416. // request-level test above can no longer tell the two apart.
  19417. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19418. Headers headers;
  19419. headers.emplace("Accept", "text/html");
  19420. headers.emplace("Accept", "");
  19421. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19422. headers.clear();
  19423. headers.emplace("Accept", "");
  19424. headers.emplace("Accept", "application/json");
  19425. EXPECT_EQ("application/json",
  19426. detail::get_combined_header_value(headers, "Accept"));
  19427. }
  19428. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19429. // An encoding offered on a later Accept-Encoding field line is still offered.
  19430. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19431. Server svr;
  19432. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19433. res.set_content(std::string(1024, 'x'), "text/plain");
  19434. });
  19435. auto port = svr.bind_to_any_port(HOST);
  19436. thread t = thread([&]() { svr.listen_after_bind(); });
  19437. auto se = detail::scope_exit([&] {
  19438. svr.stop();
  19439. t.join();
  19440. ASSERT_FALSE(svr.is_running());
  19441. });
  19442. svr.wait_until_ready();
  19443. Client cli(HOST, port);
  19444. cli.set_decompress(false);
  19445. Headers headers;
  19446. headers.emplace("Accept-Encoding", "identity");
  19447. headers.emplace("Accept-Encoding", "gzip");
  19448. auto res = cli.Get("/", headers);
  19449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19450. EXPECT_EQ(StatusCode::OK_200, res->status);
  19451. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19452. }
  19453. #endif
  19454. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19455. // Transfer-Encoding is not its body.
  19456. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19457. Server svr;
  19458. svr.set_payload_max_length(8);
  19459. svr.Post("/test", [](const Request &, Response &res) {
  19460. res.set_content("ok", "text/plain");
  19461. });
  19462. auto port = svr.bind_to_any_port(HOST);
  19463. ASSERT_GT(port, 0);
  19464. thread t = thread([&] { svr.listen_after_bind(); });
  19465. auto se = detail::scope_exit([&] {
  19466. svr.stop();
  19467. t.join();
  19468. ASSERT_FALSE(svr.is_running());
  19469. });
  19470. svr.wait_until_ready();
  19471. std::string resp;
  19472. ASSERT_TRUE(send_request(1,
  19473. "POST /test HTTP/1.1\r\n"
  19474. "Host: localhost\r\n"
  19475. "Connection: close\r\n"
  19476. "\r\n" +
  19477. std::string(16, 'X'),
  19478. &resp, port));
  19479. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19480. }
  19481. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19482. Server svr;
  19483. svr.Post("/post", [&](const Request &req, Response &res) {
  19484. res.set_content(req.body, "text/plain");
  19485. });
  19486. svr.Put("/put", [&](const Request &req, Response &res) {
  19487. res.set_content(req.body, "text/plain");
  19488. });
  19489. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19490. res.set_content(req.body, "text/plain");
  19491. });
  19492. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19493. res.set_content(req.body, "text/plain");
  19494. });
  19495. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19496. auto se = detail::scope_exit([&] {
  19497. svr.stop();
  19498. t.join();
  19499. ASSERT_FALSE(svr.is_running());
  19500. });
  19501. svr.wait_until_ready();
  19502. std::string resp;
  19503. // POST without Content-Length
  19504. ASSERT_TRUE(send_request(5,
  19505. "POST /post HTTP/1.1\r\n"
  19506. "Host: localhost\r\n"
  19507. "Connection: close\r\n"
  19508. "\r\n",
  19509. &resp));
  19510. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19511. // PUT without Content-Length
  19512. resp.clear();
  19513. ASSERT_TRUE(send_request(5,
  19514. "PUT /put HTTP/1.1\r\n"
  19515. "Host: localhost\r\n"
  19516. "Connection: close\r\n"
  19517. "\r\n",
  19518. &resp));
  19519. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19520. // PATCH without Content-Length
  19521. resp.clear();
  19522. ASSERT_TRUE(send_request(5,
  19523. "PATCH /patch HTTP/1.1\r\n"
  19524. "Host: localhost\r\n"
  19525. "Connection: close\r\n"
  19526. "\r\n",
  19527. &resp));
  19528. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19529. // DELETE without Content-Length
  19530. resp.clear();
  19531. ASSERT_TRUE(send_request(5,
  19532. "DELETE /delete HTTP/1.1\r\n"
  19533. "Host: localhost\r\n"
  19534. "Connection: close\r\n"
  19535. "\r\n",
  19536. &resp));
  19537. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19538. }
  19539. //==============================================================================
  19540. // open_stream() Tests
  19541. //==============================================================================
  19542. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19543. std::string result;
  19544. char buf[8192];
  19545. ssize_t n;
  19546. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19547. result.append(buf, static_cast<size_t>(n));
  19548. }
  19549. return result;
  19550. }
  19551. // Mock stream for unit tests
  19552. class MockStream : public Stream {
  19553. public:
  19554. std::string data;
  19555. size_t pos = 0;
  19556. ssize_t error_after = -1; // -1 = no error
  19557. explicit MockStream(const std::string &d, ssize_t err = -1)
  19558. : data(d), error_after(err) {}
  19559. bool is_readable() const override { return true; }
  19560. bool wait_readable() const override { return true; }
  19561. bool wait_writable() const override { return true; }
  19562. ssize_t read(char *ptr, size_t size) override {
  19563. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19564. if (pos >= data.size()) return 0;
  19565. size_t limit =
  19566. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19567. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19568. std::memcpy(ptr, data.data() + pos, to_read);
  19569. pos += to_read;
  19570. return static_cast<ssize_t>(to_read);
  19571. }
  19572. ssize_t write(const char *, size_t) override { return -1; }
  19573. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19574. ip = "127.0.0.1";
  19575. port = 0;
  19576. }
  19577. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19578. ip = "127.0.0.1";
  19579. port = 0;
  19580. }
  19581. socket_t socket() const override { return INVALID_SOCKET; }
  19582. time_t duration() const override { return 0; }
  19583. };
  19584. TEST(StreamHandleTest, Basic) {
  19585. ClientImpl::StreamHandle handle;
  19586. EXPECT_FALSE(handle.is_valid());
  19587. handle.response = detail::make_unique<Response>();
  19588. handle.error = Error::Connection;
  19589. EXPECT_FALSE(handle.is_valid());
  19590. handle.error = Error::Success;
  19591. EXPECT_TRUE(handle.is_valid());
  19592. }
  19593. TEST(BodyReaderTest, Basic) {
  19594. MockStream stream("Hello, World!");
  19595. detail::BodyReader reader;
  19596. reader.stream = &stream;
  19597. reader.content_length = 13;
  19598. char buf[32];
  19599. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19600. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19601. EXPECT_TRUE(reader.eof);
  19602. }
  19603. TEST(BodyReaderTest, NoStream) {
  19604. detail::BodyReader reader;
  19605. char buf[32];
  19606. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19607. EXPECT_EQ(Error::Connection, reader.last_error);
  19608. }
  19609. TEST(BodyReaderTest, Error) {
  19610. MockStream stream("Hello, World!", 5);
  19611. detail::BodyReader reader;
  19612. reader.stream = &stream;
  19613. reader.content_length = 13;
  19614. char buf[32];
  19615. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19616. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19617. EXPECT_EQ(Error::Read, reader.last_error);
  19618. }
  19619. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19620. // Mock-based StreamHandle tests relying on private internals are removed.
  19621. class OpenStreamTest : public ::testing::Test {
  19622. protected:
  19623. void SetUp() override {
  19624. svr_.Get("/hello", [](const Request &, Response &res) {
  19625. res.set_content("Hello World!", "text/plain");
  19626. });
  19627. svr_.Get("/large", [](const Request &, Response &res) {
  19628. res.set_content(std::string(10000, 'X'), "text/plain");
  19629. });
  19630. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19631. res.set_content("Hello World!", "image/jpeg");
  19632. res.set_header("Content-Encoding", "UTF-8");
  19633. });
  19634. svr_.Get("/chunked", [](const Request &, Response &res) {
  19635. res.set_chunked_content_provider("text/plain",
  19636. [](size_t offset, DataSink &sink) {
  19637. if (offset < 15) {
  19638. sink.write("chunk", 5);
  19639. return true;
  19640. }
  19641. sink.done();
  19642. return true;
  19643. });
  19644. });
  19645. svr_.Get("/compressible", [](const Request &, Response &res) {
  19646. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19647. DataSink &sink) {
  19648. if (offset < 100 * 1024) {
  19649. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19650. sink.write(chunk.data(), chunk.size());
  19651. return true;
  19652. }
  19653. sink.done();
  19654. return true;
  19655. });
  19656. });
  19657. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19658. [](const Request & /*req*/, Response &res) {
  19659. auto i = new int(0);
  19660. res.set_header("Trailer", "Content-Length, X-Allowed");
  19661. res.set_chunked_content_provider(
  19662. "text/plain",
  19663. [i](size_t /*offset*/, DataSink &sink) {
  19664. switch (*i) {
  19665. case 0: sink.os << "123"; break;
  19666. case 1: sink.os << "456"; break;
  19667. case 2: sink.os << "789"; break;
  19668. case 3: {
  19669. sink.done_with_trailer(
  19670. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19671. } break;
  19672. }
  19673. (*i)++;
  19674. return true;
  19675. },
  19676. [i](bool success) {
  19677. EXPECT_TRUE(success);
  19678. delete i;
  19679. });
  19680. });
  19681. // Echo headers endpoint for header-related tests
  19682. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19683. std::string body;
  19684. for (const auto &h : req.headers) {
  19685. body.append(h.first);
  19686. body.push_back(':');
  19687. body.append(h.second);
  19688. body.push_back('\n');
  19689. }
  19690. res.set_content(body, "text/plain");
  19691. });
  19692. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19693. std::string body;
  19694. for (const auto &h : req.headers) {
  19695. body.append(h.first);
  19696. body.push_back(':');
  19697. body.append(h.second);
  19698. body.push_back('\n');
  19699. }
  19700. res.set_content(body, "text/plain");
  19701. });
  19702. port_ = svr_.bind_to_any_port("127.0.0.1");
  19703. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19704. svr_.wait_until_ready();
  19705. }
  19706. void TearDown() override {
  19707. svr_.stop();
  19708. if (thread_.joinable()) thread_.join();
  19709. }
  19710. Server svr_;
  19711. std::thread thread_;
  19712. int port_ = 0;
  19713. };
  19714. TEST_F(OpenStreamTest, Basic) {
  19715. Client cli("127.0.0.1", port_);
  19716. auto handle = cli.open_stream("GET", "/hello");
  19717. EXPECT_TRUE(handle.is_valid());
  19718. EXPECT_EQ("Hello World!", read_all(handle));
  19719. }
  19720. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19721. Client cli("127.0.0.1", port_);
  19722. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19723. ASSERT_TRUE(handle.is_valid());
  19724. EXPECT_EQ("Hello World!", read_all(handle));
  19725. }
  19726. TEST_F(OpenStreamTest, SmallBuffer) {
  19727. Client cli("127.0.0.1", port_);
  19728. auto handle = cli.open_stream("GET", "/hello");
  19729. std::string result;
  19730. char buf[4];
  19731. ssize_t n;
  19732. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19733. result.append(buf, static_cast<size_t>(n));
  19734. EXPECT_EQ("Hello World!", result);
  19735. }
  19736. TEST_F(OpenStreamTest, DefaultHeaders) {
  19737. Client cli("127.0.0.1", port_);
  19738. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19739. {
  19740. auto handle = cli.open_stream("GET", "/echo-headers");
  19741. ASSERT_TRUE(handle.is_valid());
  19742. auto body = read_all(handle);
  19743. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19744. std::string::npos);
  19745. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19746. std::string::npos);
  19747. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19748. }
  19749. // open_stream POST with body and no explicit content_type should NOT add
  19750. // text/plain Content-Type (behavior differs from non-streaming path), but
  19751. // should include Content-Length
  19752. {
  19753. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19754. ASSERT_TRUE(handle.is_valid());
  19755. auto body = read_all(handle);
  19756. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19757. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19758. }
  19759. // open_stream POST with explicit Content-Type should preserve it
  19760. {
  19761. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19762. {{"Content-Type", "application/custom"}},
  19763. "{}", "application/custom");
  19764. ASSERT_TRUE(handle.is_valid());
  19765. auto body = read_all(handle);
  19766. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19767. }
  19768. // User-specified User-Agent must not be overwritten for stream API
  19769. {
  19770. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19771. {{"User-Agent", "MyAgent/1.2"}});
  19772. ASSERT_TRUE(handle.is_valid());
  19773. auto body = read_all(handle);
  19774. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19775. }
  19776. }
  19777. TEST_F(OpenStreamTest, Large) {
  19778. Client cli("127.0.0.1", port_);
  19779. auto handle = cli.open_stream("GET", "/large");
  19780. EXPECT_EQ(10000u, read_all(handle).size());
  19781. }
  19782. TEST_F(OpenStreamTest, ConnectionError) {
  19783. Client cli("127.0.0.1", 9999);
  19784. auto handle = cli.open_stream("GET", "/hello");
  19785. EXPECT_FALSE(handle.is_valid());
  19786. }
  19787. TEST_F(OpenStreamTest, Chunked) {
  19788. Client cli("127.0.0.1", port_);
  19789. auto handle = cli.open_stream("GET", "/chunked");
  19790. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19791. "Transfer-Encoding") == "chunked");
  19792. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19793. }
  19794. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19795. Client cli("127.0.0.1", port_);
  19796. auto handle =
  19797. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19798. ASSERT_TRUE(handle.is_valid());
  19799. // Consume body to allow trailers to be received/parsed
  19800. auto body = read_all(handle);
  19801. // Explicitly parse trailers (ensure trailers are available for assertion)
  19802. handle.parse_trailers_if_needed();
  19803. EXPECT_EQ(std::string("123456789"), body);
  19804. // The response should include a Trailer header declaring both names
  19805. ASSERT_TRUE(handle.response);
  19806. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19807. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19808. handle.response->get_header_value("Trailer"));
  19809. // Prohibited trailer must not be present
  19810. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19811. // Allowed trailer should be present
  19812. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19813. EXPECT_EQ(std::string("yes"),
  19814. handle.response->get_trailer_value("X-Allowed"));
  19815. // Verify trailers are NOT present as regular headers
  19816. EXPECT_EQ(std::string(""),
  19817. handle.response->get_header_value("Content-Length"));
  19818. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19819. }
  19820. // Accepts one connection on an OS-assigned port, which it hands over through
  19821. // port_promise, reads the request head and sends back response. after_send,
  19822. // if given, runs on the connection before it is closed.
  19823. static std::thread
  19824. serve_single_response(std::promise<int> &port_promise,
  19825. const std::string &response,
  19826. std::function<void(socket_t)> after_send = nullptr) {
  19827. return std::thread([&port_promise, response, after_send] {
  19828. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19829. default_socket_options(srv);
  19830. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19831. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19832. sockaddr_in addr{};
  19833. addr.sin_family = AF_INET;
  19834. addr.sin_port = htons(0); // Let OS assign a free port
  19835. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19836. int opt = 1;
  19837. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19838. #ifdef _WIN32
  19839. reinterpret_cast<const char *>(&opt),
  19840. #else
  19841. &opt,
  19842. #endif
  19843. sizeof(opt));
  19844. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19845. ::listen(srv, 1) != 0) {
  19846. port_promise.set_value(-1);
  19847. detail::close_socket(srv);
  19848. return;
  19849. }
  19850. socklen_t addr_len = sizeof(addr);
  19851. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19852. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19853. sockaddr_in cli_addr{};
  19854. socklen_t cli_len = sizeof(cli_addr);
  19855. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19856. if (cli != INVALID_SOCKET) {
  19857. // Read the complete HTTP request (until the blank line that terminates
  19858. // headers) before sending the response. If the server closes the socket
  19859. // while the client's request data is still unread in the kernel receive
  19860. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19861. // connection on both sides: it discards the client's receive buffer
  19862. // (which already holds our response) and causes any in-progress write on
  19863. // the client to fail with ECONNRESET. Reading all request data first
  19864. // ensures close() emits a graceful FIN.
  19865. {
  19866. char rbuf[256];
  19867. std::string req;
  19868. while (req.find("\r\n\r\n") == std::string::npos) {
  19869. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19870. if (n <= 0) { break; }
  19871. req.append(rbuf, static_cast<size_t>(n));
  19872. }
  19873. }
  19874. ::send(cli,
  19875. #ifdef _WIN32
  19876. static_cast<const char *>(response.c_str()),
  19877. static_cast<int>(response.size()),
  19878. #else
  19879. response.c_str(), response.size(),
  19880. #endif
  19881. 0);
  19882. if (after_send) { after_send(cli); }
  19883. detail::close_socket(cli);
  19884. }
  19885. detail::close_socket(srv);
  19886. });
  19887. }
  19888. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19889. #ifndef _WIN32
  19890. signal(SIGPIPE, SIG_IGN);
  19891. #endif
  19892. std::promise<int> port_promise;
  19893. auto port_future = port_promise.get_future();
  19894. auto server_thread =
  19895. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19896. "Content-Type: text/plain\r\n"
  19897. "Content-Length: not-a-number\r\n"
  19898. "Connection: close\r\n"
  19899. "\r\n"
  19900. "hello");
  19901. auto port = port_future.get();
  19902. ASSERT_GT(port, 0);
  19903. Client cli("127.0.0.1", port);
  19904. auto handle = cli.open_stream("GET", "/");
  19905. EXPECT_FALSE(handle.is_valid());
  19906. server_thread.join();
  19907. }
  19908. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19909. #ifndef _WIN32
  19910. signal(SIGPIPE, SIG_IGN);
  19911. #endif
  19912. std::promise<int> port_promise;
  19913. auto port_future = port_promise.get_future();
  19914. auto server_thread = serve_single_response(
  19915. port_promise, "HTTP/1.1 200 OK\r\n"
  19916. "Content-Type: text/plain\r\n"
  19917. "Content-Length: 99999999999999999999999999\r\n"
  19918. "Connection: close\r\n"
  19919. "\r\n"
  19920. "hello");
  19921. auto port = port_future.get();
  19922. ASSERT_GT(port, 0);
  19923. // Historically std::stoull would throw std::out_of_range here and crash
  19924. // the process, then parsing silently clamped to a bogus framing length and
  19925. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19926. // so the stream fails to open, matching the not-a-number case above. The
  19927. // process still must NOT terminate.
  19928. Client cli("127.0.0.1", port);
  19929. auto handle = cli.open_stream("GET", "/");
  19930. EXPECT_FALSE(handle.is_valid());
  19931. server_thread.join();
  19932. }
  19933. // Serves `response` to the single request `fn` makes with a fresh client.
  19934. template <typename Fn>
  19935. static void with_single_response(const std::string &response, Fn fn) {
  19936. #ifndef _WIN32
  19937. signal(SIGPIPE, SIG_IGN);
  19938. #endif
  19939. std::promise<int> port_promise;
  19940. auto port_future = port_promise.get_future();
  19941. auto server_thread = serve_single_response(port_promise, response);
  19942. auto se = detail::scope_exit([&] { server_thread.join(); });
  19943. auto port = port_future.get();
  19944. ASSERT_GT(port, 0);
  19945. Client cli("127.0.0.1", port);
  19946. fn(cli);
  19947. }
  19948. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19949. // Neither Content-Length nor chunked: the body ends at the close
  19950. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19951. "Connection: close\r\n"
  19952. "\r\n"
  19953. "hello";
  19954. with_single_response(close_delimited, [](Client &cli) {
  19955. auto handle = cli.open_stream("GET", "/");
  19956. ASSERT_TRUE(handle.is_valid());
  19957. EXPECT_EQ("hello", read_all(handle));
  19958. EXPECT_FALSE(handle.has_read_error());
  19959. });
  19960. // A close before the end of the Content-Length is still an error
  19961. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19962. "Content-Length: 10\r\n"
  19963. "\r\n"
  19964. "hello";
  19965. with_single_response(short_content_length, [](Client &cli) {
  19966. auto handle = cli.open_stream("GET", "/");
  19967. ASSERT_TRUE(handle.is_valid());
  19968. read_all(handle);
  19969. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19970. });
  19971. // So is a close before the last chunk
  19972. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19973. "Transfer-Encoding: chunked\r\n"
  19974. "\r\n"
  19975. "5\r\nhello\r\n";
  19976. with_single_response(short_chunked, [](Client &cli) {
  19977. auto handle = cli.open_stream("GET", "/");
  19978. ASSERT_TRUE(handle.is_valid());
  19979. read_all(handle);
  19980. EXPECT_TRUE(handle.has_read_error());
  19981. });
  19982. }
  19983. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19984. const char *responses[] = {
  19985. "HTTP/1.1 103 Early Hints\r\n"
  19986. "Link: </style.css>; rel=preload\r\n"
  19987. "\r\n"
  19988. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19989. "HTTP/1.1 100 Continue\r\n"
  19990. "X-Note: interim\r\n"
  19991. "\r\n"
  19992. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19993. };
  19994. for (auto response : responses) {
  19995. with_single_response(response, [](Client &cli) {
  19996. auto res = cli.Get("/");
  19997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19998. EXPECT_EQ(StatusCode::OK_200, res->status);
  19999. EXPECT_EQ("ok", res->body);
  20000. });
  20001. }
  20002. }
  20003. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20004. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20005. const std::string final_response =
  20006. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20007. std::string interims;
  20008. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20009. interims += interim;
  20010. }
  20011. with_single_response(interims + final_response, [](Client &cli) {
  20012. auto res = cli.Get("/");
  20013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20014. EXPECT_EQ("ok", res->body);
  20015. });
  20016. with_single_response(interims + interim + final_response, [](Client &cli) {
  20017. auto res = cli.Get("/");
  20018. ASSERT_FALSE(res);
  20019. EXPECT_EQ(Error::Read, res.error());
  20020. });
  20021. }
  20022. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20023. #ifndef _WIN32
  20024. signal(SIGPIPE, SIG_IGN);
  20025. #endif
  20026. // The server answers the head without asking for the body. Bytes it then
  20027. // reads on the connection would be taken for the body the request declared.
  20028. auto closed_by_client = false;
  20029. std::promise<int> port_promise;
  20030. auto server_thread = serve_single_response(
  20031. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20032. [&](socket_t sock) {
  20033. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20034. char buf[256];
  20035. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20036. });
  20037. Client cli("127.0.0.1", port_promise.get_future().get());
  20038. cli.set_keep_alive(true);
  20039. cli.set_read_timeout(1, 0);
  20040. // Long enough for the client to send Expect: 100-continue.
  20041. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20043. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20044. cli.Get("/second");
  20045. server_thread.join();
  20046. EXPECT_TRUE(closed_by_client);
  20047. }
  20048. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20049. // Long enough for the client to send Expect: 100-continue
  20050. with_single_response(
  20051. "HTTP/1.1 103 Early Hints\r\n"
  20052. "Link: </style.css>; rel=preload\r\n"
  20053. "\r\n"
  20054. "HTTP/1.1 401 Unauthorized\r\n"
  20055. "Content-Length: 0\r\n\r\n",
  20056. [](Client &cli) {
  20057. cli.set_read_timeout(2, 0);
  20058. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20060. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20061. });
  20062. }
  20063. #ifdef CPPHTTPLIB_SSL_ENABLED
  20064. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20065. #ifndef _WIN32
  20066. signal(SIGPIPE, SIG_IGN);
  20067. #endif
  20068. auto reused = false;
  20069. std::promise<int> port_promise;
  20070. auto server_thread = serve_single_response(
  20071. port_promise,
  20072. "HTTP/1.1 401 Unauthorized\r\n"
  20073. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20074. "Content-Length: 0\r\n\r\n",
  20075. [&](socket_t sock) {
  20076. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20077. char buf[256];
  20078. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20079. });
  20080. Client cli("127.0.0.1", port_promise.get_future().get());
  20081. cli.set_keep_alive(true);
  20082. cli.set_digest_auth("user", "pass");
  20083. cli.set_read_timeout(1, 0);
  20084. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20085. server_thread.join();
  20086. EXPECT_FALSE(reused);
  20087. }
  20088. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20089. // Any other answer to CONNECT would read as the origin's response.
  20090. struct {
  20091. const char *response;
  20092. bool passed_on;
  20093. } cases[] = {
  20094. {"HTTP/1.1 201 Created\r\n"
  20095. "Set-Cookie: session=from-proxy\r\n"
  20096. "Content-Length: 0\r\n\r\n",
  20097. false},
  20098. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20099. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20100. "Content-Length: 0\r\n\r\n",
  20101. true},
  20102. };
  20103. for (const auto &c : cases) {
  20104. std::promise<int> port_promise;
  20105. auto server_thread = serve_single_response(port_promise, c.response);
  20106. SSLClient cli("example.com", 443);
  20107. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20108. auto res = cli.Get("/");
  20109. server_thread.join();
  20110. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20111. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20112. if (res) {
  20113. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20114. }
  20115. }
  20116. }
  20117. #endif
  20118. // Records the client's error logger calls as "error METHOD path", or
  20119. // "error null" for a call without a request
  20120. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20121. return [&log](const Error &err, const Request *req) {
  20122. log.push_back(to_string(err) + " " +
  20123. (req ? req->method + " " + req->path : "null"));
  20124. };
  20125. }
  20126. // A failed request is reported once, with the request the caller made
  20127. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20128. Server svr;
  20129. svr.Get("/big", [](const Request &, Response &res) {
  20130. res.set_content(std::string(100000, 'b'), "text/plain");
  20131. });
  20132. auto port = svr.bind_to_any_port(HOST);
  20133. std::thread t([&]() { svr.listen_after_bind(); });
  20134. auto se = detail::scope_exit([&] {
  20135. svr.stop();
  20136. t.join();
  20137. });
  20138. svr.wait_until_ready();
  20139. Client cli(HOST, port);
  20140. std::vector<std::string> log;
  20141. cli.set_error_logger(record_errors(log));
  20142. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20143. cli.Get("/big", [](const char *, size_t) { return false; });
  20144. EXPECT_EQ(expected, log);
  20145. log.clear();
  20146. cli.Get("/big", [](size_t, size_t) { return false; });
  20147. EXPECT_EQ(expected, log);
  20148. }
  20149. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20150. // Fails while the body is read
  20151. auto broken = [](const Request &, Response &res) {
  20152. res.set_content_provider(10, "text/plain",
  20153. [](size_t, size_t, DataSink &) { return false; });
  20154. };
  20155. Server other;
  20156. other.Get("/broken", broken);
  20157. auto other_port = other.bind_to_any_port(HOST);
  20158. std::thread other_t([&]() { other.listen_after_bind(); });
  20159. auto other_se = detail::scope_exit([&] {
  20160. other.stop();
  20161. other_t.join();
  20162. });
  20163. other.wait_until_ready();
  20164. Server svr;
  20165. svr.Get("/broken", broken);
  20166. svr.Get("/same-origin",
  20167. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20168. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20169. res.set_redirect("http://" + std::string(HOST) + ":" +
  20170. std::to_string(other_port) + "/broken");
  20171. });
  20172. auto port = svr.bind_to_any_port(HOST);
  20173. std::thread t([&]() { svr.listen_after_bind(); });
  20174. auto se = detail::scope_exit([&] {
  20175. svr.stop();
  20176. t.join();
  20177. });
  20178. svr.wait_until_ready();
  20179. Client cli(HOST, port);
  20180. cli.set_follow_location(true);
  20181. std::vector<std::string> log;
  20182. cli.set_error_logger(record_errors(log));
  20183. for (auto path : {"/same-origin", "/cross-origin"}) {
  20184. log.clear();
  20185. auto res = cli.Get(path);
  20186. ASSERT_FALSE(res);
  20187. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20188. log);
  20189. }
  20190. }
  20191. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20192. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20193. std::vector<std::string> log;
  20194. cli.set_error_logger(record_errors(log));
  20195. auto handle = cli.open_stream("GET", "/x");
  20196. EXPECT_FALSE(handle.is_valid());
  20197. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20198. log);
  20199. });
  20200. }
  20201. #ifdef CPPHTTPLIB_SSL_ENABLED
  20202. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20203. // Not a TLS server, so the handshake fails. It waits for a request line in
  20204. // the handshake bytes, so a short read timeout lets it close quickly.
  20205. Server svr;
  20206. svr.set_read_timeout(0, 100000);
  20207. svr.Get("/x", [](const Request &, Response &res) {
  20208. res.set_content("x", "text/plain");
  20209. });
  20210. auto port = svr.bind_to_any_port(HOST);
  20211. std::thread t([&]() { svr.listen_after_bind(); });
  20212. auto se = detail::scope_exit([&] {
  20213. svr.stop();
  20214. t.join();
  20215. });
  20216. svr.wait_until_ready();
  20217. std::vector<std::string> log;
  20218. SSLClient cli(HOST, port);
  20219. cli.enable_server_certificate_verification(false);
  20220. cli.set_error_logger(record_errors(log));
  20221. auto res = cli.Get("/x");
  20222. ASSERT_FALSE(res);
  20223. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20224. log.clear();
  20225. auto handle = cli.open_stream("GET", "/x");
  20226. EXPECT_FALSE(handle.is_valid());
  20227. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20228. log.clear();
  20229. SSLClient no_ca(HOST, port);
  20230. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20231. no_ca.set_error_logger(record_errors(log));
  20232. res = no_ca.Get("/x");
  20233. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20234. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20235. }
  20236. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20237. #ifndef _WIN32
  20238. signal(SIGPIPE, SIG_IGN);
  20239. #endif
  20240. // Refused, answered with a challenge, or closed without an answer
  20241. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20242. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20243. "Content-Length: 0\r\n\r\n",
  20244. ""}) {
  20245. std::promise<int> port_promise;
  20246. auto server_thread = serve_single_response(port_promise, response);
  20247. SSLClient cli("example.com", 443);
  20248. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20249. std::vector<std::string> log;
  20250. cli.set_error_logger(record_errors(log));
  20251. auto res = cli.Get("/");
  20252. server_thread.join();
  20253. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20254. << response;
  20255. }
  20256. }
  20257. #endif
  20258. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20259. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20260. // the chunked coding and drop Content-Length, so a front-end that trusts
  20261. // Content-Length would disagree about where the body ends (response
  20262. // smuggling). The client must reject such a response.
  20263. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20264. for (const char *te : {"chunked", "gzip, chunked"}) {
  20265. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20266. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20267. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20268. "5\r\nhello\r\n0\r\n\r\n";
  20269. with_single_response(response, [&](Client &cli) {
  20270. auto res = cli.Get("/");
  20271. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20272. EXPECT_EQ(Error::Read, res.error()) << te;
  20273. });
  20274. with_single_response(response, [&](Client &cli) {
  20275. auto handle = cli.open_stream("GET", "/");
  20276. EXPECT_FALSE(handle.is_valid()) << te;
  20277. EXPECT_EQ(Error::Read, handle.error) << te;
  20278. });
  20279. }
  20280. }
  20281. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20282. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20283. // closing the connection (unlike a request, which must be rejected).
  20284. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20285. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20286. "Transfer-Encoding: chunked\r\n"
  20287. "Connection: close\r\n"
  20288. "\r\n"
  20289. "5\r\nhello\r\n0\r\n\r\n",
  20290. "HTTP/1.1 200 OK\r\n"
  20291. "Transfer-Encoding: gzip\r\n"
  20292. "Connection: close\r\n"
  20293. "\r\n"
  20294. "hello"}) {
  20295. with_single_response(response, [&](Client &cli) {
  20296. auto res = cli.Get("/");
  20297. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20298. EXPECT_EQ("hello", res->body);
  20299. });
  20300. with_single_response(response, [&](Client &cli) {
  20301. auto handle = cli.open_stream("GET", "/");
  20302. ASSERT_TRUE(handle.is_valid()) << response;
  20303. EXPECT_EQ("hello", read_all(handle));
  20304. });
  20305. }
  20306. }
  20307. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20308. // framing headers describe nothing to read and must not be rejected.
  20309. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20310. const std::string framing = "Content-Length: 5\r\n"
  20311. "Transfer-Encoding: chunked\r\n"
  20312. "Connection: close\r\n"
  20313. "\r\n";
  20314. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20315. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20316. });
  20317. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20318. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20319. });
  20320. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20321. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20322. with_single_response(response, [&](Client &cli) {
  20323. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20324. });
  20325. with_single_response(response, [&](Client &cli) {
  20326. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20327. });
  20328. }
  20329. }
  20330. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20331. // header section, so a stream opened on one has nothing to read, whatever
  20332. // framing or coding headers it carries.
  20333. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20334. struct Case {
  20335. const char *method;
  20336. const char *status;
  20337. };
  20338. // A reader of the declared body reports an early close when nothing
  20339. // follows, and hands back what does.
  20340. struct Framing {
  20341. const char *headers;
  20342. const char *after;
  20343. };
  20344. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20345. Case{"GET", "304 Not Modified"}}) {
  20346. for (const auto &f :
  20347. {Framing{"Content-Length: 5\r\n", ""},
  20348. Framing{"Content-Length: 5\r\n", "hello"},
  20349. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20350. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20351. // Not decoded, so a build without Brotli opens it too
  20352. Framing{"Content-Encoding: br\r\n", ""}}) {
  20353. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20354. "Connection: close\r\n"
  20355. "\r\n" +
  20356. f.after;
  20357. with_single_response(response, [&](Client &cli) {
  20358. auto handle = cli.open_stream(c.method, "/");
  20359. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20360. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20361. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20362. });
  20363. }
  20364. }
  20365. }
  20366. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20367. // response, is faulty framing, so the connection is not reused after it.
  20368. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20369. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20370. "Content-Length: 0\r\n"
  20371. "Transfer-Encoding: chunked\r\n"
  20372. "\r\n"
  20373. "5\r\nhello\r\n0\r\n\r\n",
  20374. "HTTP/1.0 200 Connection established\r\n"
  20375. "Connection: keep-alive\r\n"
  20376. "Transfer-Encoding: chunked\r\n"
  20377. "\r\n"
  20378. "5\r\nhello\r\n0\r\n\r\n"}) {
  20379. with_single_response(response, [&](Client &cli) {
  20380. cli.set_keep_alive(true);
  20381. auto res = cli.Get("/");
  20382. ASSERT_TRUE(res) << response;
  20383. EXPECT_EQ("hello", res->body);
  20384. EXPECT_FALSE(cli.is_socket_open()) << response;
  20385. });
  20386. }
  20387. }
  20388. // A payload max length of 0 means no limit, however the body is framed.
  20389. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20390. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20391. "Transfer-Encoding: chunked\r\n"
  20392. "\r\n"
  20393. "5\r\nhello\r\n0\r\n\r\n",
  20394. "HTTP/1.1 200 OK\r\n"
  20395. "Connection: close\r\n"
  20396. "\r\n"
  20397. "hello"}) {
  20398. with_single_response(response, [&](Client &cli) {
  20399. cli.set_payload_max_length(0);
  20400. auto res = cli.Get("/");
  20401. ASSERT_TRUE(res) << response;
  20402. EXPECT_EQ("hello", res->body) << response;
  20403. });
  20404. }
  20405. }
  20406. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20407. Server svr;
  20408. svr.set_payload_max_length(0);
  20409. svr.Post("/echo", [](const Request &req, Response &res) {
  20410. res.set_content(req.body, "text/plain");
  20411. });
  20412. auto port = svr.bind_to_any_port(HOST);
  20413. thread t = thread([&] { svr.listen_after_bind(); });
  20414. auto se = detail::scope_exit([&] {
  20415. svr.stop();
  20416. t.join();
  20417. ASSERT_FALSE(svr.is_running());
  20418. });
  20419. svr.wait_until_ready();
  20420. Client cli(HOST, port);
  20421. auto res = cli.Post(
  20422. "/echo",
  20423. [](size_t /*offset*/, DataSink &sink) {
  20424. sink.write("hello", 5);
  20425. sink.done();
  20426. return true;
  20427. },
  20428. "text/plain");
  20429. ASSERT_TRUE(res);
  20430. EXPECT_EQ(StatusCode::OK_200, res->status);
  20431. EXPECT_EQ("hello", res->body);
  20432. }
  20433. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20434. TEST_F(OpenStreamTest, Gzip) {
  20435. Client cli("127.0.0.1", port_);
  20436. auto handle = cli.open_stream("GET", "/compressible", {},
  20437. {{"Accept-Encoding", "gzip"}});
  20438. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20439. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20440. }
  20441. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20442. Client cli("127.0.0.1", port_);
  20443. auto handle =
  20444. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20445. {{"Accept-Encoding", "gzip"}});
  20446. ASSERT_TRUE(handle.is_valid());
  20447. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20448. EXPECT_EQ("123456789", read_all(handle));
  20449. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20450. }
  20451. #endif
  20452. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20453. TEST_F(OpenStreamTest, Brotli) {
  20454. Client cli("127.0.0.1", port_);
  20455. auto handle =
  20456. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20457. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20458. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20459. }
  20460. #endif
  20461. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20462. TEST_F(OpenStreamTest, Zstd) {
  20463. Client cli("127.0.0.1", port_);
  20464. auto handle = cli.open_stream("GET", "/compressible", {},
  20465. {{"Accept-Encoding", "zstd"}});
  20466. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20467. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20468. }
  20469. #endif
  20470. #ifdef CPPHTTPLIB_SSL_ENABLED
  20471. class SSLOpenStreamTest : public ::testing::Test {
  20472. protected:
  20473. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20474. void SetUp() override {
  20475. svr_.Get("/hello", [](const Request &, Response &res) {
  20476. res.set_content("Hello SSL World!", "text/plain");
  20477. });
  20478. svr_.Get("/chunked", [](const Request &, Response &res) {
  20479. res.set_chunked_content_provider("text/plain",
  20480. [](size_t offset, DataSink &sink) {
  20481. if (offset < 15) {
  20482. sink.write("chunk", 5);
  20483. return true;
  20484. }
  20485. sink.done();
  20486. return true;
  20487. });
  20488. });
  20489. svr_.Post("/echo", [](const Request &req, Response &res) {
  20490. res.set_content(req.body, req.get_header_value("Content-Type"));
  20491. });
  20492. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20493. std::string body = req.body;
  20494. res.set_chunked_content_provider(
  20495. "text/plain", [body](size_t offset, DataSink &sink) {
  20496. if (offset < body.size()) {
  20497. sink.write(body.data() + offset, body.size() - offset);
  20498. }
  20499. sink.done();
  20500. return true;
  20501. });
  20502. });
  20503. port_ = svr_.bind_to_any_port("127.0.0.1");
  20504. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20505. svr_.wait_until_ready();
  20506. }
  20507. void TearDown() override {
  20508. svr_.stop();
  20509. if (thread_.joinable()) thread_.join();
  20510. }
  20511. SSLServer svr_;
  20512. std::thread thread_;
  20513. int port_ = 0;
  20514. };
  20515. TEST_F(SSLOpenStreamTest, Basic) {
  20516. SSLClient cli("127.0.0.1", port_);
  20517. cli.enable_server_certificate_verification(false);
  20518. auto handle = cli.open_stream("GET", "/hello");
  20519. ASSERT_TRUE(handle.is_valid());
  20520. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20521. }
  20522. TEST_F(SSLOpenStreamTest, Chunked) {
  20523. SSLClient cli("127.0.0.1", port_);
  20524. cli.enable_server_certificate_verification(false);
  20525. auto handle = cli.open_stream("GET", "/chunked");
  20526. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20527. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20528. "Transfer-Encoding") == "chunked");
  20529. auto body = read_all(handle);
  20530. EXPECT_EQ("chunkchunkchunk", body);
  20531. }
  20532. TEST_F(SSLOpenStreamTest, Post) {
  20533. SSLClient cli("127.0.0.1", port_);
  20534. cli.enable_server_certificate_verification(false);
  20535. auto handle =
  20536. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20537. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20538. EXPECT_EQ(200, handle.response->status);
  20539. auto body = read_all(handle);
  20540. EXPECT_EQ("Hello SSL POST", body);
  20541. }
  20542. TEST_F(SSLOpenStreamTest, PostChunked) {
  20543. SSLClient cli("127.0.0.1", port_);
  20544. cli.enable_server_certificate_verification(false);
  20545. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20546. "Chunked SSL Data", "text/plain");
  20547. ASSERT_TRUE(handle.is_valid());
  20548. EXPECT_EQ(200, handle.response->status);
  20549. auto body = read_all(handle);
  20550. EXPECT_EQ("Chunked SSL Data", body);
  20551. }
  20552. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20553. // Content-Length is terminated by the server closing the connection. When the
  20554. // SSL peer sends a close_notify after the body, the client must treat it as a
  20555. // clean EOF and return a successful response rather than an error.
  20556. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20557. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20558. ASSERT_TRUE(svr.is_valid());
  20559. svr.set_keep_alive_max_count(1);
  20560. const std::string expected_body = "Hello from connection-close response!";
  20561. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20562. res.set_content_provider("text/plain",
  20563. [&](size_t offset, DataSink &sink) -> bool {
  20564. if (offset < expected_body.size()) {
  20565. sink.write(expected_body.data() + offset,
  20566. expected_body.size() - offset);
  20567. }
  20568. sink.done();
  20569. return true;
  20570. });
  20571. });
  20572. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20573. auto se = detail::scope_exit([&] {
  20574. svr.stop();
  20575. listen_thread.join();
  20576. ASSERT_FALSE(svr.is_running());
  20577. });
  20578. svr.wait_until_ready();
  20579. SSLClient cli(HOST, PORT);
  20580. cli.enable_server_certificate_verification(false);
  20581. auto res = cli.Get("/no-content-length");
  20582. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20583. EXPECT_EQ(StatusCode::OK_200, res->status);
  20584. EXPECT_EQ(expected_body, res->body);
  20585. }
  20586. #endif // CPPHTTPLIB_SSL_ENABLED
  20587. //==============================================================================
  20588. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20589. // results for various scenarios.
  20590. //==============================================================================
  20591. TEST(ParityTest, GetVsOpenStream) {
  20592. Server svr;
  20593. const std::string path = "/parity";
  20594. const std::string content = "Parity test content: hello world";
  20595. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20596. res.set_content(content, "text/plain");
  20597. });
  20598. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20599. auto se = detail::scope_exit([&] {
  20600. svr.stop();
  20601. t.join();
  20602. ASSERT_FALSE(svr.is_running());
  20603. });
  20604. svr.wait_until_ready();
  20605. Client cli(HOST, PORT);
  20606. // Non-stream path
  20607. auto r1 = cli.Get(path);
  20608. ASSERT_TRUE(r1);
  20609. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20610. // Stream path
  20611. auto h = cli.open_stream("GET", path);
  20612. ASSERT_TRUE(h.is_valid());
  20613. EXPECT_EQ(r1->body, read_all(h));
  20614. }
  20615. // Helper to compress data with provided compressor type T
  20616. template <typename Compressor>
  20617. static std::string compress_payload_for_parity(const std::string &in) {
  20618. std::string out;
  20619. Compressor compressor;
  20620. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20621. [&](const char *data, size_t n) {
  20622. out.append(data, n);
  20623. return true;
  20624. });
  20625. EXPECT_TRUE(ok);
  20626. return out;
  20627. }
  20628. // Helper function for compression parity tests
  20629. template <typename Compressor>
  20630. static void test_compression_parity(const std::string &original,
  20631. const std::string &path,
  20632. const std::string &encoding) {
  20633. const std::string compressed =
  20634. compress_payload_for_parity<Compressor>(original);
  20635. Server svr;
  20636. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20637. res.set_content(compressed, "application/octet-stream");
  20638. res.set_header("Content-Encoding", encoding);
  20639. });
  20640. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20641. auto se = detail::scope_exit([&] {
  20642. svr.stop();
  20643. t.join();
  20644. ASSERT_FALSE(svr.is_running());
  20645. });
  20646. svr.wait_until_ready();
  20647. Client cli(HOST, PORT);
  20648. // Non-streaming
  20649. {
  20650. auto res = cli.Get(path);
  20651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20652. EXPECT_EQ(StatusCode::OK_200, res->status);
  20653. EXPECT_EQ(original, res->body);
  20654. }
  20655. // Streaming
  20656. {
  20657. auto h = cli.open_stream("GET", path);
  20658. ASSERT_TRUE(h.is_valid());
  20659. EXPECT_EQ(original, read_all(h));
  20660. }
  20661. }
  20662. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20663. TEST(ParityTest, Gzip) {
  20664. test_compression_parity<detail::gzip_compressor>(
  20665. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20666. }
  20667. #endif
  20668. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20669. TEST(ParityTest, Brotli) {
  20670. test_compression_parity<detail::brotli_compressor>(
  20671. "Hello, brotli parity test payload", "/parity-br", "br");
  20672. }
  20673. #endif
  20674. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20675. TEST(ParityTest, Zstd) {
  20676. test_compression_parity<detail::zstd_compressor>(
  20677. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20678. }
  20679. #endif
  20680. //==============================================================================
  20681. // New Stream API Tests
  20682. //==============================================================================
  20683. inline std::string read_body(httplib::stream::Result &result) {
  20684. std::string body;
  20685. while (result.next()) {
  20686. body.append(result.data(), result.size());
  20687. }
  20688. return body;
  20689. }
  20690. TEST(ClientConnectionTest, Basic) {
  20691. httplib::ClientConnection conn;
  20692. EXPECT_FALSE(conn.is_open());
  20693. conn.sock = 1;
  20694. EXPECT_TRUE(conn.is_open());
  20695. httplib::ClientConnection conn2(std::move(conn));
  20696. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20697. conn2.sock = INVALID_SOCKET;
  20698. }
  20699. // Unified test server for all stream::* tests
  20700. class StreamApiTest : public ::testing::Test {
  20701. protected:
  20702. void SetUp() override {
  20703. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20704. res.set_content("Hello World!", "text/plain");
  20705. });
  20706. svr_.Get("/echo-params",
  20707. [](const httplib::Request &req, httplib::Response &res) {
  20708. std::string r;
  20709. for (const auto &p : req.params) {
  20710. if (!r.empty()) r += "&";
  20711. r += p.first + "=" + p.second;
  20712. }
  20713. res.set_content(r, "text/plain");
  20714. });
  20715. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20716. res.set_content(req.body, req.get_header_value("Content-Type"));
  20717. });
  20718. svr_.Post("/echo-headers",
  20719. [](const httplib::Request &req, httplib::Response &res) {
  20720. std::string r;
  20721. for (const auto &h : req.headers)
  20722. r += h.first + ": " + h.second + "\n";
  20723. res.set_content(r, "text/plain");
  20724. });
  20725. svr_.Post("/echo-params",
  20726. [](const httplib::Request &req, httplib::Response &res) {
  20727. std::string r = "params:";
  20728. for (const auto &p : req.params)
  20729. r += p.first + "=" + p.second + ";";
  20730. res.set_content(r + " body:" + req.body, "text/plain");
  20731. });
  20732. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20733. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20734. });
  20735. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20736. res.set_content("PUT:" + req.body, "text/plain");
  20737. });
  20738. svr_.Patch("/echo",
  20739. [](const httplib::Request &req, httplib::Response &res) {
  20740. res.set_content("PATCH:" + req.body, "text/plain");
  20741. });
  20742. svr_.Delete(
  20743. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20744. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20745. "text/plain");
  20746. });
  20747. svr_.Get("/head-test",
  20748. [](const httplib::Request &, httplib::Response &res) {
  20749. res.set_content("body for HEAD", "text/plain");
  20750. });
  20751. svr_.Options("/options",
  20752. [](const httplib::Request &, httplib::Response &res) {
  20753. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20754. });
  20755. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20756. svr_.wait_until_ready();
  20757. }
  20758. void TearDown() override {
  20759. svr_.stop();
  20760. if (thread_.joinable()) thread_.join();
  20761. }
  20762. httplib::Server svr_;
  20763. std::thread thread_;
  20764. };
  20765. // stream::Get tests
  20766. TEST_F(StreamApiTest, GetBasic) {
  20767. httplib::Client cli(HOST, PORT);
  20768. auto result = httplib::stream::Get(cli, "/hello");
  20769. ASSERT_TRUE(result.is_valid());
  20770. EXPECT_EQ(200, result.status());
  20771. EXPECT_EQ("Hello World!", read_body(result));
  20772. }
  20773. TEST_F(StreamApiTest, GetWithParams) {
  20774. httplib::Client cli(HOST, PORT);
  20775. httplib::Params params{{"foo", "bar"}};
  20776. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20777. ASSERT_TRUE(result.is_valid());
  20778. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20779. }
  20780. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20781. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20782. httplib::Client cli(HOST, PORT);
  20783. cli.set_payload_max_length(0);
  20784. auto result = httplib::stream::Get(cli, "/hello");
  20785. ASSERT_TRUE(result.is_valid());
  20786. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20787. EXPECT_EQ("Hello World!", read_body(result));
  20788. }
  20789. #endif
  20790. TEST_F(StreamApiTest, GetConnectionError) {
  20791. httplib::Client cli(HOST, 9999);
  20792. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20793. }
  20794. TEST_F(StreamApiTest, Get404) {
  20795. httplib::Client cli(HOST, PORT);
  20796. auto result = httplib::stream::Get(cli, "/nonexistent");
  20797. EXPECT_TRUE(result.is_valid());
  20798. EXPECT_EQ(404, result.status());
  20799. }
  20800. // stream::Post tests
  20801. TEST_F(StreamApiTest, PostBasic) {
  20802. httplib::Client cli(HOST, PORT);
  20803. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20804. "application/json");
  20805. ASSERT_TRUE(result.is_valid());
  20806. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20807. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20808. }
  20809. TEST_F(StreamApiTest, PostWithHeaders) {
  20810. httplib::Client cli(HOST, PORT);
  20811. httplib::Headers headers{{"X-Custom", "value"}};
  20812. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20813. "text/plain");
  20814. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20815. }
  20816. TEST_F(StreamApiTest, PostWithParams) {
  20817. httplib::Client cli(HOST, PORT);
  20818. httplib::Params params{{"k", "v"}};
  20819. auto result =
  20820. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20821. auto body = read_body(result);
  20822. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20823. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20824. }
  20825. TEST_F(StreamApiTest, PostLarge) {
  20826. httplib::Client cli(HOST, PORT);
  20827. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20828. size_t total = 0;
  20829. while (result.next()) {
  20830. total += result.size();
  20831. }
  20832. EXPECT_EQ(100u * 1024u, total);
  20833. }
  20834. // stream::Put/Patch tests
  20835. TEST_F(StreamApiTest, PutAndPatch) {
  20836. httplib::Client cli(HOST, PORT);
  20837. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20838. EXPECT_EQ("PUT:test", read_body(put));
  20839. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20840. EXPECT_EQ("PATCH:test", read_body(patch));
  20841. }
  20842. // stream::Delete tests
  20843. TEST_F(StreamApiTest, Delete) {
  20844. httplib::Client cli(HOST, PORT);
  20845. auto del1 = httplib::stream::Delete(cli, "/resource");
  20846. EXPECT_EQ("Deleted", read_body(del1));
  20847. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20848. EXPECT_EQ("Deleted:data", read_body(del2));
  20849. }
  20850. // stream::Head/Options tests
  20851. TEST_F(StreamApiTest, HeadAndOptions) {
  20852. httplib::Client cli(HOST, PORT);
  20853. auto head = httplib::stream::Head(cli, "/head-test");
  20854. EXPECT_TRUE(head.is_valid());
  20855. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20856. auto opts = httplib::stream::Options(cli, "/options");
  20857. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20858. }
  20859. // SSL stream::* tests
  20860. #ifdef CPPHTTPLIB_SSL_ENABLED
  20861. class SSLStreamApiTest : public ::testing::Test {
  20862. protected:
  20863. void SetUp() override {
  20864. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20865. res.set_content("Hello SSL!", "text/plain");
  20866. });
  20867. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20868. res.set_content(req.body, "text/plain");
  20869. });
  20870. port_ = svr_.bind_to_any_port("127.0.0.1");
  20871. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20872. svr_.wait_until_ready();
  20873. }
  20874. void TearDown() override {
  20875. svr_.stop();
  20876. if (thread_.joinable()) thread_.join();
  20877. }
  20878. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20879. std::thread thread_;
  20880. int port_ = 0;
  20881. };
  20882. TEST_F(SSLStreamApiTest, GetAndPost) {
  20883. httplib::SSLClient cli("127.0.0.1", port_);
  20884. cli.enable_server_certificate_verification(false);
  20885. auto get = httplib::stream::Get(cli, "/hello");
  20886. EXPECT_EQ("Hello SSL!", read_body(get));
  20887. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20888. EXPECT_EQ("test", read_body(post));
  20889. }
  20890. #endif
  20891. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20892. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20893. // BodyReader
  20894. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20895. // Test that read timeout during streaming is detected
  20896. // Use a large content-length response where server delays mid-stream
  20897. Server svr;
  20898. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20899. // Send a large response with delay in the middle
  20900. res.set_content_provider(
  20901. 1000, // content_length
  20902. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20903. if (offset < 100) {
  20904. // Send first 100 bytes immediately
  20905. std::string data(100, 'A');
  20906. sink.write(data.c_str(), data.size());
  20907. return true;
  20908. }
  20909. // Then delay longer than client timeout
  20910. std::this_thread::sleep_for(std::chrono::seconds(3));
  20911. std::string data(900, 'B');
  20912. sink.write(data.c_str(), data.size());
  20913. return true;
  20914. });
  20915. });
  20916. auto port = 8091;
  20917. std::thread t([&]() { svr.listen("localhost", port); });
  20918. svr.wait_until_ready();
  20919. Client cli("localhost", port);
  20920. cli.set_read_timeout(1, 0); // 1 second timeout
  20921. auto handle = cli.open_stream("GET", "/slow-stream");
  20922. ASSERT_TRUE(handle.is_valid());
  20923. char buf[256];
  20924. ssize_t total = 0;
  20925. ssize_t n;
  20926. bool got_error = false;
  20927. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20928. total += n;
  20929. }
  20930. if (n < 0) {
  20931. got_error = true;
  20932. // Should be timeout or read error
  20933. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20934. handle.get_read_error() == Error::Read)
  20935. << "Actual error: " << to_string(handle.get_read_error());
  20936. }
  20937. // Either we got an error, or we got less data than expected
  20938. EXPECT_TRUE(got_error || total < 1000)
  20939. << "Expected timeout but got all " << total << " bytes";
  20940. svr.stop();
  20941. t.join();
  20942. }
  20943. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20944. // Test connection closed detection via BodyReader
  20945. Server svr;
  20946. std::atomic<bool> close_now{false};
  20947. svr.Get("/will-close", [&](const Request &, Response &res) {
  20948. res.set_content_provider(
  20949. 10000, // Large content_length that we won't fully send
  20950. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20951. if (offset < 100) {
  20952. std::string data(100, 'X');
  20953. sink.write(data.c_str(), data.size());
  20954. return true;
  20955. }
  20956. // Wait for signal then abort
  20957. while (!close_now) {
  20958. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20959. }
  20960. return false; // Abort - server will close connection
  20961. });
  20962. });
  20963. auto port = 8092;
  20964. std::thread t([&]() { svr.listen("localhost", port); });
  20965. svr.wait_until_ready();
  20966. Client cli("localhost", port);
  20967. auto handle = cli.open_stream("GET", "/will-close");
  20968. ASSERT_TRUE(handle.is_valid());
  20969. char buf[256];
  20970. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20971. EXPECT_GT(n, 0) << "First read should succeed";
  20972. // Signal server to close
  20973. close_now = true;
  20974. // Keep reading until error or EOF
  20975. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20976. // Keep reading
  20977. }
  20978. // Should get an error since content_length wasn't satisfied
  20979. if (n < 0) {
  20980. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20981. handle.get_read_error() == Error::Read)
  20982. << "Actual error: " << to_string(handle.get_read_error());
  20983. }
  20984. svr.stop();
  20985. t.join();
  20986. }
  20987. #ifdef CPPHTTPLIB_SSL_ENABLED
  20988. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20989. // Test that read timeout during SSL streaming is detected
  20990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20991. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20992. res.set_content_provider(
  20993. 1000, "text/plain",
  20994. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20995. if (offset < 100) {
  20996. std::string data(100, 'A');
  20997. sink.write(data.c_str(), data.size());
  20998. return true;
  20999. }
  21000. std::this_thread::sleep_for(std::chrono::seconds(3));
  21001. std::string data(900, 'B');
  21002. sink.write(data.c_str(), data.size());
  21003. return true;
  21004. });
  21005. });
  21006. auto port = 8093;
  21007. std::thread t([&]() { svr.listen("localhost", port); });
  21008. svr.wait_until_ready();
  21009. SSLClient cli("localhost", port);
  21010. cli.enable_server_certificate_verification(false);
  21011. cli.set_read_timeout(1, 0); // 1 second timeout
  21012. auto handle = cli.open_stream("GET", "/slow-stream");
  21013. ASSERT_TRUE(handle.is_valid());
  21014. char buf[256];
  21015. ssize_t total = 0;
  21016. ssize_t n;
  21017. bool got_error = false;
  21018. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21019. total += n;
  21020. }
  21021. if (n < 0) {
  21022. got_error = true;
  21023. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21024. handle.get_read_error() == Error::Read)
  21025. << "Actual error: " << to_string(handle.get_read_error());
  21026. }
  21027. EXPECT_TRUE(got_error || total < 1000)
  21028. << "Expected timeout but got all " << total << " bytes";
  21029. svr.stop();
  21030. t.join();
  21031. }
  21032. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21033. // Test SSL connection closed detection
  21034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21035. std::atomic<bool> close_now{false};
  21036. svr.Get("/will-close", [&](const Request &, Response &res) {
  21037. res.set_content_provider(
  21038. 10000, "text/plain",
  21039. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21040. if (offset < 100) {
  21041. std::string data(100, 'X');
  21042. sink.write(data.c_str(), data.size());
  21043. return true;
  21044. }
  21045. while (!close_now) {
  21046. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21047. }
  21048. return false;
  21049. });
  21050. });
  21051. auto port = 8094;
  21052. std::thread t([&]() { svr.listen("localhost", port); });
  21053. svr.wait_until_ready();
  21054. SSLClient cli("localhost", port);
  21055. cli.enable_server_certificate_verification(false);
  21056. auto handle = cli.open_stream("GET", "/will-close");
  21057. ASSERT_TRUE(handle.is_valid());
  21058. char buf[256];
  21059. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21060. EXPECT_GT(n, 0);
  21061. // Signal server to close
  21062. close_now = true;
  21063. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21064. // Keep reading
  21065. }
  21066. if (n < 0) {
  21067. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21068. handle.get_read_error() == Error::Read)
  21069. << "Actual error: " << to_string(handle.get_read_error());
  21070. }
  21071. svr.stop();
  21072. t.join();
  21073. }
  21074. #endif
  21075. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21076. using namespace httplib;
  21077. // Create a test file
  21078. const char *fname = "etag_testfile.txt";
  21079. const char *content = "etag-content";
  21080. {
  21081. std::ofstream ofs(fname);
  21082. ofs << content;
  21083. ASSERT_TRUE(ofs.good());
  21084. }
  21085. Server svr;
  21086. svr.set_mount_point("/static", ".");
  21087. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21088. svr.wait_until_ready();
  21089. Client cli(HOST, PORT);
  21090. // First request: should get 200 with ETag header
  21091. auto res1 = cli.Get("/static/etag_testfile.txt");
  21092. ASSERT_TRUE(res1);
  21093. ASSERT_EQ(200, res1->status);
  21094. ASSERT_TRUE(res1->has_header("ETag"));
  21095. std::string etag = res1->get_header_value("ETag");
  21096. EXPECT_FALSE(etag.empty());
  21097. // Verify ETag format: W/"hex-hex"
  21098. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21099. EXPECT_EQ('W', etag[0]);
  21100. EXPECT_EQ('/', etag[1]);
  21101. EXPECT_EQ('"', etag[2]);
  21102. EXPECT_EQ('"', etag.back());
  21103. // Exact match: expect 304 Not Modified
  21104. Headers h2 = {{"If-None-Match", etag}};
  21105. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21106. ASSERT_TRUE(res2);
  21107. EXPECT_EQ(304, res2->status);
  21108. // Wildcard match: expect 304 Not Modified
  21109. Headers h3 = {{"If-None-Match", "*"}};
  21110. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21111. ASSERT_TRUE(res3);
  21112. EXPECT_EQ(304, res3->status);
  21113. // Non-matching ETag: expect 200
  21114. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21115. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21116. ASSERT_TRUE(res4);
  21117. EXPECT_EQ(200, res4->status);
  21118. // Multiple ETags with one matching: expect 304
  21119. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21120. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21121. ASSERT_TRUE(res5);
  21122. EXPECT_EQ(304, res5->status);
  21123. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21124. // that equivalent to the single comma-separated list above, so the match on
  21125. // the second line must still be found.
  21126. Headers h6;
  21127. h6.emplace("If-None-Match", "W/\"other\"");
  21128. h6.emplace("If-None-Match", etag);
  21129. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21130. ASSERT_TRUE(res6);
  21131. EXPECT_EQ(304, res6->status);
  21132. svr.stop();
  21133. t.join();
  21134. std::remove(fname);
  21135. }
  21136. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21137. using namespace httplib;
  21138. Server svr;
  21139. svr.set_mount_point("/static", ".");
  21140. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21141. svr.wait_until_ready();
  21142. Client cli(HOST, PORT);
  21143. // Send If-None-Match: * to a non-existent file
  21144. Headers h = {{"If-None-Match", "*"}};
  21145. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21147. EXPECT_EQ(404, res->status);
  21148. svr.stop();
  21149. t.join();
  21150. }
  21151. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21152. using namespace httplib;
  21153. // Create a test file
  21154. const char *fname = "etag_boundary_testfile.txt";
  21155. const char *content = "boundary-test";
  21156. {
  21157. std::ofstream ofs(fname);
  21158. ofs << content;
  21159. ASSERT_TRUE(ofs.good());
  21160. }
  21161. Server svr;
  21162. svr.set_mount_point("/static", ".");
  21163. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21164. svr.wait_until_ready();
  21165. Client cli(HOST, PORT);
  21166. // Get the actual ETag
  21167. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21168. ASSERT_TRUE(res1);
  21169. ASSERT_EQ(200, res1->status);
  21170. ASSERT_TRUE(res1->has_header("ETag"));
  21171. std::string etag = res1->get_header_value("ETag");
  21172. // Test 1: Very long ETag value (longer than actual ETag)
  21173. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21174. Headers h1 = {{"If-None-Match", "W/"
  21175. "\"very-long-etag-value-that-is-much-longer-"
  21176. "than-the-actual-etag-value\""}};
  21177. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21178. ASSERT_TRUE(res2);
  21179. EXPECT_EQ(200, res2->status); // Should not match
  21180. // Test 2: Long string followed by wildcard
  21181. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21182. // string)
  21183. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21184. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21185. ASSERT_TRUE(res3);
  21186. EXPECT_EQ(304, res3->status); // Should match on "*"
  21187. // Test 3: Wildcard followed by long string
  21188. // Should match on "*" immediately and return 304
  21189. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21190. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21191. ASSERT_TRUE(res4);
  21192. EXPECT_EQ(304, res4->status); // Should match on "*"
  21193. // Test 4: Multiple long non-matching values
  21194. // Should NOT match and return 200 (test that all comparisons are safe)
  21195. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21196. "W/\"second-long-non-matching-value\", "
  21197. "W/\"third-long-non-matching-value\""}};
  21198. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21199. ASSERT_TRUE(res5);
  21200. EXPECT_EQ(200, res5->status); // Should not match
  21201. // Test 5: Single character that is not "*" (edge case)
  21202. Headers h5 = {{"If-None-Match", "X"}};
  21203. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21204. ASSERT_TRUE(res6);
  21205. EXPECT_EQ(200, res6->status); // Should not match
  21206. svr.stop();
  21207. t.join();
  21208. std::remove(fname);
  21209. }
  21210. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21211. using namespace httplib;
  21212. // Create a test file
  21213. const char *fname = "ims_testfile.txt";
  21214. const char *content = "if-modified-since-test";
  21215. {
  21216. std::ofstream ofs(fname);
  21217. ofs << content;
  21218. ASSERT_TRUE(ofs.good());
  21219. }
  21220. Server svr;
  21221. svr.set_mount_point("/static", ".");
  21222. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21223. svr.wait_until_ready();
  21224. Client cli(HOST, PORT);
  21225. // First request: should get 200 with Last-Modified header
  21226. auto res1 = cli.Get("/static/ims_testfile.txt");
  21227. ASSERT_TRUE(res1);
  21228. ASSERT_EQ(200, res1->status);
  21229. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21230. std::string last_modified = res1->get_header_value("Last-Modified");
  21231. EXPECT_FALSE(last_modified.empty());
  21232. // If-Modified-Since with same time: expect 304
  21233. Headers h2 = {{"If-Modified-Since", last_modified}};
  21234. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21235. ASSERT_TRUE(res2);
  21236. EXPECT_EQ(304, res2->status);
  21237. // If-Modified-Since with future time: expect 304
  21238. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21239. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21240. ASSERT_TRUE(res3);
  21241. EXPECT_EQ(304, res3->status);
  21242. // If-Modified-Since with past time: expect 200
  21243. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21244. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21245. ASSERT_TRUE(res4);
  21246. EXPECT_EQ(200, res4->status);
  21247. // If-None-Match takes precedence over If-Modified-Since
  21248. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21249. ASSERT_TRUE(res1->has_header("ETag"));
  21250. std::string etag = res1->get_header_value("ETag");
  21251. Headers h5 = {{"If-None-Match", etag},
  21252. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21253. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21254. ASSERT_TRUE(res5);
  21255. EXPECT_EQ(304, res5->status);
  21256. svr.stop();
  21257. t.join();
  21258. std::remove(fname);
  21259. }
  21260. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21261. using namespace httplib;
  21262. Server svr;
  21263. // Endpoint that returns compressible content
  21264. svr.Get("/compressible", [](const Request &, Response &res) {
  21265. // Return a large enough body to trigger compression
  21266. std::string body(1000, 'a');
  21267. res.set_content(body, "text/plain");
  21268. });
  21269. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21270. svr.wait_until_ready();
  21271. Client cli(HOST, PORT);
  21272. // Request with gzip support: should get Vary header when compressed
  21273. cli.set_compress(true);
  21274. auto res1 = cli.Get("/compressible");
  21275. ASSERT_TRUE(res1);
  21276. EXPECT_EQ(200, res1->status);
  21277. // If Content-Encoding is set, Vary should also be set
  21278. if (res1->has_header("Content-Encoding")) {
  21279. EXPECT_TRUE(res1->has_header("Vary"));
  21280. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21281. }
  21282. // Request without Accept-Encoding header: should not have compression
  21283. Headers h_no_compress;
  21284. auto res2 = cli.Get("/compressible", h_no_compress);
  21285. ASSERT_TRUE(res2);
  21286. EXPECT_EQ(200, res2->status);
  21287. // Verify Vary header is present when compression is applied
  21288. // (the exact behavior depends on server configuration)
  21289. svr.stop();
  21290. t.join();
  21291. }
  21292. TEST(ETagTest, IfRangeWithETag) {
  21293. using namespace httplib;
  21294. // Create a test file with known content
  21295. const char *fname = "if_range_testfile.txt";
  21296. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21297. {
  21298. std::ofstream ofs(fname);
  21299. ofs << content;
  21300. ASSERT_TRUE(ofs.good());
  21301. }
  21302. Server svr;
  21303. svr.set_mount_point("/static", ".");
  21304. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21305. svr.wait_until_ready();
  21306. Client cli(HOST, PORT);
  21307. // First request: get ETag
  21308. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21309. ASSERT_TRUE(res1);
  21310. ASSERT_EQ(200, res1->status);
  21311. ASSERT_TRUE(res1->has_header("ETag"));
  21312. std::string etag = res1->get_header_value("ETag");
  21313. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21314. // Since our server generates weak ETags (W/"..."), If-Range with our
  21315. // ETag should NOT result in partial content - it should return full content.
  21316. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21317. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21318. ASSERT_TRUE(res2);
  21319. // Weak ETag in If-Range -> full content (200), not partial (206)
  21320. EXPECT_EQ(200, res2->status);
  21321. EXPECT_EQ(content, res2->body);
  21322. EXPECT_FALSE(res2->has_header("Content-Range"));
  21323. // Range request with non-matching If-Range (ETag): should get 200 (full
  21324. // content)
  21325. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21326. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21327. ASSERT_TRUE(res3);
  21328. EXPECT_EQ(200, res3->status);
  21329. EXPECT_EQ(content, res3->body);
  21330. EXPECT_FALSE(res3->has_header("Content-Range"));
  21331. // Range request with strong ETag (hypothetical - our server doesn't generate
  21332. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21333. // should return full content)
  21334. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21335. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21336. ASSERT_TRUE(res4);
  21337. EXPECT_EQ(200, res4->status);
  21338. EXPECT_EQ(content, res4->body);
  21339. EXPECT_FALSE(res4->has_header("Content-Range"));
  21340. svr.stop();
  21341. t.join();
  21342. std::remove(fname);
  21343. }
  21344. TEST(ETagTest, IfRangeWithDate) {
  21345. using namespace httplib;
  21346. // Create a test file
  21347. const char *fname = "if_range_date_testfile.txt";
  21348. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21349. {
  21350. std::ofstream ofs(fname);
  21351. ofs << content;
  21352. ASSERT_TRUE(ofs.good());
  21353. }
  21354. Server svr;
  21355. svr.set_mount_point("/static", ".");
  21356. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21357. svr.wait_until_ready();
  21358. Client cli(HOST, PORT);
  21359. // First request: get Last-Modified
  21360. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21361. ASSERT_TRUE(res1);
  21362. ASSERT_EQ(200, res1->status);
  21363. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21364. std::string last_modified = res1->get_header_value("Last-Modified");
  21365. // Range request with matching If-Range (date): should get 206
  21366. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21367. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21368. ASSERT_TRUE(res2);
  21369. EXPECT_EQ(206, res2->status);
  21370. EXPECT_EQ("FGHIJ", res2->body);
  21371. // Range request with old If-Range date: should get 200 (full content)
  21372. Headers h3 = {{"Range", "bytes=5-9"},
  21373. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21374. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21375. ASSERT_TRUE(res3);
  21376. EXPECT_EQ(200, res3->status);
  21377. EXPECT_EQ(content, res3->body);
  21378. // Range request with future If-Range date: should get 206
  21379. Headers h4 = {{"Range", "bytes=0-4"},
  21380. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21381. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21382. ASSERT_TRUE(res4);
  21383. EXPECT_EQ(206, res4->status);
  21384. EXPECT_EQ("ABCDE", res4->body);
  21385. svr.stop();
  21386. t.join();
  21387. std::remove(fname);
  21388. }
  21389. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21390. using namespace httplib;
  21391. const char *fname = "etag_malformed.txt";
  21392. const char *content = "malformed-etag";
  21393. {
  21394. std::ofstream ofs(fname);
  21395. ofs << content;
  21396. ASSERT_TRUE(ofs.good());
  21397. }
  21398. Server svr;
  21399. svr.set_mount_point("/static", ".");
  21400. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21401. svr.wait_until_ready();
  21402. Client cli(HOST, PORT);
  21403. // baseline: should get 200 and an ETag
  21404. auto res1 = cli.Get("/static/etag_malformed.txt");
  21405. ASSERT_TRUE(res1);
  21406. ASSERT_EQ(200, res1->status);
  21407. ASSERT_TRUE(res1->has_header("ETag"));
  21408. // Malformed ETag value (missing quotes) should be treated as non-matching
  21409. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21410. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21411. ASSERT_TRUE(res_bad);
  21412. EXPECT_EQ(200, res_bad->status);
  21413. // Whitespace-only header value should be considered invalid / non-matching
  21414. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21415. "Host: localhost\r\n"
  21416. "If-None-Match: \r\n"
  21417. "Connection: close\r\n"
  21418. "\r\n";
  21419. std::string out;
  21420. ASSERT_TRUE(send_request(5, raw_req, &out));
  21421. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21422. svr.stop();
  21423. t.join();
  21424. std::remove(fname);
  21425. }
  21426. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21427. using namespace httplib;
  21428. const char *fname = "ims_invalid_format.txt";
  21429. const char *content = "ims-bad-format";
  21430. {
  21431. std::ofstream ofs(fname);
  21432. ofs << content;
  21433. ASSERT_TRUE(ofs.good());
  21434. }
  21435. Server svr;
  21436. svr.set_mount_point("/static", ".");
  21437. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21438. svr.wait_until_ready();
  21439. Client cli(HOST, PORT);
  21440. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21441. ASSERT_TRUE(res1);
  21442. ASSERT_EQ(200, res1->status);
  21443. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21444. // If-Modified-Since with invalid format should not result in 304
  21445. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21446. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21447. ASSERT_TRUE(res_bad);
  21448. EXPECT_EQ(200, res_bad->status);
  21449. // If-Range with invalid date format should be treated as mismatch -> full
  21450. // content (200)
  21451. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21452. {"If-Range", "invalid-date"}};
  21453. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21454. ASSERT_TRUE(res_ifrange);
  21455. EXPECT_EQ(200, res_ifrange->status);
  21456. svr.stop();
  21457. t.join();
  21458. std::remove(fname);
  21459. }
  21460. TEST(ETagTest, IfRangeWithMalformedETag) {
  21461. using namespace httplib;
  21462. const char *fname = "ifrange_malformed.txt";
  21463. const std::string content = "0123456789";
  21464. {
  21465. std::ofstream ofs(fname);
  21466. ofs << content;
  21467. ASSERT_TRUE(ofs.good());
  21468. }
  21469. Server svr;
  21470. svr.set_mount_point("/static", ".");
  21471. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21472. svr.wait_until_ready();
  21473. Client cli(HOST, PORT);
  21474. // First request: get ETag
  21475. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21476. ASSERT_TRUE(res1);
  21477. ASSERT_EQ(200, res1->status);
  21478. ASSERT_TRUE(res1->has_header("ETag"));
  21479. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21480. // full content (200)
  21481. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21482. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21483. ASSERT_TRUE(res2);
  21484. EXPECT_EQ(200, res2->status);
  21485. EXPECT_EQ(content, res2->body);
  21486. svr.stop();
  21487. t.join();
  21488. std::remove(fname);
  21489. }
  21490. TEST(ETagTest, ExtremeLargeDateValues) {
  21491. using namespace httplib;
  21492. const char *fname = "ims_extreme_date.txt";
  21493. const char *content = "ims-extreme-date";
  21494. {
  21495. std::ofstream ofs(fname);
  21496. ofs << content;
  21497. ASSERT_TRUE(ofs.good());
  21498. }
  21499. Server svr;
  21500. svr.set_mount_point("/static", ".");
  21501. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21502. svr.wait_until_ready();
  21503. Client cli(HOST, PORT);
  21504. auto res1 = cli.Get(std::string("/static/") + fname);
  21505. ASSERT_TRUE(res1);
  21506. ASSERT_EQ(200, res1->status);
  21507. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21508. // Extremely large year that may overflow date parsing routines.
  21509. Headers h_large_date = {
  21510. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21511. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21512. ASSERT_TRUE(res_bad);
  21513. // Expect server to treat this as invalid/mismatch and return full content
  21514. EXPECT_EQ(200, res_bad->status);
  21515. // If-Range with extremely large date should be treated as mismatch -> full
  21516. // content (200)
  21517. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21518. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21519. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21520. ASSERT_TRUE(res_ifrange);
  21521. EXPECT_EQ(200, res_ifrange->status);
  21522. svr.stop();
  21523. t.join();
  21524. std::remove(fname);
  21525. }
  21526. TEST(ETagTest, NegativeFileModificationTime) {
  21527. using namespace httplib;
  21528. const char *fname = "ims_negative_mtime.txt";
  21529. const std::string content = "negative-mtime";
  21530. {
  21531. std::ofstream ofs(fname);
  21532. ofs << content;
  21533. ASSERT_TRUE(ofs.good());
  21534. }
  21535. // Try to set file mtime to a negative value. This may fail on some
  21536. // platforms/filesystems; if it fails, the test will still verify server
  21537. // behaves safely by performing a regular conditional request.
  21538. #if defined(__APPLE__) || defined(__linux__)
  21539. bool set_negative = false;
  21540. do {
  21541. struct timeval times[2];
  21542. // access time: now
  21543. times[0].tv_sec = time(nullptr);
  21544. times[0].tv_usec = 0;
  21545. // modification time: negative (e.g., -1)
  21546. times[1].tv_sec = -1;
  21547. times[1].tv_usec = 0;
  21548. if (utimes(fname, times) == 0) { set_negative = true; }
  21549. } while (0);
  21550. #else
  21551. bool set_negative = false;
  21552. #endif
  21553. Server svr;
  21554. svr.set_mount_point("/static", ".");
  21555. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21556. svr.wait_until_ready();
  21557. Client cli(HOST, PORT);
  21558. auto res1 = cli.Get(std::string("/static/") + fname);
  21559. ASSERT_TRUE(res1);
  21560. ASSERT_EQ(200, res1->status);
  21561. bool has_last_modified = res1->has_header("Last-Modified");
  21562. std::string last_modified;
  21563. if (has_last_modified) {
  21564. last_modified = res1->get_header_value("Last-Modified");
  21565. }
  21566. if (set_negative) {
  21567. // If we successfully set a negative mtime, ensure server returns a
  21568. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21569. // with an old date and ensure server handles it without crash.
  21570. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21571. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21572. ASSERT_TRUE(res2);
  21573. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21574. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21575. } else {
  21576. // Could not set negative mtime on this platform; fall back to verifying
  21577. // that normal invalid/malformed dates are treated safely (non-304).
  21578. Headers h_bad_date = {
  21579. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21580. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21581. ASSERT_TRUE(res_bad);
  21582. EXPECT_EQ(200, res_bad->status);
  21583. }
  21584. svr.stop();
  21585. t.join();
  21586. std::remove(fname);
  21587. }
  21588. //==============================================================================
  21589. // Integration Tests with Server
  21590. //==============================================================================
  21591. class SSEIntegrationTest : public ::testing::Test {
  21592. protected:
  21593. void SetUp() override {
  21594. stop_server_.store(false);
  21595. events_.clear();
  21596. server_ = httplib::detail::make_unique<Server>();
  21597. setup_server();
  21598. start_server();
  21599. }
  21600. void TearDown() override {
  21601. stop_server_.store(true);
  21602. event_cv_.notify_all();
  21603. server_->stop();
  21604. if (server_thread_.joinable()) { server_thread_.join(); }
  21605. }
  21606. void setup_server() {
  21607. // Simple SSE endpoint
  21608. server_->Get("/events", [this](const Request &req, Response &res) {
  21609. auto last_id = req.get_header_value("Last-Event-ID");
  21610. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21611. res.set_chunked_content_provider(
  21612. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21613. std::unique_lock<std::mutex> lock(event_mutex_);
  21614. if (event_cv_.wait_for(
  21615. lock, std::chrono::milliseconds(200), [this] {
  21616. return !events_.empty() || stop_server_.load();
  21617. })) {
  21618. if (stop_server_.load()) { return false; }
  21619. if (!events_.empty()) {
  21620. std::string event = events_.front();
  21621. events_.erase(events_.begin());
  21622. sink.write(event.data(), event.size());
  21623. return true;
  21624. }
  21625. }
  21626. return !stop_server_.load();
  21627. });
  21628. });
  21629. // Endpoint that returns error
  21630. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21631. res.status = 500;
  21632. res.set_content("Internal Server Error", "text/plain");
  21633. });
  21634. // Endpoint for custom event types
  21635. server_->Get("/custom-events", [](const Request &, Response &res) {
  21636. res.set_chunked_content_provider(
  21637. "text/event-stream", [](size_t offset, DataSink &sink) {
  21638. if (offset == 0) {
  21639. std::string event = "event: update\ndata: updated\n\n"
  21640. "event: delete\ndata: deleted\n\n";
  21641. sink.write(event.data(), event.size());
  21642. }
  21643. return false; // End stream after sending
  21644. });
  21645. });
  21646. }
  21647. void start_server() {
  21648. port_ = server_->bind_to_any_port(HOST);
  21649. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21650. // Wait for server to start
  21651. while (!server_->is_running()) {
  21652. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21653. }
  21654. }
  21655. int get_port() const { return port_; }
  21656. void send_event(const std::string &event) {
  21657. std::lock_guard<std::mutex> lock(event_mutex_);
  21658. events_.push_back(event);
  21659. event_cv_.notify_all();
  21660. }
  21661. std::unique_ptr<Server> server_;
  21662. std::thread server_thread_;
  21663. std::mutex event_mutex_;
  21664. std::condition_variable event_cv_;
  21665. std::vector<std::string> events_;
  21666. std::atomic<bool> stop_server_{false};
  21667. std::string last_received_event_id_;
  21668. int port_ = 0;
  21669. };
  21670. //==============================================================================
  21671. // SSE Parsing Tests
  21672. //==============================================================================
  21673. class SSEParsingTest : public SSEIntegrationTest {
  21674. protected:
  21675. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21676. // A trailing sentinel event tells when the whole stream has been parsed.
  21677. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21678. auto body = stream + "event: end\ndata: end\n\n";
  21679. server_->Get("/parse", [body](const Request &, Response &res) {
  21680. res.set_content(body, "text/event-stream");
  21681. });
  21682. return collect("/parse");
  21683. }
  21684. // Runs SSEClient against path until an "end" event arrives and returns the
  21685. // messages dispatched before it
  21686. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21687. Client client(HOST, get_port());
  21688. sse::SSEClient sse(client, path);
  21689. std::mutex mutex;
  21690. std::condition_variable cv;
  21691. std::vector<sse::SSEMessage> messages;
  21692. auto done = false;
  21693. sse.on_message([&](const sse::SSEMessage &msg) {
  21694. std::lock_guard<std::mutex> lock(mutex);
  21695. // Ignore a replay from a reconnect that races with stop()
  21696. if (!done) { messages.push_back(msg); }
  21697. });
  21698. sse.on_event("end", [&](const sse::SSEMessage &) {
  21699. std::lock_guard<std::mutex> lock(mutex);
  21700. done = true;
  21701. cv.notify_all();
  21702. });
  21703. sse.set_reconnect_interval(100);
  21704. sse.start_async();
  21705. {
  21706. std::unique_lock<std::mutex> lock(mutex);
  21707. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21708. }
  21709. sse.stop();
  21710. EXPECT_TRUE(done);
  21711. return messages;
  21712. }
  21713. };
  21714. TEST_F(SSEParsingTest, SingleLineData) {
  21715. auto msgs = parse("data: hello\n\n");
  21716. ASSERT_EQ(msgs.size(), 1u);
  21717. EXPECT_EQ(msgs[0].data, "hello");
  21718. EXPECT_EQ(msgs[0].event, "message");
  21719. }
  21720. TEST_F(SSEParsingTest, MultiLineData) {
  21721. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21722. ASSERT_EQ(msgs.size(), 1u);
  21723. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21724. }
  21725. TEST_F(SSEParsingTest, CustomEventType) {
  21726. auto msgs = parse("event: update\ndata: payload\n\n");
  21727. ASSERT_EQ(msgs.size(), 1u);
  21728. EXPECT_EQ(msgs[0].event, "update");
  21729. EXPECT_EQ(msgs[0].data, "payload");
  21730. }
  21731. TEST_F(SSEParsingTest, EventIdHandling) {
  21732. auto msgs = parse("id: 12345\ndata: test\n\n");
  21733. ASSERT_EQ(msgs.size(), 1u);
  21734. EXPECT_EQ(msgs[0].id, "12345");
  21735. }
  21736. TEST_F(SSEParsingTest, EmptyEventId) {
  21737. auto msgs = parse("id:\ndata: test\n\n");
  21738. ASSERT_EQ(msgs.size(), 1u);
  21739. EXPECT_EQ(msgs[0].id, "");
  21740. }
  21741. TEST_F(SSEParsingTest, CommentsIgnored) {
  21742. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21743. ASSERT_EQ(msgs.size(), 1u);
  21744. EXPECT_EQ(msgs[0].data, "hello");
  21745. EXPECT_EQ(msgs[0].event, "message");
  21746. }
  21747. TEST_F(SSEParsingTest, ColonInValue) {
  21748. auto msgs = parse("data: hello:world:test\n\n");
  21749. ASSERT_EQ(msgs.size(), 1u);
  21750. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21751. }
  21752. TEST_F(SSEParsingTest, FieldNameOnly) {
  21753. // A line without a colon is a field name with an empty value
  21754. auto msgs = parse("data\n\n");
  21755. ASSERT_EQ(msgs.size(), 1u);
  21756. EXPECT_EQ(msgs[0].data, "");
  21757. }
  21758. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21759. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21760. ASSERT_EQ(msgs.size(), 1u);
  21761. EXPECT_EQ(msgs[0].event, "update");
  21762. EXPECT_EQ(msgs[0].data, "hello");
  21763. }
  21764. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21765. auto msgs = parse("data\r\n\r\n");
  21766. ASSERT_EQ(msgs.size(), 1u);
  21767. EXPECT_EQ(msgs[0].data, "");
  21768. }
  21769. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21770. auto msgs = parse("event: update\rdata: hello\r\r");
  21771. ASSERT_EQ(msgs.size(), 1u);
  21772. EXPECT_EQ(msgs[0].event, "update");
  21773. EXPECT_EQ(msgs[0].data, "hello");
  21774. }
  21775. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21776. // Chunk boundaries fall inside every \r\n and right before the first one
  21777. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21778. "\n\r", "\nevent: end\ndata: end\n\n"};
  21779. server_->Get("/split", [chunks](const Request &, Response &res) {
  21780. auto i = std::make_shared<size_t>(0);
  21781. res.set_chunked_content_provider(
  21782. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21783. if (*i == chunks.size()) {
  21784. sink.done();
  21785. } else {
  21786. sink.write(chunks[*i].data(), chunks[*i].size());
  21787. (*i)++;
  21788. }
  21789. return true;
  21790. });
  21791. });
  21792. auto msgs = collect("/split");
  21793. ASSERT_EQ(msgs.size(), 1u);
  21794. EXPECT_EQ(msgs[0].event, "update");
  21795. EXPECT_EQ(msgs[0].data, "hello");
  21796. }
  21797. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21798. // Only a BOM at the start of the stream is ignored
  21799. auto msgs = parse("\xEF\xBB\xBF"
  21800. "data: first\n\n"
  21801. "\xEF\xBB\xBF"
  21802. "data: second\n\n");
  21803. ASSERT_EQ(msgs.size(), 1u);
  21804. EXPECT_EQ(msgs[0].data, "first");
  21805. }
  21806. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21807. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21808. ASSERT_EQ(msgs.size(), 1u);
  21809. EXPECT_EQ(msgs[0].data, "hello");
  21810. EXPECT_EQ(msgs[0].event, "message");
  21811. }
  21812. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21813. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21814. ASSERT_EQ(msgs.size(), 2u);
  21815. EXPECT_EQ(msgs[0].data, "hello");
  21816. EXPECT_EQ(msgs[1].data, "hello");
  21817. }
  21818. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21819. // An event without data is not dispatched, and its type must not leak
  21820. // into the next event
  21821. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21822. ASSERT_EQ(msgs.size(), 1u);
  21823. EXPECT_EQ(msgs[0].event, "message");
  21824. EXPECT_EQ(msgs[0].data, "hello");
  21825. }
  21826. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21827. // Also when the empty field replaces an earlier type
  21828. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21829. ASSERT_EQ(msgs.size(), 2u);
  21830. EXPECT_EQ(msgs[0].event, "message");
  21831. EXPECT_EQ(msgs[1].event, "message");
  21832. }
  21833. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21834. // The first connection sends only an id; the second echoes back the
  21835. // Last-Event-ID it was reconnected with
  21836. std::atomic<int> connection_count{0};
  21837. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21838. if (connection_count++ == 0) {
  21839. res.set_content("id: 42\n\n", "text/event-stream");
  21840. } else {
  21841. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21842. "\n\nevent: end\ndata: end\n\n",
  21843. "text/event-stream");
  21844. }
  21845. });
  21846. auto msgs = collect("/id-only");
  21847. ASSERT_EQ(msgs.size(), 1u);
  21848. EXPECT_EQ(msgs[0].data, "42");
  21849. }
  21850. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21851. // The first connection sets an id and then clears it with an empty one; the
  21852. // second reports whether it was reconnected with a Last-Event-ID
  21853. std::atomic<int> connection_count{0};
  21854. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21855. if (connection_count++ == 0) {
  21856. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21857. "text/event-stream");
  21858. } else {
  21859. res.set_content(
  21860. std::string("data: ") +
  21861. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21862. "\n\nevent: end\ndata: end\n\n",
  21863. "text/event-stream");
  21864. }
  21865. });
  21866. auto msgs = collect("/id-clear");
  21867. ASSERT_EQ(msgs.size(), 3u);
  21868. EXPECT_EQ(msgs[0].id, "1");
  21869. EXPECT_EQ(msgs[1].id, "");
  21870. EXPECT_EQ(msgs[2].data, "not sent");
  21871. }
  21872. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21873. // The first connection sets an id and then sends ids that cannot be carried
  21874. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21875. // with
  21876. std::atomic<int> connection_count{0};
  21877. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21878. if (connection_count++ == 0) {
  21879. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21880. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21881. "text/event-stream");
  21882. } else {
  21883. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21884. "\n\nevent: end\ndata: end\n\n",
  21885. "text/event-stream");
  21886. }
  21887. });
  21888. auto msgs = collect("/id-unsendable");
  21889. ASSERT_EQ(msgs.size(), 1u);
  21890. EXPECT_EQ(msgs[0].data, "42");
  21891. }
  21892. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21893. auto msgs = parse("event: notification\nid: evt-42\n"
  21894. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21895. ASSERT_EQ(msgs.size(), 1u);
  21896. EXPECT_EQ(msgs[0].event, "notification");
  21897. EXPECT_EQ(msgs[0].id, "evt-42");
  21898. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21899. }
  21900. TEST(SSEMessageTest, Clear) {
  21901. sse::SSEMessage msg;
  21902. msg.event = "custom";
  21903. msg.data = "some data";
  21904. msg.id = "123";
  21905. msg.clear();
  21906. EXPECT_EQ(msg.event, "message");
  21907. EXPECT_EQ(msg.data, "");
  21908. EXPECT_EQ(msg.id, "");
  21909. }
  21910. //==============================================================================
  21911. // SSE Integration Tests
  21912. //==============================================================================
  21913. // Test: Successful connection and on_open callback
  21914. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21915. // Add a simple endpoint that sends one event and closes
  21916. server_->Get("/simple-event", [](const Request &, Response &res) {
  21917. res.set_chunked_content_provider(
  21918. "text/event-stream", [](size_t offset, DataSink &sink) {
  21919. if (offset == 0) {
  21920. std::string event = "data: hello\n\n";
  21921. sink.write(event.data(), event.size());
  21922. }
  21923. return false; // Close stream after sending
  21924. });
  21925. });
  21926. Client client("localhost", get_port());
  21927. sse::SSEClient sse(client, "/simple-event");
  21928. std::atomic<bool> open_called{false};
  21929. std::atomic<bool> message_received{false};
  21930. sse.on_open([&open_called]() { open_called.store(true); });
  21931. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21932. if (msg.data == "hello") { message_received.store(true); }
  21933. });
  21934. sse.set_reconnect_interval(100);
  21935. sse.set_max_reconnect_attempts(1);
  21936. // Start async
  21937. sse.start_async();
  21938. // Wait for message to be processed
  21939. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21940. sse.stop();
  21941. EXPECT_TRUE(open_called.load());
  21942. EXPECT_TRUE(message_received.load());
  21943. }
  21944. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21945. // A data line that never ends.
  21946. server_->Get("/endless-line", [](const Request &, Response &res) {
  21947. res.set_chunked_content_provider(
  21948. "text/event-stream", [](size_t offset, DataSink &sink) {
  21949. if (offset == 0) { sink.write("data: ", 6); }
  21950. std::string chunk(64 * 1024, 'A');
  21951. return sink.write(chunk.data(), chunk.size());
  21952. });
  21953. });
  21954. Client client("localhost", get_port());
  21955. sse::SSEClient sse(client, "/endless-line");
  21956. std::atomic<bool> too_long{false};
  21957. sse.on_error([&](Error err) {
  21958. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21959. });
  21960. sse.set_max_reconnect_attempts(1);
  21961. sse.start_async();
  21962. for (int i = 0; i < 500 && !too_long; i++) {
  21963. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21964. }
  21965. sse.stop();
  21966. EXPECT_TRUE(too_long);
  21967. }
  21968. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21969. // Far more in all than the client's payload limit below.
  21970. server_->Get("/many-events", [](const Request &, Response &res) {
  21971. res.set_chunked_content_provider(
  21972. "text/event-stream", [](size_t offset, DataSink &sink) {
  21973. if (offset == 0) {
  21974. std::string events;
  21975. for (int i = 0; i < 1000; i++) {
  21976. events += "data: message\n\n";
  21977. }
  21978. sink.write(events.data(), events.size());
  21979. }
  21980. return false;
  21981. });
  21982. });
  21983. Client client("localhost", get_port());
  21984. client.set_payload_max_length(1024);
  21985. sse::SSEClient sse(client, "/many-events");
  21986. std::atomic<int> messages{0};
  21987. std::atomic<bool> too_large{false};
  21988. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21989. sse.on_error([&](Error err) {
  21990. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21991. });
  21992. sse.set_max_reconnect_attempts(1);
  21993. sse.start_async();
  21994. for (int i = 0; i < 500 && messages < 1000; i++) {
  21995. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21996. }
  21997. sse.stop();
  21998. EXPECT_GE(messages.load(), 1000);
  21999. EXPECT_FALSE(too_large);
  22000. }
  22001. // Test: on_message callback
  22002. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22003. // Endpoint that sends multiple events then closes
  22004. server_->Get("/multi-event", [](const Request &, Response &res) {
  22005. res.set_chunked_content_provider(
  22006. "text/event-stream", [](size_t offset, DataSink &sink) {
  22007. if (offset == 0) {
  22008. std::string events = "data: message1\n\ndata: message2\n\n";
  22009. sink.write(events.data(), events.size());
  22010. }
  22011. return false;
  22012. });
  22013. });
  22014. Client client("localhost", get_port());
  22015. sse::SSEClient sse(client, "/multi-event");
  22016. std::vector<std::string> received_messages;
  22017. std::mutex messages_mutex;
  22018. sse.on_message([&](const sse::SSEMessage &msg) {
  22019. std::lock_guard<std::mutex> lock(messages_mutex);
  22020. received_messages.push_back(msg.data);
  22021. });
  22022. sse.set_reconnect_interval(100);
  22023. sse.set_max_reconnect_attempts(1);
  22024. sse.start_async();
  22025. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22026. sse.stop();
  22027. std::lock_guard<std::mutex> lock(messages_mutex);
  22028. EXPECT_GE(received_messages.size(), 2u);
  22029. if (received_messages.size() >= 2) {
  22030. EXPECT_EQ(received_messages[0], "message1");
  22031. EXPECT_EQ(received_messages[1], "message2");
  22032. }
  22033. }
  22034. // Test: on_event for specific types
  22035. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22036. Client client("localhost", get_port());
  22037. sse::SSEClient sse(client, "/custom-events");
  22038. std::atomic<bool> update_received{false};
  22039. std::atomic<bool> delete_received{false};
  22040. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22041. if (msg.data == "updated") { update_received.store(true); }
  22042. });
  22043. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22044. if (msg.data == "deleted") { delete_received.store(true); }
  22045. });
  22046. sse.set_max_reconnect_attempts(1);
  22047. sse.start_async();
  22048. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22049. sse.stop();
  22050. EXPECT_TRUE(update_received.load());
  22051. EXPECT_TRUE(delete_received.load());
  22052. }
  22053. // Test: on_error callback on connection failure
  22054. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22055. // Connect to a non-existent port
  22056. Client client("localhost", 59999);
  22057. sse::SSEClient sse(client, "/events");
  22058. std::atomic<bool> error_called{false};
  22059. Error received_error = Error::Success;
  22060. sse.on_error([&](Error err) {
  22061. error_called.store(true);
  22062. received_error = err;
  22063. });
  22064. sse.set_reconnect_interval(50);
  22065. sse.set_max_reconnect_attempts(1);
  22066. sse.start_async();
  22067. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22068. sse.stop();
  22069. EXPECT_TRUE(error_called.load());
  22070. EXPECT_NE(received_error, Error::Success);
  22071. }
  22072. // Test: Last-Event-ID header sent on reconnect
  22073. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22074. // Endpoint that sends event with ID
  22075. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22076. res.set_chunked_content_provider(
  22077. "text/event-stream", [](size_t offset, DataSink &sink) {
  22078. if (offset == 0) {
  22079. std::string event = "id: evt-123\ndata: test\n\n";
  22080. sink.write(event.data(), event.size());
  22081. }
  22082. return false;
  22083. });
  22084. });
  22085. Client client("localhost", get_port());
  22086. sse::SSEClient sse(client, "/event-with-id");
  22087. std::atomic<bool> id_received{false};
  22088. sse.on_message([&](const sse::SSEMessage &msg) {
  22089. if (!msg.id.empty()) { id_received.store(true); }
  22090. });
  22091. sse.set_reconnect_interval(100);
  22092. sse.set_max_reconnect_attempts(1);
  22093. sse.start_async();
  22094. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22095. sse.stop();
  22096. EXPECT_TRUE(id_received.load());
  22097. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22098. }
  22099. // Test: Manual stop
  22100. TEST_F(SSEIntegrationTest, ManualStop) {
  22101. // Endpoint that sends one event and stays open briefly. The server outlives
  22102. // this test body, so the provider uses the fixture's flag, not a local.
  22103. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22104. res.set_chunked_content_provider(
  22105. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22106. if (offset == 0) {
  22107. std::string event = "data: connected\n\n";
  22108. sink.write(event.data(), event.size());
  22109. }
  22110. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22111. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22112. }
  22113. return false;
  22114. });
  22115. });
  22116. Client client("localhost", get_port());
  22117. sse::SSEClient sse(client, "/stay-open");
  22118. std::atomic<bool> connected{false};
  22119. sse.on_open([&connected]() { connected.store(true); });
  22120. sse.set_reconnect_interval(100);
  22121. sse.set_max_reconnect_attempts(1);
  22122. sse.start_async();
  22123. // Wait for connection to establish
  22124. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22125. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22126. }
  22127. EXPECT_TRUE(connected.load());
  22128. EXPECT_TRUE(sse.is_connected());
  22129. // Signal handler to stop
  22130. stop_server_.store(true);
  22131. // Stop SSE client
  22132. sse.stop();
  22133. EXPECT_FALSE(sse.is_connected());
  22134. }
  22135. // Sends one event, then nothing until stop is set
  22136. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22137. return [&stop](const Request &, Response &res) {
  22138. res.set_chunked_content_provider(
  22139. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22140. if (offset == 0) {
  22141. std::string event = "data: hello\n\n";
  22142. sink.write(event.data(), event.size());
  22143. }
  22144. while (!stop.load()) {
  22145. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22146. }
  22147. return false;
  22148. });
  22149. };
  22150. }
  22151. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22152. static void check_stop_interrupts_blocked_read(Client &client) {
  22153. client.set_read_timeout(30, 0);
  22154. for (auto by_destructor : {false, true}) {
  22155. std::atomic<bool> received{false};
  22156. std::chrono::steady_clock::time_point start;
  22157. {
  22158. sse::SSEClient sse(client, "/idle-stream");
  22159. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22160. sse.start_async();
  22161. for (int i = 0; i < 500 && !received.load(); ++i) {
  22162. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22163. }
  22164. ASSERT_TRUE(received.load());
  22165. // Let the client block in the next read
  22166. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22167. start = std::chrono::steady_clock::now();
  22168. if (!by_destructor) { sse.stop(); }
  22169. }
  22170. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22171. std::chrono::seconds(2));
  22172. }
  22173. }
  22174. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22175. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22176. Client client("localhost", get_port());
  22177. check_stop_interrupts_blocked_read(client);
  22178. }
  22179. #ifdef CPPHTTPLIB_SSL_ENABLED
  22180. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22181. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22182. std::atomic<bool> done{false};
  22183. svr.Get("/idle-stream", idle_event_stream(done));
  22184. auto port = svr.bind_to_any_port(HOST);
  22185. std::thread t([&] { svr.listen_after_bind(); });
  22186. auto se = detail::scope_exit([&] {
  22187. done.store(true);
  22188. svr.stop();
  22189. t.join();
  22190. });
  22191. svr.wait_until_ready();
  22192. Client client("https://localhost:" + std::to_string(port));
  22193. client.enable_server_certificate_verification(false);
  22194. check_stop_interrupts_blocked_read(client);
  22195. }
  22196. #endif
  22197. // Test: SSEClient with custom headers
  22198. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22199. // Setup a server endpoint that checks for custom header
  22200. std::atomic<bool> header_received{false};
  22201. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22202. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22203. header_received.store(true);
  22204. }
  22205. res.set_chunked_content_provider("text/event-stream",
  22206. [](size_t, DataSink &) { return false; });
  22207. });
  22208. Client client("localhost", get_port());
  22209. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22210. sse::SSEClient sse(client, "/header-check", headers);
  22211. sse.set_max_reconnect_attempts(1);
  22212. sse.start_async();
  22213. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22214. sse.stop();
  22215. EXPECT_TRUE(header_received.load());
  22216. }
  22217. // Test: Reconnect interval configuration
  22218. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22219. Client client("localhost", get_port());
  22220. sse::SSEClient sse(client, "/events");
  22221. auto &result = sse.set_reconnect_interval(500);
  22222. // Builder pattern should return reference to self
  22223. EXPECT_EQ(&result, &sse);
  22224. }
  22225. // Test: Max reconnect attempts
  22226. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22227. // Connect to non-existent port to force reconnects
  22228. Client client("localhost", 59998);
  22229. sse::SSEClient sse(client, "/events");
  22230. std::atomic<int> error_count{0};
  22231. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22232. sse.set_reconnect_interval(50);
  22233. sse.set_max_reconnect_attempts(2);
  22234. auto start = std::chrono::steady_clock::now();
  22235. sse.start(); // Blocking call
  22236. auto end = std::chrono::steady_clock::now();
  22237. // Should have stopped after 2 failed attempts
  22238. EXPECT_GE(error_count.load(), 2);
  22239. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22240. auto duration =
  22241. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22242. #ifdef _WIN32
  22243. // Windows is much slower for socket connection failures
  22244. EXPECT_LT(duration.count(), 7000);
  22245. #else
  22246. EXPECT_LT(duration.count(), 1000);
  22247. #endif
  22248. }
  22249. // Test: Multi-line data in integration
  22250. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22251. // Endpoint with multi-line data
  22252. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22253. res.set_chunked_content_provider(
  22254. "text/event-stream", [](size_t offset, DataSink &sink) {
  22255. if (offset == 0) {
  22256. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22257. sink.write(event.data(), event.size());
  22258. }
  22259. return false;
  22260. });
  22261. });
  22262. Client client("localhost", get_port());
  22263. sse::SSEClient sse(client, "/multiline-data");
  22264. std::string received_data;
  22265. std::mutex data_mutex;
  22266. sse.on_message([&](const sse::SSEMessage &msg) {
  22267. std::lock_guard<std::mutex> lock(data_mutex);
  22268. received_data = msg.data;
  22269. });
  22270. sse.set_reconnect_interval(100);
  22271. sse.set_max_reconnect_attempts(1);
  22272. sse.start_async();
  22273. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22274. sse.stop();
  22275. std::lock_guard<std::mutex> lock(data_mutex);
  22276. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22277. }
  22278. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22279. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22280. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22281. DataSink &sink) {
  22282. if (offset == 0) {
  22283. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22284. sink.write(events.data(), events.size());
  22285. }
  22286. return false;
  22287. });
  22288. });
  22289. Client client("localhost", get_port());
  22290. sse::SSEClient sse(client, "/empty-data-lines");
  22291. std::mutex mutex;
  22292. std::condition_variable cv;
  22293. std::vector<std::string> received;
  22294. sse.on_message([&](const sse::SSEMessage &msg) {
  22295. std::lock_guard<std::mutex> lock(mutex);
  22296. received.push_back(msg.data);
  22297. cv.notify_all();
  22298. });
  22299. sse.set_max_reconnect_attempts(1);
  22300. sse.start_async();
  22301. {
  22302. std::unique_lock<std::mutex> lock(mutex);
  22303. cv.wait_for(lock, std::chrono::seconds(2),
  22304. [&] { return received.size() >= 3; });
  22305. }
  22306. sse.stop();
  22307. ASSERT_GE(received.size(), 3u);
  22308. EXPECT_EQ(received[0], "");
  22309. EXPECT_EQ(received[1], "\nhello");
  22310. EXPECT_EQ(received[2], "");
  22311. }
  22312. // Test: Auto-reconnect after server disconnection
  22313. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22314. std::atomic<int> connection_count{0};
  22315. std::atomic<int> message_count{0};
  22316. // Endpoint that sends one event and closes, forcing reconnect
  22317. server_->Get("/reconnect-test",
  22318. [&connection_count](const Request &, Response &res) {
  22319. connection_count.fetch_add(1);
  22320. res.set_chunked_content_provider(
  22321. "text/event-stream", [](size_t offset, DataSink &sink) {
  22322. if (offset == 0) {
  22323. std::string event = "data: hello\n\n";
  22324. sink.write(event.data(), event.size());
  22325. }
  22326. return false; // Close connection after sending
  22327. });
  22328. });
  22329. Client client("localhost", get_port());
  22330. sse::SSEClient sse(client, "/reconnect-test");
  22331. sse.on_message([&message_count](const sse::SSEMessage &) {
  22332. message_count.fetch_add(1);
  22333. });
  22334. sse.set_reconnect_interval(100);
  22335. sse.set_max_reconnect_attempts(3);
  22336. sse.start_async();
  22337. // Wait long enough for multiple reconnects
  22338. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22339. sse.stop();
  22340. // Should have connected multiple times (initial + reconnects)
  22341. EXPECT_GE(connection_count.load(), 2);
  22342. // Should have received messages from multiple connections
  22343. EXPECT_GE(message_count.load(), 2);
  22344. }
  22345. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22346. std::atomic<int> connection_count{0};
  22347. // Neither Content-Length nor chunked: the close ends the stream
  22348. server_->Get("/close-delimited",
  22349. [&connection_count](const Request &, Response &res) {
  22350. connection_count.fetch_add(1);
  22351. res.set_content_provider(
  22352. "text/event-stream", [](size_t offset, DataSink &sink) {
  22353. if (offset == 0) {
  22354. std::string event = "data: hello\n\n";
  22355. sink.write(event.data(), event.size());
  22356. } else {
  22357. sink.done();
  22358. }
  22359. return true;
  22360. });
  22361. });
  22362. Client client("localhost", get_port());
  22363. sse::SSEClient sse(client, "/close-delimited");
  22364. std::atomic<int> error_count{0};
  22365. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22366. sse.set_reconnect_interval(100);
  22367. sse.start_async();
  22368. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22369. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22370. }
  22371. sse.stop();
  22372. // Reconnects as after any end of the stream, but reports no error
  22373. EXPECT_GE(connection_count.load(), 2);
  22374. EXPECT_EQ(0, error_count.load());
  22375. }
  22376. // Test: A retry field that is not all ASCII digits is ignored
  22377. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22378. std::atomic<int> connection_count{0};
  22379. server_->Get("/bad-retry",
  22380. [&connection_count](const Request &, Response &res) {
  22381. connection_count.fetch_add(1);
  22382. res.set_chunked_content_provider(
  22383. "text/event-stream", [](size_t offset, DataSink &sink) {
  22384. if (offset == 0) {
  22385. std::string event = "retry: -1\ndata: hello\n\n";
  22386. sink.write(event.data(), event.size());
  22387. }
  22388. return false;
  22389. });
  22390. });
  22391. Client client("localhost", get_port());
  22392. sse::SSEClient sse(client, "/bad-retry");
  22393. sse.set_reconnect_interval(10000);
  22394. sse.start_async();
  22395. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22396. sse.stop();
  22397. EXPECT_EQ(connection_count.load(), 1);
  22398. }
  22399. // Test: A retry field of all ASCII digits sets the reconnection time
  22400. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22401. std::mutex mutex;
  22402. std::condition_variable cv;
  22403. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22404. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22405. {
  22406. std::lock_guard<std::mutex> lock(mutex);
  22407. connected_at.push_back(std::chrono::steady_clock::now());
  22408. cv.notify_all();
  22409. }
  22410. res.set_chunked_content_provider(
  22411. "text/event-stream", [](size_t offset, DataSink &sink) {
  22412. if (offset == 0) {
  22413. std::string event = "retry: 0\ndata: hello\n\n";
  22414. sink.write(event.data(), event.size());
  22415. }
  22416. return false;
  22417. });
  22418. });
  22419. Client client("localhost", get_port());
  22420. sse::SSEClient sse(client, "/zero-retry");
  22421. sse.set_reconnect_interval(10000);
  22422. sse.start_async();
  22423. {
  22424. std::unique_lock<std::mutex> lock(mutex);
  22425. cv.wait_for(lock, std::chrono::seconds(5),
  22426. [&] { return connected_at.size() >= 2; });
  22427. }
  22428. sse.stop();
  22429. // The server-supplied interval is applied, but never below 100ms, so
  22430. // "retry: 0" does not cause a busy reconnect loop
  22431. std::lock_guard<std::mutex> lock(mutex);
  22432. ASSERT_GE(connected_at.size(), 2u);
  22433. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22434. connected_at[1] - connected_at[0])
  22435. .count();
  22436. EXPECT_GE(interval_ms, 100);
  22437. }
  22438. // Test: Last-Event-ID sent on reconnect
  22439. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22440. std::atomic<int> connection_count{0};
  22441. std::vector<std::string> received_last_event_ids;
  22442. std::mutex id_mutex;
  22443. // Endpoint that checks Last-Event-ID header and sends event with ID
  22444. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22445. int conn = connection_count.fetch_add(1);
  22446. // Capture the Last-Event-ID header from each connection
  22447. {
  22448. std::lock_guard<std::mutex> lock(id_mutex);
  22449. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22450. }
  22451. res.set_chunked_content_provider(
  22452. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22453. if (offset == 0) {
  22454. std::string event =
  22455. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22456. sink.write(event.data(), event.size());
  22457. }
  22458. return false;
  22459. });
  22460. });
  22461. Client client("localhost", get_port());
  22462. sse::SSEClient sse(client, "/reconnect-with-id");
  22463. sse.set_reconnect_interval(100);
  22464. sse.set_max_reconnect_attempts(3);
  22465. sse.start_async();
  22466. // Wait for at least 2 connections
  22467. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22468. sse.stop();
  22469. // Verify behavior
  22470. std::lock_guard<std::mutex> lock(id_mutex);
  22471. EXPECT_GE(received_last_event_ids.size(), 2u);
  22472. // First connection should have no Last-Event-ID
  22473. if (!received_last_event_ids.empty()) {
  22474. EXPECT_EQ(received_last_event_ids[0], "");
  22475. }
  22476. // Second connection should have Last-Event-ID from first connection
  22477. if (received_last_event_ids.size() >= 2) {
  22478. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22479. }
  22480. }
  22481. // Test: set_headers updates headers used on reconnect
  22482. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22483. std::vector<std::string> received_tokens;
  22484. std::mutex token_mutex;
  22485. // Endpoint that captures Authorization header
  22486. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22487. {
  22488. std::lock_guard<std::mutex> lock(token_mutex);
  22489. received_tokens.push_back(req.get_header_value("Authorization"));
  22490. }
  22491. res.set_chunked_content_provider(
  22492. "text/event-stream", [](size_t offset, DataSink &sink) {
  22493. if (offset == 0) {
  22494. std::string event = "data: hello\n\n";
  22495. sink.write(event.data(), event.size());
  22496. }
  22497. return false; // Close connection to trigger reconnect
  22498. });
  22499. });
  22500. Client client("localhost", get_port());
  22501. Headers headers = {{"Authorization", "Bearer old-token"}};
  22502. sse::SSEClient sse(client, "/auth-check", headers);
  22503. // Update headers on each successful connection
  22504. sse.on_open(
  22505. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22506. sse.set_reconnect_interval(100);
  22507. sse.set_max_reconnect_attempts(3);
  22508. sse.start_async();
  22509. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22510. sse.stop();
  22511. std::lock_guard<std::mutex> lock(token_mutex);
  22512. ASSERT_GE(received_tokens.size(), 2u);
  22513. // First connection uses original header
  22514. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22515. // Second connection uses updated header from set_headers
  22516. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22517. }
  22518. // Test: 401 allows reconnection (so on_error can refresh headers)
  22519. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22520. std::atomic<int> connection_count{0};
  22521. // Endpoint: returns 401 on first attempt, 200 on second
  22522. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22523. int conn = connection_count.fetch_add(1);
  22524. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22525. res.status = StatusCode::Unauthorized_401;
  22526. res.set_content("Unauthorized", "text/plain");
  22527. return;
  22528. }
  22529. res.set_chunked_content_provider(
  22530. "text/event-stream", [](size_t offset, DataSink &sink) {
  22531. if (offset == 0) {
  22532. std::string event = "data: authenticated\n\n";
  22533. sink.write(event.data(), event.size());
  22534. }
  22535. return false;
  22536. });
  22537. });
  22538. Client client("localhost", get_port());
  22539. Headers headers = {{"Authorization", "Bearer expired"}};
  22540. sse::SSEClient sse(client, "/auth-retry", headers);
  22541. std::atomic<bool> message_received{false};
  22542. // Refresh token on error
  22543. sse.on_error(
  22544. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22545. sse.on_message([&](const sse::SSEMessage &msg) {
  22546. if (msg.data == "authenticated") { message_received.store(true); }
  22547. });
  22548. sse.set_reconnect_interval(100);
  22549. sse.set_max_reconnect_attempts(3);
  22550. sse.start_async();
  22551. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22552. sse.stop();
  22553. // Should have reconnected after 401 and succeeded with new token
  22554. EXPECT_GE(connection_count.load(), 2);
  22555. EXPECT_TRUE(message_received.load());
  22556. }
  22557. TEST(Issue2318Test, EmptyHostString) {
  22558. {
  22559. httplib::Client cli_empty("", PORT);
  22560. auto res = cli_empty.Get("/");
  22561. ASSERT_FALSE(res);
  22562. EXPECT_EQ(httplib::Error::Connection, res.error());
  22563. }
  22564. {
  22565. httplib::Client cli(" ", PORT);
  22566. auto res = cli.Get("/");
  22567. ASSERT_FALSE(res);
  22568. EXPECT_EQ(httplib::Error::Connection, res.error());
  22569. }
  22570. }
  22571. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22572. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22573. Server svr;
  22574. // Set a small payload limit (1KB)
  22575. svr.set_payload_max_length(1024);
  22576. svr.Post("/test", [&](const Request &req, Response &res) {
  22577. res.set_content("Body size: " + std::to_string(req.body.size()),
  22578. "text/plain");
  22579. });
  22580. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22581. auto se = detail::scope_exit([&] {
  22582. svr.stop();
  22583. listen_thread.join();
  22584. });
  22585. svr.wait_until_ready();
  22586. // Create data that compresses well but exceeds limit when decompressed
  22587. // 8KB of repeated null bytes compresses to a very small size
  22588. std::string original_data(8 * 1024, '\0');
  22589. // Compress the data using gzip
  22590. std::string compressed_data;
  22591. detail::gzip_compressor compressor;
  22592. compressor.compress(original_data.data(), original_data.size(), true,
  22593. [&](const char *data, size_t size) {
  22594. compressed_data.append(data, size);
  22595. return true;
  22596. });
  22597. // Verify compression worked (compressed should be much smaller)
  22598. ASSERT_LT(compressed_data.size(), original_data.size());
  22599. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22600. // Send compressed data with Content-Encoding: gzip
  22601. Client cli(HOST, PORT);
  22602. Headers headers = {{"Content-Encoding", "gzip"}};
  22603. auto res =
  22604. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22605. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22607. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22608. }
  22609. #endif
  22610. // ============================================================================
  22611. // OpenSSL-Specific Tests
  22612. // ============================================================================
  22613. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22614. X509 *readCertificate(const std::string &strFileName) {
  22615. std::ifstream inStream(strFileName);
  22616. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22617. std::istreambuf_iterator<char>());
  22618. if (strCertPEM.empty()) return (nullptr);
  22619. BIO *pbCert = BIO_new(BIO_s_mem());
  22620. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22621. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22622. BIO_free(pbCert);
  22623. return (pCert);
  22624. }
  22625. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22626. std::ifstream inStream(strFileName);
  22627. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22628. std::istreambuf_iterator<char>());
  22629. if (strPrivateKeyPEM.empty()) return (nullptr);
  22630. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22631. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22632. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22633. BIO_free(pbPrivKey);
  22634. return (pPrivateKey);
  22635. }
  22636. TEST(BindServerTest, UpdateCerts) {
  22637. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22638. int port = svr.bind_to_any_port("0.0.0.0");
  22639. ASSERT_TRUE(svr.is_valid());
  22640. ASSERT_TRUE(port > 0);
  22641. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22642. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22643. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22644. ASSERT_TRUE(cert != nullptr);
  22645. ASSERT_TRUE(ca_cert != nullptr);
  22646. ASSERT_TRUE(key != nullptr);
  22647. X509_STORE *cert_store = X509_STORE_new();
  22648. X509_STORE_add_cert(cert_store, ca_cert);
  22649. // svr.update_certs(cert, key, cert_store); // deprecated
  22650. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22651. CLIENT_CA_CERT_FILE);
  22652. ASSERT_TRUE(svr.is_valid());
  22653. svr.stop();
  22654. X509_STORE_free(cert_store);
  22655. X509_free(cert);
  22656. X509_free(ca_cert);
  22657. EVP_PKEY_free(key);
  22658. }
  22659. // Test that update_certs() updates client CA list correctly
  22660. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22661. // Start with file-based constructor
  22662. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22663. ASSERT_TRUE(svr.is_valid());
  22664. // Initially no client CA list should be set
  22665. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22666. ASSERT_TRUE(ssl_ctx != nullptr);
  22667. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22668. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22669. // Now update with client CA (PEM string)
  22670. std::string cert_pem, key_pem, ca_pem;
  22671. read_file(SERVER_CERT_FILE, cert_pem);
  22672. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22673. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22674. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22675. ASSERT_TRUE(svr.is_valid());
  22676. // Now client CA list should be set
  22677. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22678. ASSERT_TRUE(ca_list_after != nullptr);
  22679. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22680. }
  22681. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22682. // Test that the file-path SSLServer constructor properly sets the client CA
  22683. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22684. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22685. ASSERT_TRUE(svr.is_valid());
  22686. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22687. ASSERT_TRUE(ssl_ctx != nullptr);
  22688. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22689. ASSERT_TRUE(ca_list != nullptr);
  22690. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22691. }
  22692. #endif
  22693. // ============================================================================
  22694. // MbedTLS-Specific Tests
  22695. // ============================================================================
  22696. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22697. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22698. using namespace httplib::tls;
  22699. // Track if callback was invoked
  22700. bool callback_invoked = false;
  22701. // The callback receives void* ctx which is actually MbedTlsContext*
  22702. // We can access the mbedtls_ssl_config via the context
  22703. auto setup_callback = [&callback_invoked](void *ctx) {
  22704. callback_invoked = true;
  22705. // Cast to MbedTlsContext* to access the ssl config
  22706. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22707. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22708. // Use static variables to hold certificate data (simplified for test)
  22709. static mbedtls_x509_crt own_cert;
  22710. static mbedtls_pk_context own_key;
  22711. static mbedtls_x509_crt ca_chain;
  22712. static bool initialized = false;
  22713. if (!initialized) {
  22714. mbedtls_x509_crt_init(&own_cert);
  22715. mbedtls_pk_init(&own_key);
  22716. mbedtls_x509_crt_init(&ca_chain);
  22717. // Load server certificate
  22718. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22719. return false;
  22720. }
  22721. // Load server private key.
  22722. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22723. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22724. #if MBEDTLS_VERSION_MAJOR == 3
  22725. ,
  22726. mbedtls_ctr_drbg_random, nullptr
  22727. #endif
  22728. ) != 0) {
  22729. return false;
  22730. }
  22731. // Load CA chain for client verification
  22732. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22733. return false;
  22734. }
  22735. initialized = true;
  22736. }
  22737. // Configure the SSL config
  22738. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22739. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22740. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22741. // Set minimum TLS version using mbedTLS native API
  22742. #if MBEDTLS_VERSION_MAJOR >= 3
  22743. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22744. #else
  22745. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22746. MBEDTLS_SSL_MINOR_VERSION_3);
  22747. #endif
  22748. return true;
  22749. };
  22750. SSLServer svr(setup_callback);
  22751. ASSERT_TRUE(svr.is_valid());
  22752. ASSERT_TRUE(callback_invoked);
  22753. svr.Get("/test", [&](const Request &req, Response &res) {
  22754. res.set_content("test", "text/plain");
  22755. auto cert = req.peer_cert();
  22756. ASSERT_TRUE(static_cast<bool>(cert));
  22757. auto common_name = cert.subject_cn();
  22758. EXPECT_EQ("Common Name", common_name);
  22759. });
  22760. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22761. auto se = detail::scope_exit([&] {
  22762. svr.stop();
  22763. t.join();
  22764. ASSERT_FALSE(svr.is_running());
  22765. });
  22766. svr.wait_until_ready();
  22767. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22768. cli.enable_server_certificate_verification(false);
  22769. cli.set_connection_timeout(30);
  22770. auto res = cli.Get("/test");
  22771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22772. ASSERT_EQ(StatusCode::OK_200, res->status);
  22773. }
  22774. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22775. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22776. // keep-alive SSL session, which reads through that config in
  22777. // mbedtls_ssl_close_notify.
  22778. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22779. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22780. ASSERT_TRUE(svr.is_valid());
  22781. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22782. res.set_content("test", "text/plain");
  22783. });
  22784. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22785. auto se = detail::scope_exit([&] {
  22786. svr.stop();
  22787. t.join();
  22788. ASSERT_FALSE(svr.is_running());
  22789. });
  22790. svr.wait_until_ready();
  22791. {
  22792. SSLClient cli(HOST, PORT);
  22793. cli.enable_server_certificate_verification(false);
  22794. cli.set_keep_alive(true);
  22795. auto res = cli.Get("/test");
  22796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22797. ASSERT_EQ(StatusCode::OK_200, res->status);
  22798. // cli is destructed here with the keep-alive SSL session still open.
  22799. }
  22800. }
  22801. #endif
  22802. // WebSocket Tests
  22803. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22804. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22805. // defining the meaning of these bits has been negotiated.
  22806. auto make_frame = [](uint8_t first_byte) {
  22807. std::string frame;
  22808. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22809. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22810. frame += "Hello";
  22811. return frame;
  22812. };
  22813. // RSV1 set (0x40)
  22814. {
  22815. detail::BufferStream strm;
  22816. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22817. ws::Opcode opcode;
  22818. std::string payload;
  22819. bool fin;
  22820. EXPECT_EQ(
  22821. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22822. ws::impl::FrameRead::Fail);
  22823. }
  22824. // RSV2 set (0x20)
  22825. {
  22826. detail::BufferStream strm;
  22827. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22828. ws::Opcode opcode;
  22829. std::string payload;
  22830. bool fin;
  22831. EXPECT_EQ(
  22832. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22833. ws::impl::FrameRead::Fail);
  22834. }
  22835. // RSV3 set (0x10)
  22836. {
  22837. detail::BufferStream strm;
  22838. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22839. ws::Opcode opcode;
  22840. std::string payload;
  22841. bool fin;
  22842. EXPECT_EQ(
  22843. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22844. ws::impl::FrameRead::Fail);
  22845. }
  22846. // No RSV bits set - should succeed
  22847. {
  22848. detail::BufferStream strm;
  22849. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22850. ws::Opcode opcode;
  22851. std::string payload;
  22852. bool fin;
  22853. EXPECT_EQ(
  22854. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22855. ws::impl::FrameRead::Ok);
  22856. EXPECT_EQ(ws::Opcode::Text, opcode);
  22857. EXPECT_EQ("Hello", payload);
  22858. EXPECT_TRUE(fin);
  22859. }
  22860. }
  22861. TEST(WebSocketTest, ControlFrameValidation) {
  22862. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22863. // payload length <= 125.
  22864. // Ping with FIN=0 - must be rejected
  22865. {
  22866. detail::BufferStream strm;
  22867. std::string frame;
  22868. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22869. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22870. strm.write(frame.data(), frame.size());
  22871. ws::Opcode opcode;
  22872. std::string payload;
  22873. bool fin;
  22874. EXPECT_EQ(
  22875. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22876. ws::impl::FrameRead::Fail);
  22877. }
  22878. // Close with FIN=0 - must be rejected
  22879. {
  22880. detail::BufferStream strm;
  22881. std::string frame;
  22882. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22883. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22884. strm.write(frame.data(), frame.size());
  22885. ws::Opcode opcode;
  22886. std::string payload;
  22887. bool fin;
  22888. EXPECT_EQ(
  22889. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22890. ws::impl::FrameRead::Fail);
  22891. }
  22892. // Ping with payload_len=126 (extended length) - must be rejected
  22893. {
  22894. detail::BufferStream strm;
  22895. std::string frame;
  22896. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22897. frame += static_cast<char>(126); // payload_len=126 (>125)
  22898. frame += static_cast<char>(0x00); // extended length high byte
  22899. frame += static_cast<char>(126); // extended length low byte
  22900. frame += std::string(126, 'x');
  22901. strm.write(frame.data(), frame.size());
  22902. ws::Opcode opcode;
  22903. std::string payload;
  22904. bool fin;
  22905. EXPECT_EQ(
  22906. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22907. ws::impl::FrameRead::Fail);
  22908. }
  22909. // Ping with FIN=1 and payload_len=125 - should succeed
  22910. {
  22911. detail::BufferStream strm;
  22912. std::string frame;
  22913. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22914. frame += static_cast<char>(125); // payload_len=125
  22915. frame += std::string(125, 'x');
  22916. strm.write(frame.data(), frame.size());
  22917. ws::Opcode opcode;
  22918. std::string payload;
  22919. bool fin;
  22920. EXPECT_EQ(
  22921. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22922. ws::impl::FrameRead::Ok);
  22923. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22924. EXPECT_EQ(125u, payload.size());
  22925. EXPECT_TRUE(fin);
  22926. }
  22927. }
  22928. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22929. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22930. // length MUST be 0.
  22931. // MSB set - must be rejected
  22932. {
  22933. detail::BufferStream strm;
  22934. std::string frame;
  22935. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22936. frame += static_cast<char>(127); // 64-bit extended length
  22937. frame += static_cast<char>(0x80); // MSB set (invalid)
  22938. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22939. strm.write(frame.data(), frame.size());
  22940. ws::Opcode opcode;
  22941. std::string payload;
  22942. bool fin;
  22943. EXPECT_EQ(
  22944. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22945. ws::impl::FrameRead::Fail);
  22946. }
  22947. // MSB clear - should pass length parsing (will be rejected by max_len,
  22948. // but that's a different check; use a small length to verify)
  22949. {
  22950. detail::BufferStream strm;
  22951. std::string frame;
  22952. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22953. frame += static_cast<char>(127); // 64-bit extended length
  22954. frame += std::string(7, '\0'); // high bytes = 0
  22955. frame += static_cast<char>(0x03); // length = 3
  22956. frame += "abc";
  22957. strm.write(frame.data(), frame.size());
  22958. ws::Opcode opcode;
  22959. std::string payload;
  22960. bool fin;
  22961. EXPECT_EQ(
  22962. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22963. ws::impl::FrameRead::Ok);
  22964. EXPECT_EQ(ws::Opcode::Text, opcode);
  22965. EXPECT_EQ("abc", payload);
  22966. }
  22967. }
  22968. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22969. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22970. // Valid UTF-8
  22971. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22972. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22973. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22974. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22975. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22976. // Invalid UTF-8
  22977. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22978. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22979. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22980. EXPECT_FALSE(
  22981. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22982. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22983. }
  22984. TEST(WebSocketTest, ConnectAndDisconnect) {
  22985. Server svr;
  22986. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22987. std::string msg;
  22988. while (ws.read(msg)) {}
  22989. });
  22990. auto port = svr.bind_to_any_port(HOST);
  22991. std::thread t([&]() { svr.listen_after_bind(); });
  22992. svr.wait_until_ready();
  22993. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22994. auto res = client.connect();
  22995. ASSERT_TRUE(res);
  22996. EXPECT_EQ(Error::Success, res.error());
  22997. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22998. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22999. EXPECT_TRUE(client.is_open());
  23000. client.close();
  23001. EXPECT_FALSE(client.is_open());
  23002. svr.stop();
  23003. t.join();
  23004. }
  23005. TEST(WebSocketTest, ValidURL) {
  23006. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23007. EXPECT_TRUE(ws1.is_valid());
  23008. ws::WebSocketClient ws2("ws://example.com/path");
  23009. EXPECT_TRUE(ws2.is_valid());
  23010. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23011. EXPECT_TRUE(ws3.is_valid());
  23012. #ifdef CPPHTTPLIB_SSL_ENABLED
  23013. ws::WebSocketClient wss1("wss://example.com/path");
  23014. EXPECT_TRUE(wss1.is_valid());
  23015. ws::WebSocketClient wss2("wss://example.com:443/path");
  23016. EXPECT_TRUE(wss2.is_valid());
  23017. #endif
  23018. }
  23019. TEST(WebSocketTest, InvalidURL) {
  23020. // No scheme
  23021. ws::WebSocketClient ws1("localhost:8080/path");
  23022. EXPECT_FALSE(ws1.is_valid());
  23023. // No path
  23024. ws::WebSocketClient ws2("ws://localhost:8080");
  23025. EXPECT_FALSE(ws2.is_valid());
  23026. // Empty string
  23027. ws::WebSocketClient ws3("");
  23028. EXPECT_FALSE(ws3.is_valid());
  23029. // Missing host
  23030. ws::WebSocketClient ws4("ws://:8080/path");
  23031. EXPECT_FALSE(ws4.is_valid());
  23032. // Port number overflow — should not crash
  23033. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23034. EXPECT_FALSE(ws5.is_valid());
  23035. // Port out of range
  23036. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23037. EXPECT_FALSE(ws6.is_valid());
  23038. }
  23039. TEST(WebSocketTest, UnsupportedScheme) {
  23040. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23041. ws::WebSocketClient ws1("http://localhost:8080/path");
  23042. EXPECT_FALSE(ws1.is_valid());
  23043. ws::WebSocketClient ws2("https://localhost:8080/path");
  23044. EXPECT_FALSE(ws2.is_valid());
  23045. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23046. EXPECT_FALSE(ws3.is_valid());
  23047. #else
  23048. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23049. std::invalid_argument);
  23050. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23051. std::invalid_argument);
  23052. #endif
  23053. }
  23054. TEST(WebSocketTest, ConnectWhenInvalid) {
  23055. ws::WebSocketClient ws("not a valid url");
  23056. EXPECT_FALSE(ws.is_valid());
  23057. auto res = ws.connect();
  23058. EXPECT_FALSE(res);
  23059. EXPECT_EQ(Error::Connection, res.error());
  23060. EXPECT_EQ(-1, res.status());
  23061. }
  23062. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23063. // Grab a port that is free, then close it again so nothing listens there
  23064. Server svr;
  23065. auto port = svr.bind_to_any_port(HOST);
  23066. svr.stop();
  23067. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23068. auto res = client.connect();
  23069. ASSERT_FALSE(res);
  23070. EXPECT_EQ(Error::Connection, res.error());
  23071. EXPECT_EQ(-1, res.status());
  23072. }
  23073. TEST(WebSocketTest, DefaultPort) {
  23074. ws::WebSocketClient ws1("ws://example.com/path");
  23075. EXPECT_TRUE(ws1.is_valid());
  23076. // ws:// defaults to port 80 (verified by successful parse)
  23077. #ifdef CPPHTTPLIB_SSL_ENABLED
  23078. ws::WebSocketClient ws2("wss://example.com/path");
  23079. EXPECT_TRUE(ws2.is_valid());
  23080. // wss:// defaults to port 443 (verified by successful parse)
  23081. #endif
  23082. }
  23083. TEST(WebSocketTest, IPv6LiteralAddress) {
  23084. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23085. EXPECT_TRUE(ws1.is_valid());
  23086. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23087. EXPECT_TRUE(ws2.is_valid());
  23088. }
  23089. TEST(WebSocketTest, ComplexPath) {
  23090. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23091. EXPECT_TRUE(ws1.is_valid());
  23092. ws::WebSocketClient ws2("ws://localhost:8080/");
  23093. EXPECT_TRUE(ws2.is_valid());
  23094. }
  23095. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23096. Server svr;
  23097. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23098. std::string msg;
  23099. while (ws.read(msg)) {}
  23100. });
  23101. auto port = svr.bind_to_any_port(HOST);
  23102. std::thread t([&]() { svr.listen_after_bind(); });
  23103. svr.wait_until_ready();
  23104. auto another_host = "example.com";
  23105. auto wrong_ip = "192.0.2.1";
  23106. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23107. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23108. ASSERT_TRUE(client.connect());
  23109. EXPECT_TRUE(client.is_open());
  23110. client.close();
  23111. svr.stop();
  23112. t.join();
  23113. }
  23114. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23115. Server svr;
  23116. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23117. std::string msg;
  23118. while (ws.read(msg)) {}
  23119. });
  23120. auto port = svr.bind_to_any_port(HOST);
  23121. std::thread t([&]() { svr.listen_after_bind(); });
  23122. svr.wait_until_ready();
  23123. auto wrong_ip = "192.0.2.1";
  23124. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23125. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23126. client.set_connection_timeout(1);
  23127. client.set_read_timeout(1);
  23128. client.set_write_timeout(1);
  23129. EXPECT_FALSE(client.connect());
  23130. EXPECT_FALSE(client.is_open());
  23131. svr.stop();
  23132. t.join();
  23133. }
  23134. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23135. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23136. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23137. // (RFC 6761) is only a map key and the Host header value.
  23138. auto host = "target.invalid";
  23139. Server svr;
  23140. std::string received_host;
  23141. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23142. received_host = req.get_header_value("Host");
  23143. std::string msg;
  23144. while (ws.read(msg)) {}
  23145. });
  23146. auto port = svr.bind_to_any_port(HOST);
  23147. std::thread t([&]() { svr.listen_after_bind(); });
  23148. // ASSERT_* below returns from the test body, which would leave t joinable
  23149. // and make ~thread call std::terminate.
  23150. auto se = detail::scope_exit([&] {
  23151. svr.stop();
  23152. if (t.joinable()) { t.join(); }
  23153. });
  23154. svr.wait_until_ready();
  23155. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23156. std::to_string(port) + "/ws");
  23157. client.set_hostname_addr_map({{host, HOST}});
  23158. ASSERT_TRUE(client.connect());
  23159. EXPECT_TRUE(client.is_open());
  23160. client.close();
  23161. svr.stop();
  23162. t.join();
  23163. // The mapping only redirects the connection; the identity stays host_.
  23164. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23165. }
  23166. class WebSocketIntegrationTest : public ::testing::Test {
  23167. protected:
  23168. void SetUp() override {
  23169. server_ = httplib::detail::make_unique<Server>();
  23170. setup_server();
  23171. start_server();
  23172. }
  23173. void TearDown() override {
  23174. server_->stop();
  23175. if (server_thread_.joinable()) { server_thread_.join(); }
  23176. }
  23177. void setup_server() {
  23178. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23179. std::string msg;
  23180. ws::ReadResult ret;
  23181. while ((ret = ws.read(msg))) {
  23182. if (ret == ws::Binary) {
  23183. ws.send(msg.data(), msg.size());
  23184. } else {
  23185. ws.send(msg);
  23186. }
  23187. }
  23188. });
  23189. server_->WebSocket("/ws-echo-string",
  23190. [](const Request &, ws::WebSocket &ws) {
  23191. std::string msg;
  23192. while (ws.read(msg)) {
  23193. ws.send("echo: " + msg);
  23194. }
  23195. });
  23196. server_->WebSocket(
  23197. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23198. // Echo back request metadata
  23199. ws.send("path:" + req.path);
  23200. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23201. std::string msg;
  23202. while (ws.read(msg)) {}
  23203. });
  23204. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23205. std::string msg;
  23206. ws.read(msg); // wait for a message
  23207. ws.close();
  23208. });
  23209. server_->WebSocket("/ws-close-status",
  23210. [](const Request &, ws::WebSocket &ws) {
  23211. std::string msg;
  23212. ws.read(msg); // wait for a message
  23213. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23214. });
  23215. server_->WebSocket(
  23216. "/ws-subprotocol",
  23217. [](const Request &, ws::WebSocket &ws) {
  23218. std::string msg;
  23219. while (ws.read(msg)) {
  23220. ws.send(msg);
  23221. }
  23222. },
  23223. [](const std::vector<std::string> &protocols) -> std::string {
  23224. for (const auto &p : protocols) {
  23225. if (p == "graphql-ws") { return p; }
  23226. }
  23227. return "";
  23228. });
  23229. server_->WebSocket(
  23230. "/ws-subprotocol-unoffered",
  23231. [](const Request &, ws::WebSocket &ws) {
  23232. std::string msg;
  23233. while (ws.read(msg)) {
  23234. ws.send(msg);
  23235. }
  23236. },
  23237. [](const std::vector<std::string> &) -> std::string {
  23238. return "admin";
  23239. });
  23240. }
  23241. void start_server() {
  23242. port_ = server_->bind_to_any_port(HOST);
  23243. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23244. server_->wait_until_ready();
  23245. }
  23246. std::unique_ptr<Server> server_;
  23247. std::thread server_thread_;
  23248. int port_ = 0;
  23249. };
  23250. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23251. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23252. "/ws-echo");
  23253. ASSERT_TRUE(client.connect());
  23254. ASSERT_TRUE(client.is_open());
  23255. ASSERT_TRUE(client.send("Hello WebSocket"));
  23256. std::string msg;
  23257. EXPECT_EQ(ws::Text, client.read(msg));
  23258. EXPECT_EQ("Hello WebSocket", msg);
  23259. client.close();
  23260. }
  23261. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23262. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23263. "/ws-echo");
  23264. ASSERT_TRUE(client.connect());
  23265. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23266. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23267. std::string msg;
  23268. EXPECT_EQ(ws::Binary, client.read(msg));
  23269. EXPECT_EQ(binary_data, msg);
  23270. client.close();
  23271. }
  23272. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23274. "/ws-echo");
  23275. ASSERT_TRUE(client.connect());
  23276. for (int i = 0; i < 10; i++) {
  23277. auto text = "message " + std::to_string(i);
  23278. ASSERT_TRUE(client.send(text));
  23279. std::string msg;
  23280. ASSERT_TRUE(client.read(msg));
  23281. EXPECT_EQ(text, msg);
  23282. }
  23283. client.close();
  23284. }
  23285. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23286. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23287. "/ws-close");
  23288. ASSERT_TRUE(client.connect());
  23289. // Send a message to trigger the server to close
  23290. ASSERT_TRUE(client.send("trigger close"));
  23291. // The server will close, so read should return false
  23292. std::string msg;
  23293. EXPECT_FALSE(client.read(msg));
  23294. EXPECT_FALSE(client.is_open());
  23295. }
  23296. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23297. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23298. "/ws-echo");
  23299. ASSERT_TRUE(client.connect());
  23300. // 128KB message
  23301. std::string large_data(128 * 1024, 'X');
  23302. ASSERT_TRUE(client.send(large_data));
  23303. std::string msg;
  23304. ASSERT_TRUE(client.read(msg));
  23305. EXPECT_EQ(large_data, msg);
  23306. client.close();
  23307. }
  23308. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23309. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23310. "/ws-echo");
  23311. ASSERT_TRUE(client.connect());
  23312. const int num_threads = 4;
  23313. std::vector<std::thread> threads;
  23314. std::atomic<int> send_count{0};
  23315. for (int t = 0; t < num_threads; t++) {
  23316. threads.emplace_back([&client, &send_count, t]() {
  23317. for (int i = 0; i < 5; i++) {
  23318. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23319. if (client.send(text)) { send_count++; }
  23320. }
  23321. });
  23322. }
  23323. for (auto &th : threads) {
  23324. th.join();
  23325. }
  23326. int received = 0;
  23327. std::string msg;
  23328. while (received < send_count.load()) {
  23329. if (!client.read(msg)) { break; }
  23330. received++;
  23331. }
  23332. EXPECT_EQ(send_count.load(), received);
  23333. client.close();
  23334. }
  23335. TEST_F(WebSocketIntegrationTest, ReadString) {
  23336. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23337. "/ws-echo-string");
  23338. ASSERT_TRUE(client.connect());
  23339. ASSERT_TRUE(client.send("hello"));
  23340. std::string msg;
  23341. ASSERT_TRUE(client.read(msg));
  23342. EXPECT_EQ("echo: hello", msg);
  23343. ASSERT_TRUE(client.send("world"));
  23344. ASSERT_TRUE(client.read(msg));
  23345. EXPECT_EQ("echo: world", msg);
  23346. client.close();
  23347. }
  23348. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23349. Headers headers = {{"X-Test-Header", "test-value"}};
  23350. ws::WebSocketClient client(
  23351. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23352. ASSERT_TRUE(client.connect());
  23353. std::string msg;
  23354. ASSERT_TRUE(client.read(msg));
  23355. EXPECT_EQ("path:/ws-request-info", msg);
  23356. ASSERT_TRUE(client.read(msg));
  23357. EXPECT_EQ("header:test-value", msg);
  23358. client.close();
  23359. }
  23360. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23361. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23362. "/ws-echo");
  23363. client.set_read_timeout(1, 0); // 1 second
  23364. ASSERT_TRUE(client.connect());
  23365. // Don't send anything — server echo handler waits for a message, so read()
  23366. // should time out. The connection survives it: nothing was consumed.
  23367. std::string msg;
  23368. EXPECT_EQ(client.read(msg), ws::Timeout);
  23369. EXPECT_TRUE(client.is_open());
  23370. // And it is still usable afterwards.
  23371. EXPECT_TRUE(client.send("after timeout"));
  23372. EXPECT_EQ(client.read(msg), ws::Text);
  23373. EXPECT_EQ(msg, "after timeout");
  23374. }
  23375. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23376. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23377. "/ws-echo");
  23378. client.set_read_timeout(1, 0);
  23379. ASSERT_TRUE(client.connect());
  23380. ASSERT_TRUE(client.send("first"));
  23381. std::string msg;
  23382. ASSERT_EQ(client.read(msg), ws::Text);
  23383. ASSERT_EQ(msg, "first");
  23384. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23385. // not be used with a read timeout: it would reprocess the previous message.
  23386. EXPECT_EQ(client.read(msg), ws::Timeout);
  23387. EXPECT_EQ(msg, "first");
  23388. }
  23389. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23390. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23391. "/ws-echo");
  23392. ASSERT_TRUE(client.connect());
  23393. // Setting it once the connection is open reaches the live stream, not just
  23394. // the seed for the next connect().
  23395. client.set_read_timeout(1, 0);
  23396. std::string msg;
  23397. EXPECT_EQ(client.read(msg), ws::Timeout);
  23398. EXPECT_TRUE(client.is_open());
  23399. }
  23400. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23401. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23402. "/ws-echo");
  23403. client.set_read_timeout(5, 0);
  23404. ASSERT_TRUE(client.connect());
  23405. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23406. // The server should reject it and close the connection.
  23407. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23408. client.send(oversized);
  23409. // The server's read() should have failed due to payload limit,
  23410. // so our read() should return false (connection closed).
  23411. std::string msg;
  23412. EXPECT_FALSE(client.read(msg));
  23413. }
  23414. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23415. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23416. "/ws-echo");
  23417. client.set_read_timeout(10, 0);
  23418. ASSERT_TRUE(client.connect());
  23419. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23420. // This should succeed.
  23421. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23422. ASSERT_TRUE(client.send(at_limit));
  23423. std::string msg;
  23424. ASSERT_TRUE(client.read(msg));
  23425. EXPECT_EQ(at_limit.size(), msg.size());
  23426. client.close();
  23427. }
  23428. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23429. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23430. "/nonexistent");
  23431. auto res = client.connect();
  23432. EXPECT_FALSE(res);
  23433. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23434. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23435. EXPECT_FALSE(client.is_open());
  23436. }
  23437. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23438. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23439. "/ws-echo");
  23440. ASSERT_TRUE(client.connect());
  23441. ASSERT_TRUE(client.send(""));
  23442. std::string msg;
  23443. EXPECT_EQ(ws::Text, client.read(msg));
  23444. EXPECT_EQ("", msg);
  23445. client.close();
  23446. }
  23447. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23448. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23449. "/ws-echo");
  23450. // First connection
  23451. ASSERT_TRUE(client.connect());
  23452. ASSERT_TRUE(client.send("first"));
  23453. std::string msg;
  23454. ASSERT_TRUE(client.read(msg));
  23455. EXPECT_EQ("first", msg);
  23456. client.close();
  23457. EXPECT_FALSE(client.is_open());
  23458. // Reconnect using the same client object
  23459. ASSERT_TRUE(client.connect());
  23460. ASSERT_TRUE(client.is_open());
  23461. ASSERT_TRUE(client.send("second"));
  23462. ASSERT_TRUE(client.read(msg));
  23463. EXPECT_EQ("second", msg);
  23464. client.close();
  23465. }
  23466. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23467. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23468. "/ws-close-status");
  23469. ASSERT_TRUE(client.connect());
  23470. // Trigger the server to close with GoingAway status
  23471. ASSERT_TRUE(client.send("trigger"));
  23472. // read() should return false after receiving the close frame
  23473. std::string msg;
  23474. EXPECT_FALSE(client.read(msg));
  23475. EXPECT_FALSE(client.is_open());
  23476. }
  23477. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23478. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23479. "/ws-echo");
  23480. ASSERT_TRUE(client.connect());
  23481. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23482. EXPECT_FALSE(client.is_open());
  23483. }
  23484. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23485. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23486. ws::WebSocketClient client(
  23487. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23488. ASSERT_TRUE(client.connect());
  23489. // Server should have selected graphql-ws
  23490. EXPECT_EQ("graphql-ws", client.subprotocol());
  23491. client.close();
  23492. }
  23493. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23494. Headers headers;
  23495. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23496. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23497. ws::WebSocketClient client(
  23498. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23499. ASSERT_TRUE(client.connect());
  23500. // The offer on the second field line counts too, so graphql-ws is selected
  23501. EXPECT_EQ("graphql-ws", client.subprotocol());
  23502. client.close();
  23503. }
  23504. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23505. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23506. ws::WebSocketClient client(
  23507. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23508. ASSERT_TRUE(client.connect());
  23509. // Server should not have selected any subprotocol
  23510. EXPECT_TRUE(client.subprotocol().empty());
  23511. client.close();
  23512. }
  23513. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23514. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23515. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23516. "/ws-subprotocol-unoffered",
  23517. headers);
  23518. ASSERT_TRUE(client.connect());
  23519. EXPECT_TRUE(client.subprotocol().empty());
  23520. client.close();
  23521. }
  23522. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23523. // Connect without requesting any subprotocol
  23524. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23525. "/ws-subprotocol");
  23526. ASSERT_TRUE(client.connect());
  23527. EXPECT_TRUE(client.subprotocol().empty());
  23528. client.close();
  23529. }
  23530. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23531. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23532. "/ws-echo");
  23533. client.set_tcp_nodelay(true);
  23534. client.set_connection_timeout(3, 0);
  23535. bool socket_options_called = false;
  23536. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23537. ASSERT_TRUE(client.connect());
  23538. ASSERT_TRUE(client.is_open());
  23539. EXPECT_TRUE(socket_options_called);
  23540. ASSERT_TRUE(client.send("hello"));
  23541. std::string msg;
  23542. auto result = client.read(msg);
  23543. EXPECT_EQ(result, ws::ReadResult::Text);
  23544. EXPECT_EQ(msg, "hello");
  23545. client.close();
  23546. }
  23547. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23548. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23549. "/ws-echo");
  23550. client.set_connection_timeout(std::chrono::seconds(3));
  23551. client.set_write_timeout(std::chrono::seconds(3));
  23552. // A sub-second remainder exercises the seconds/microseconds split.
  23553. client.set_read_timeout(std::chrono::milliseconds(1500));
  23554. ASSERT_TRUE(client.connect());
  23555. auto start = std::chrono::steady_clock::now();
  23556. std::string msg;
  23557. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23558. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23559. std::chrono::steady_clock::now() - start)
  23560. .count();
  23561. // Above 1s so that dropping the microseconds half of the split fails here.
  23562. // Ignoring the setter altogether would not reach this line at all: a client
  23563. // waits forever by default.
  23564. EXPECT_GE(elapsed, 1400);
  23565. EXPECT_LT(elapsed, 30000);
  23566. }
  23567. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23568. Server svr;
  23569. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23570. if (!req.has_header("Authorization")) {
  23571. res.status = StatusCode::Unauthorized_401;
  23572. res.set_content("Unauthorized", "text/plain");
  23573. return Server::HandlerResponse::Handled;
  23574. }
  23575. return Server::HandlerResponse::Unhandled;
  23576. });
  23577. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23578. std::string msg;
  23579. while (ws.read(msg)) {
  23580. ws.send(msg);
  23581. }
  23582. });
  23583. auto port = svr.bind_to_any_port("localhost");
  23584. std::thread t([&]() { svr.listen_after_bind(); });
  23585. svr.wait_until_ready();
  23586. // Without Authorization header - should be rejected before upgrade
  23587. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23588. EXPECT_FALSE(client1.connect());
  23589. // The rejection is framed like any other HTTP response
  23590. {
  23591. Client cli("localhost", port);
  23592. Headers headers = {{"Upgrade", "websocket"},
  23593. {"Connection", "Upgrade"},
  23594. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23595. {"Sec-WebSocket-Version", "13"}};
  23596. auto res = cli.Get("/ws", headers);
  23597. ASSERT_TRUE(res);
  23598. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23599. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23600. EXPECT_EQ("Unauthorized", res->body);
  23601. }
  23602. // With Authorization header - should succeed
  23603. Headers headers = {{"Authorization", "Bearer token123"}};
  23604. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23605. headers);
  23606. ASSERT_TRUE(client2.connect());
  23607. ASSERT_TRUE(client2.send("hello"));
  23608. std::string msg;
  23609. ASSERT_TRUE(client2.read(msg));
  23610. EXPECT_EQ("hello", msg);
  23611. client2.close();
  23612. svr.stop();
  23613. t.join();
  23614. }
  23615. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23616. Server svr;
  23617. std::atomic<int> pre_routing_calls{0};
  23618. std::atomic<int> pre_request_calls{0};
  23619. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23620. pre_routing_calls++;
  23621. if (req.path == "/handled") {
  23622. res.set_content("handled", "text/plain");
  23623. return Server::HandlerResponse::Handled;
  23624. }
  23625. return Server::HandlerResponse::Unhandled;
  23626. });
  23627. svr.set_pre_request_handler([&](const Request &, Response &) {
  23628. pre_request_calls++;
  23629. return Server::HandlerResponse::Unhandled;
  23630. });
  23631. svr.Get("/http", [](const Request &, Response &res) {
  23632. res.set_content("http", "text/plain");
  23633. });
  23634. svr.WebSocket("/ws",
  23635. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23636. auto port = svr.bind_to_any_port("localhost");
  23637. std::thread t([&]() { svr.listen_after_bind(); });
  23638. auto se = detail::scope_exit([&] {
  23639. svr.stop();
  23640. t.join();
  23641. });
  23642. svr.wait_until_ready();
  23643. Headers upgrade = {{"Upgrade", "websocket"},
  23644. {"Connection", "Upgrade"},
  23645. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23646. {"Sec-WebSocket-Version", "13"}};
  23647. auto get = [&](const char *path) {
  23648. pre_routing_calls = 0;
  23649. return Client("localhost", port).Get(path, upgrade);
  23650. };
  23651. // No WebSocket route, but an HTTP one
  23652. auto res = get("/http");
  23653. ASSERT_TRUE(res);
  23654. EXPECT_EQ(StatusCode::OK_200, res->status);
  23655. EXPECT_EQ("http", res->body);
  23656. EXPECT_EQ(1, pre_routing_calls);
  23657. EXPECT_EQ(1, pre_request_calls);
  23658. // No route at all
  23659. res = get("/none");
  23660. ASSERT_TRUE(res);
  23661. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23662. EXPECT_EQ(1, pre_routing_calls);
  23663. // Answered by the pre-routing handler
  23664. res = get("/handled");
  23665. ASSERT_TRUE(res);
  23666. EXPECT_EQ(StatusCode::OK_200, res->status);
  23667. EXPECT_EQ("handled", res->body);
  23668. EXPECT_EQ(1, pre_routing_calls);
  23669. // A WebSocket route
  23670. pre_routing_calls = 0;
  23671. pre_request_calls = 0;
  23672. {
  23673. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23674. "/ws");
  23675. ASSERT_TRUE(client.connect());
  23676. std::string msg;
  23677. ASSERT_TRUE(client.read(msg));
  23678. EXPECT_EQ("ws", msg);
  23679. client.close();
  23680. }
  23681. EXPECT_EQ(1, pre_routing_calls);
  23682. EXPECT_EQ(1, pre_request_calls);
  23683. }
  23684. // An upgrade request answered by a hook leaves its body unread, so that body
  23685. // must not be served as the next request on the connection.
  23686. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23687. Server svr;
  23688. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23689. if (req.path == "/pre-routing") {
  23690. res.set_content("pre-routing", "text/plain");
  23691. return Server::HandlerResponse::Handled;
  23692. }
  23693. return Server::HandlerResponse::Unhandled;
  23694. });
  23695. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23696. if (req.matched_route == "/pre-request") {
  23697. res.set_content("pre-request", "text/plain");
  23698. return Server::HandlerResponse::Handled;
  23699. }
  23700. return Server::HandlerResponse::Unhandled;
  23701. });
  23702. svr.Get("/smuggled", [](const Request &, Response &res) {
  23703. res.set_content("smuggled", "text/plain");
  23704. });
  23705. svr.WebSocket("/pre-request",
  23706. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23707. auto port = svr.bind_to_any_port(HOST);
  23708. std::thread t([&]() { svr.listen_after_bind(); });
  23709. auto se = detail::scope_exit([&] {
  23710. svr.stop();
  23711. t.join();
  23712. });
  23713. svr.wait_until_ready();
  23714. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23715. for (auto path : {"/pre-routing", "/pre-request"}) {
  23716. std::string req = std::string("GET ") + path +
  23717. " HTTP/1.1\r\n"
  23718. "Host: localhost\r\n"
  23719. "Upgrade: websocket\r\n"
  23720. "Connection: Upgrade\r\n"
  23721. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23722. "Sec-WebSocket-Version: 13\r\n"
  23723. "Content-Length: " +
  23724. std::to_string(body.size()) + "\r\n\r\n" + body;
  23725. std::string res;
  23726. ASSERT_TRUE(send_request(5, req, &res, port));
  23727. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23728. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23729. // Only one response, and the body was not served as a request
  23730. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23731. }
  23732. }
  23733. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23734. Server svr;
  23735. std::atomic<int> pre_request_calls{0};
  23736. std::atomic<bool> route_matched{false};
  23737. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23738. pre_request_calls++;
  23739. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23740. if (req.get_header_value("Authorization") != "Bearer token123") {
  23741. res.status = StatusCode::Unauthorized_401;
  23742. res.set_content("Unauthorized", "text/plain");
  23743. return Server::HandlerResponse::Handled;
  23744. }
  23745. return Server::HandlerResponse::Unhandled;
  23746. });
  23747. std::atomic<bool> handler_called{false};
  23748. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23749. handler_called = true;
  23750. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23751. });
  23752. auto port = svr.bind_to_any_port("localhost");
  23753. std::thread t([&]() { svr.listen_after_bind(); });
  23754. svr.wait_until_ready();
  23755. // Without Authorization header - should be rejected before upgrade
  23756. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23757. "/ws/1");
  23758. EXPECT_FALSE(client1.connect());
  23759. EXPECT_FALSE(handler_called);
  23760. EXPECT_EQ(1, pre_request_calls);
  23761. EXPECT_TRUE(route_matched);
  23762. // The rejection is an ordinary HTTP response, not a protocol switch
  23763. {
  23764. Client cli("localhost", port);
  23765. Headers headers = {{"Upgrade", "websocket"},
  23766. {"Connection", "Upgrade"},
  23767. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23768. {"Sec-WebSocket-Version", "13"}};
  23769. auto res = cli.Get("/ws/1", headers);
  23770. ASSERT_TRUE(res);
  23771. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23772. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23773. EXPECT_EQ("Unauthorized", res->body);
  23774. }
  23775. EXPECT_FALSE(handler_called);
  23776. // With Authorization header - should succeed
  23777. Headers headers = {{"Authorization", "Bearer token123"}};
  23778. ws::WebSocketClient client2(
  23779. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23780. ASSERT_TRUE(client2.connect());
  23781. std::string msg;
  23782. ASSERT_TRUE(client2.read(msg));
  23783. EXPECT_EQ("/ws/:id 2", msg);
  23784. EXPECT_TRUE(handler_called);
  23785. client2.close();
  23786. svr.stop();
  23787. t.join();
  23788. }
  23789. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  23790. static Headers websocket_upgrade_headers() {
  23791. return {{"Upgrade", "websocket"},
  23792. {"Connection", "Upgrade"},
  23793. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23794. {"Sec-WebSocket-Version", "13"},
  23795. {"Sec-WebSocket-Protocol", "chat"}};
  23796. }
  23797. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  23798. Server svr;
  23799. svr.set_pre_routing_handler([](const Request &req, Response &) {
  23800. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  23801. return Server::HandlerResponse::Unhandled;
  23802. });
  23803. svr.set_pre_request_handler([](const Request &req, Response &) {
  23804. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  23805. return Server::HandlerResponse::Unhandled;
  23806. });
  23807. svr.set_exception_handler(
  23808. [](const Request &, Response &res, std::exception_ptr ep) {
  23809. try {
  23810. std::rethrow_exception(ep);
  23811. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  23812. });
  23813. auto handler = [](const Request &, ws::WebSocket &) {};
  23814. svr.WebSocket("/pre-routing", handler);
  23815. svr.WebSocket("/pre-request", handler);
  23816. svr.WebSocket("/sub-protocol", handler,
  23817. [](const std::vector<std::string> &) -> std::string {
  23818. throw std::runtime_error("/sub-protocol");
  23819. });
  23820. auto port = svr.bind_to_any_port(HOST);
  23821. ASSERT_GT(port, 0);
  23822. thread t = thread([&] { svr.listen_after_bind(); });
  23823. auto se = detail::scope_exit([&] {
  23824. svr.stop();
  23825. t.join();
  23826. ASSERT_FALSE(svr.is_running());
  23827. });
  23828. svr.wait_until_ready();
  23829. Client cli(HOST, port);
  23830. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  23831. auto res = cli.Get(path, websocket_upgrade_headers());
  23832. if (!res) {
  23833. ADD_FAILURE() << path << ": " << to_string(res.error());
  23834. continue;
  23835. }
  23836. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  23837. EXPECT_EQ(path, res->body);
  23838. }
  23839. }
  23840. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  23841. Server svr;
  23842. svr.set_pre_routing_handler(
  23843. [](const Request &, Response &) -> Server::HandlerResponse {
  23844. throw std::runtime_error("pre-routing");
  23845. });
  23846. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23847. auto port = svr.bind_to_any_port(HOST);
  23848. ASSERT_GT(port, 0);
  23849. thread t = thread([&] { svr.listen_after_bind(); });
  23850. auto se = detail::scope_exit([&] {
  23851. svr.stop();
  23852. t.join();
  23853. ASSERT_FALSE(svr.is_running());
  23854. });
  23855. svr.wait_until_ready();
  23856. Client cli(HOST, port);
  23857. auto res = cli.Get("/ws", websocket_upgrade_headers());
  23858. ASSERT_TRUE(res) << to_string(res.error());
  23859. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  23860. }
  23861. #endif
  23862. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23863. Server svr;
  23864. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23865. // A read timeout is how a handler gets control back. Without it, a handler
  23866. // parked in read() can never write on the connection it is reading.
  23867. ws.set_read_timeout(std::chrono::milliseconds(100));
  23868. std::string msg;
  23869. while (ws.is_open()) {
  23870. auto r = ws.read(msg);
  23871. if (r == httplib::ws::Timeout) {
  23872. ws.send("tick");
  23873. continue;
  23874. }
  23875. if (r == httplib::ws::Fail) { break; }
  23876. ws.send(msg);
  23877. }
  23878. });
  23879. auto port = svr.bind_to_any_port("localhost");
  23880. std::thread t([&]() { svr.listen_after_bind(); });
  23881. svr.wait_until_ready();
  23882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23883. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23884. ASSERT_TRUE(client.connect());
  23885. // The client sends nothing, so anything it receives came out of the
  23886. // handler's timeout path.
  23887. std::string msg;
  23888. ASSERT_EQ(client.read(msg), ws::Text);
  23889. EXPECT_EQ("tick", msg);
  23890. client.close();
  23891. svr.stop();
  23892. t.join();
  23893. }
  23894. // Stream::read may return fewer bytes than asked for. This is that contract at
  23895. // its worst -- one byte per call -- which is what a frame header straddling a
  23896. // read buffer's boundary looks like to the frame parser.
  23897. class WsByteAtATimeStream : public Stream {
  23898. public:
  23899. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23900. bool is_readable() const override { return true; }
  23901. bool wait_readable() const override { return true; }
  23902. bool wait_writable() const override { return true; }
  23903. ssize_t read(char *ptr, size_t size) override {
  23904. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23905. *ptr = data_[pos_++];
  23906. return 1;
  23907. }
  23908. ssize_t write(const char *, size_t size) override {
  23909. return static_cast<ssize_t>(size);
  23910. }
  23911. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23912. ip = "127.0.0.1";
  23913. port = 0;
  23914. }
  23915. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23916. ip = "127.0.0.1";
  23917. port = 0;
  23918. }
  23919. socket_t socket() const override { return INVALID_SOCKET; }
  23920. time_t duration() const override { return 0; }
  23921. private:
  23922. std::string data_;
  23923. size_t pos_ = 0;
  23924. };
  23925. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23926. // The payload uses the 16-bit extended length, so the header, the length
  23927. // and the mask key are all multi-byte fields here. Each used to be read
  23928. // with a single read() call, which fails as soon as one is split. The
  23929. // payload is also a little over one read chunk, so it is read in two.
  23930. std::string body;
  23931. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23932. body += static_cast<char>(i % 251);
  23933. }
  23934. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23935. std::string frame;
  23936. frame += static_cast<char>(0x81); // FIN + Text
  23937. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23938. frame += static_cast<char>(body.size() >> 8);
  23939. frame += static_cast<char>(body.size() & 0xff);
  23940. for (size_t i = 0; i < 4; i++) {
  23941. frame += static_cast<char>(mask[i]);
  23942. }
  23943. for (size_t i = 0; i < body.size(); i++) {
  23944. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23945. }
  23946. WsByteAtATimeStream strm(frame);
  23947. ws::Opcode opcode;
  23948. std::string payload;
  23949. bool fin = false;
  23950. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23951. /*expect_masked=*/true, body.size()),
  23952. ws::impl::FrameRead::Ok);
  23953. EXPECT_TRUE(fin);
  23954. EXPECT_EQ(opcode, ws::Opcode::Text);
  23955. EXPECT_EQ(payload, body);
  23956. }
  23957. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23958. std::string body(2000, 'x');
  23959. std::string frame;
  23960. frame += static_cast<char>(0x82); // FIN + Binary
  23961. frame += static_cast<char>(126); // 16-bit length follows
  23962. frame += static_cast<char>(body.size() >> 8);
  23963. frame += static_cast<char>(body.size() & 0xff);
  23964. frame += body;
  23965. detail::BufferStream strm;
  23966. strm.write(frame.data(), frame.size());
  23967. ws::Opcode opcode;
  23968. std::string payload;
  23969. bool fin;
  23970. EXPECT_EQ(
  23971. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23972. ws::impl::FrameRead::Ok);
  23973. EXPECT_EQ(body, payload);
  23974. }
  23975. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23976. // The header announces the largest payload allowed, and only 3 bytes of it
  23977. // ever arrive.
  23978. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23979. std::string frame;
  23980. frame += static_cast<char>(0x82); // FIN + Binary
  23981. frame += static_cast<char>(127); // 64-bit length follows
  23982. for (int shift = 56; shift >= 0; shift -= 8) {
  23983. frame += static_cast<char>((len >> shift) & 0xff);
  23984. }
  23985. frame += "abc";
  23986. detail::BufferStream strm;
  23987. strm.write(frame.data(), frame.size());
  23988. ws::Opcode opcode;
  23989. std::string payload;
  23990. bool fin;
  23991. EXPECT_EQ(
  23992. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23993. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23994. ws::impl::FrameRead::Fail);
  23995. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23996. }
  23997. TEST(WebSocketTest, QueryStringInHandshake) {
  23998. Server svr;
  23999. std::mutex mtx;
  24000. std::string received_target;
  24001. std::string received_token;
  24002. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24003. {
  24004. std::lock_guard<std::mutex> lock(mtx);
  24005. received_target = req.target;
  24006. if (req.has_param("token")) {
  24007. received_token = req.get_param_value("token");
  24008. }
  24009. }
  24010. std::string msg;
  24011. while (ws.read(msg)) {
  24012. ws.send(msg);
  24013. }
  24014. });
  24015. auto port = svr.bind_to_any_port("localhost");
  24016. std::thread t([&]() { svr.listen_after_bind(); });
  24017. svr.wait_until_ready();
  24018. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24019. "/ws?token=ABC&session=123");
  24020. ASSERT_TRUE(client.connect());
  24021. // Round-trip ensures the handler has run and captured the request.
  24022. ASSERT_TRUE(client.send("hello"));
  24023. std::string msg;
  24024. ASSERT_TRUE(client.read(msg));
  24025. EXPECT_EQ("hello", msg);
  24026. client.close();
  24027. {
  24028. std::lock_guard<std::mutex> lock(mtx);
  24029. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24030. EXPECT_EQ("ABC", received_token);
  24031. }
  24032. svr.stop();
  24033. t.join();
  24034. }
  24035. // Run a handshake against a throwaway server and hand the request the server
  24036. // received back to the caller, so tests can assert on the headers the client
  24037. // actually put on the wire.
  24038. static void capture_websocket_handshake_request(
  24039. const Headers &client_headers,
  24040. std::function<void(const Request &, int port)> verify) {
  24041. Server svr;
  24042. std::mutex mtx;
  24043. Request received;
  24044. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24045. {
  24046. std::lock_guard<std::mutex> lock(mtx);
  24047. received = req;
  24048. }
  24049. std::string msg;
  24050. while (ws.read(msg)) {
  24051. ws.send(msg);
  24052. }
  24053. });
  24054. auto port = svr.bind_to_any_port("localhost");
  24055. std::thread t([&]() { svr.listen_after_bind(); });
  24056. auto se = detail::scope_exit([&] {
  24057. svr.stop();
  24058. t.join();
  24059. });
  24060. svr.wait_until_ready();
  24061. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24062. client_headers);
  24063. ASSERT_TRUE(client.connect());
  24064. ASSERT_TRUE(client.send("hello"));
  24065. std::string msg;
  24066. ASSERT_TRUE(client.read(msg));
  24067. client.close();
  24068. {
  24069. std::lock_guard<std::mutex> lock(mtx);
  24070. verify(received, port);
  24071. }
  24072. }
  24073. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24074. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24075. // Non-default port must be present in the Host header. Default ports
  24076. // (80/443) are omitted; that logic is covered by
  24077. // MakeHostAndPortStringTest.
  24078. EXPECT_EQ("localhost:" + std::to_string(port),
  24079. req.get_header_value("Host"));
  24080. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24081. req.get_header_value("User-Agent"));
  24082. EXPECT_FALSE(req.has_header("Accept"));
  24083. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24084. EXPECT_FALSE(req.has_header("Content-Length"));
  24085. });
  24086. }
  24087. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24088. capture_websocket_handshake_request(
  24089. {{"Host", "example.com"},
  24090. {"User-Agent", "custom-agent"},
  24091. {"X-Custom", "value"}},
  24092. [](const Request &req, int) {
  24093. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24094. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24095. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24096. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24097. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24098. });
  24099. }
  24100. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24101. capture_websocket_handshake_request(
  24102. {{"Upgrade", "bogus"},
  24103. {"Connection", "close"},
  24104. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24105. {"Sec-WebSocket-Version", "8"}},
  24106. [](const Request &req, int) {
  24107. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24108. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24109. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24110. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24111. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24112. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24113. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24114. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24115. req.get_header_value("Sec-WebSocket-Key"));
  24116. });
  24117. }
  24118. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24119. // A header the client refuses to send must abort the handshake before any
  24120. // part of it reaches the wire; a lone request line would otherwise sit in
  24121. // the peer's buffer as a truncated request.
  24122. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24123. ASSERT_NE(INVALID_SOCKET, srv);
  24124. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24125. sockaddr_in addr{};
  24126. addr.sin_family = AF_INET;
  24127. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24128. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24129. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24130. ASSERT_EQ(0, ::listen(srv, 1));
  24131. sockaddr_in bound{};
  24132. socklen_t bound_len = sizeof(bound);
  24133. ASSERT_EQ(
  24134. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24135. auto port = ntohs(bound.sin_port);
  24136. ssize_t received = -1;
  24137. std::thread t([&] {
  24138. // Bound every blocking call so a regression fails the test with a bad
  24139. // value instead of hanging the suite.
  24140. fd_set rfds;
  24141. FD_ZERO(&rfds);
  24142. FD_SET(srv, &rfds);
  24143. timeval tv{5, 0};
  24144. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24145. 0) {
  24146. return;
  24147. }
  24148. sockaddr_in cli_addr{};
  24149. socklen_t cli_len = sizeof(cli_addr);
  24150. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24151. if (cli == INVALID_SOCKET) { return; }
  24152. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24153. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24154. char buf[4096];
  24155. received = ::recv(cli, buf, sizeof(buf), 0);
  24156. });
  24157. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24158. // connect() has already shut the socket down by the time it returns false,
  24159. // so the peer sees EOF without waiting for the client to be destroyed.
  24160. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24161. {{"X-Bad", "a\r\nInjected: 1"}});
  24162. EXPECT_FALSE(client.connect());
  24163. t.join();
  24164. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24165. EXPECT_EQ(0, received);
  24166. }
  24167. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24168. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24169. // contains "upgrade" as a substring is a different token and must not
  24170. // start a WebSocket handshake.
  24171. auto make_request = [](const std::vector<std::string> &connection_values) {
  24172. Request req;
  24173. req.method = "GET";
  24174. req.headers.emplace("Upgrade", "websocket");
  24175. for (const auto &value : connection_values) {
  24176. req.headers.emplace("Connection", value);
  24177. }
  24178. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24179. req.headers.emplace("Sec-WebSocket-Version", "13");
  24180. return req;
  24181. };
  24182. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24183. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24184. EXPECT_TRUE(
  24185. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24186. EXPECT_TRUE(
  24187. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24188. EXPECT_TRUE(
  24189. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24190. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24191. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24192. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24193. EXPECT_FALSE(
  24194. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24195. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24196. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24197. }
  24198. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24199. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24200. // asks recipients to match each protocol-name case-insensitively, and RFC
  24201. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24202. // client naming websocket alongside another protocol, or on a second field
  24203. // line, is offering websocket; a value that merely contains "websocket" as a
  24204. // substring is a different protocol name and is not.
  24205. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24206. Request req;
  24207. req.method = "GET";
  24208. for (const auto &value : upgrade_values) {
  24209. req.headers.emplace("Upgrade", value);
  24210. }
  24211. req.headers.emplace("Connection", "Upgrade");
  24212. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24213. req.headers.emplace("Sec-WebSocket-Version", "13");
  24214. return req;
  24215. };
  24216. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24217. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24218. EXPECT_TRUE(
  24219. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24220. EXPECT_TRUE(
  24221. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24222. EXPECT_TRUE(
  24223. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24224. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24225. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24226. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24227. EXPECT_FALSE(
  24228. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24229. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24230. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24231. }
  24232. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24233. Server svr;
  24234. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24235. auto port = svr.bind_to_any_port("localhost");
  24236. std::thread t([&]() { svr.listen_after_bind(); });
  24237. auto se = detail::scope_exit([&] {
  24238. svr.stop();
  24239. t.join();
  24240. });
  24241. svr.wait_until_ready();
  24242. Headers headers = {{"Upgrade", "websocket"},
  24243. {"Connection", "notupgrade"},
  24244. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24245. {"Sec-WebSocket-Version", "13"}};
  24246. Client cli("localhost", port);
  24247. auto res = cli.Get("/ws", headers);
  24248. // The route exists only as a WebSocket route, so a request that fails the
  24249. // handshake check falls through to ordinary routing.
  24250. ASSERT_TRUE(res);
  24251. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24252. }
  24253. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24254. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24255. // Connection value is the only thing left for the client to reject.
  24256. Server svr;
  24257. svr.Get("/ws", [](const Request &req, Response &res) {
  24258. res.status = StatusCode::SwitchingProtocol_101;
  24259. res.set_header("Upgrade", "websocket");
  24260. res.set_header("Connection", "notupgrade");
  24261. res.set_header("Sec-WebSocket-Accept",
  24262. detail::websocket_accept_key(
  24263. req.get_header_value("Sec-WebSocket-Key")));
  24264. });
  24265. auto port = svr.bind_to_any_port("localhost");
  24266. std::thread t([&]() { svr.listen_after_bind(); });
  24267. auto se = detail::scope_exit([&] {
  24268. svr.stop();
  24269. t.join();
  24270. });
  24271. svr.wait_until_ready();
  24272. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24273. auto res = client.connect();
  24274. EXPECT_FALSE(res);
  24275. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24276. EXPECT_FALSE(client.is_open());
  24277. }
  24278. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24279. Server svr;
  24280. svr.Get("/ws", [](const Request &req, Response &res) {
  24281. res.status = StatusCode::SwitchingProtocol_101;
  24282. res.set_header("Upgrade", "websocket");
  24283. res.set_header("Connection", "Upgrade");
  24284. res.set_header("Sec-WebSocket-Accept",
  24285. detail::websocket_accept_key(
  24286. req.get_header_value("Sec-WebSocket-Key")));
  24287. res.set_header("Sec-WebSocket-Protocol", "admin");
  24288. });
  24289. auto port = svr.bind_to_any_port("localhost");
  24290. std::thread t([&]() { svr.listen_after_bind(); });
  24291. auto se = detail::scope_exit([&] {
  24292. svr.stop();
  24293. t.join();
  24294. });
  24295. svr.wait_until_ready();
  24296. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24297. // Server selects a subprotocol the client never offered
  24298. {
  24299. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24300. ws::WebSocketClient client(url, headers);
  24301. auto res = client.connect();
  24302. EXPECT_FALSE(res);
  24303. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24304. EXPECT_FALSE(client.is_open());
  24305. EXPECT_TRUE(client.subprotocol().empty());
  24306. }
  24307. // Client offered none but the server named one anyway
  24308. {
  24309. ws::WebSocketClient client(url);
  24310. auto res = client.connect();
  24311. EXPECT_FALSE(res);
  24312. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24313. EXPECT_FALSE(client.is_open());
  24314. EXPECT_TRUE(client.subprotocol().empty());
  24315. }
  24316. }
  24317. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24318. // The socket path doubles as the URL host, so it must not contain '/'.
  24319. const char *shard = getenv("GTEST_SHARD_INDEX");
  24320. const std::string sock_path =
  24321. shard ? std::string("httplib-ws-") + shard + ".sock"
  24322. : std::string("httplib-ws.sock");
  24323. std::remove(sock_path.c_str());
  24324. Server svr;
  24325. std::mutex mtx;
  24326. std::string received_host;
  24327. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24328. {
  24329. std::lock_guard<std::mutex> lock(mtx);
  24330. received_host = req.get_header_value("Host");
  24331. }
  24332. std::string msg;
  24333. while (ws.read(msg)) {
  24334. ws.send(msg);
  24335. }
  24336. });
  24337. svr.set_address_family(AF_UNIX);
  24338. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24339. auto se = detail::scope_exit([&] {
  24340. svr.stop();
  24341. t.join();
  24342. std::remove(sock_path.c_str());
  24343. });
  24344. svr.wait_until_ready();
  24345. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24346. client.set_address_family(AF_UNIX);
  24347. ASSERT_TRUE(client.connect());
  24348. ASSERT_TRUE(client.send("hello"));
  24349. std::string msg;
  24350. ASSERT_TRUE(client.read(msg));
  24351. client.close();
  24352. {
  24353. std::lock_guard<std::mutex> lock(mtx);
  24354. // There is no host:port for a Unix socket, so the same "localhost"
  24355. // placeholder the HTTP client uses is expected.
  24356. EXPECT_EQ("localhost", received_host);
  24357. }
  24358. }
  24359. // Two threads must never parse WebSocket frames from the same stream.
  24360. // close() used to read the peer's Close reply with its own frame read, so it
  24361. // raced a reader thread that was in the middle of a payload: the payload loop
  24362. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24363. // so bytes taken by close() were replaced with bytes from further along the
  24364. // stream. The message kept its length and silently changed content.
  24365. //
  24366. // The raw peer below sends a frame header plus part of the payload, waits for
  24367. // the handler to call close(), and only then sends the rest. Whichever thread
  24368. // would win the race for those bytes, the message must arrive intact, because
  24369. // close() must not touch the stream while read() owns it.
  24370. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24371. #ifndef _WIN32
  24372. signal(SIGPIPE, SIG_IGN);
  24373. #endif
  24374. const size_t payload_len = 120; // fits the 7-bit length field
  24375. const size_t prefix_len = 8;
  24376. const int attempts = 8;
  24377. std::string expected(payload_len, '\0');
  24378. for (size_t i = 0; i < payload_len; i++) {
  24379. expected[i] = static_cast<char>('a' + i % 26);
  24380. }
  24381. std::atomic<bool> peer_stalled{false};
  24382. std::atomic<bool> handler_done{false};
  24383. std::mutex received_mutex;
  24384. std::vector<std::string> received;
  24385. // Bound every wait, so a regression fails the test instead of hanging the
  24386. // suite.
  24387. auto wait_for = [](const std::atomic<bool> &flag) {
  24388. for (int i = 0; i < 500 && !flag; i++) {
  24389. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24390. }
  24391. };
  24392. Server svr;
  24393. svr.set_websocket_ping_interval(0);
  24394. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24395. std::thread reader([&]() {
  24396. std::string msg;
  24397. while (ws.read(msg)) {
  24398. std::lock_guard<std::mutex> guard(received_mutex);
  24399. received.push_back(msg);
  24400. }
  24401. });
  24402. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24403. // inside read_websocket_frame() when close() runs.
  24404. wait_for(peer_stalled);
  24405. ws.close();
  24406. reader.join();
  24407. handler_done = true;
  24408. });
  24409. auto port = svr.bind_to_any_port("127.0.0.1");
  24410. std::thread t([&]() { svr.listen_after_bind(); });
  24411. auto se = detail::scope_exit([&] {
  24412. svr.stop();
  24413. t.join();
  24414. });
  24415. svr.wait_until_ready();
  24416. auto send_bytes = [](socket_t s, const std::string &data) {
  24417. #ifdef _WIN32
  24418. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24419. #else
  24420. auto n = ::send(s, data.data(), data.size(), 0);
  24421. #endif
  24422. return n == static_cast<decltype(n)>(data.size());
  24423. };
  24424. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24425. // Every length used here fits the 7-bit length field.
  24426. auto masked_header = [](uint8_t first_byte, size_t len) {
  24427. std::string h;
  24428. h += static_cast<char>(first_byte);
  24429. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24430. h.append(4, '\0'); // mask key
  24431. return h;
  24432. };
  24433. for (int attempt = 0; attempt < attempts; attempt++) {
  24434. peer_stalled = false;
  24435. handler_done = false;
  24436. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24437. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24438. auto se_sock = detail::scope_exit([&] {
  24439. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24440. });
  24441. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24442. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24443. sockaddr_in addr{};
  24444. addr.sin_family = AF_INET;
  24445. addr.sin_port = htons(static_cast<uint16_t>(port));
  24446. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24447. ASSERT_EQ(
  24448. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24449. << "attempt " << attempt;
  24450. ASSERT_TRUE(send_bytes(sock,
  24451. "GET /ws HTTP/1.1\r\n"
  24452. "Host: 127.0.0.1\r\n"
  24453. "Upgrade: websocket\r\n"
  24454. "Connection: Upgrade\r\n"
  24455. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24456. "Sec-WebSocket-Version: 13\r\n"
  24457. "\r\n"))
  24458. << "attempt " << attempt;
  24459. std::string response;
  24460. while (response.find("\r\n\r\n") == std::string::npos) {
  24461. char buf[512];
  24462. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24463. if (n <= 0) { break; }
  24464. response.append(buf, static_cast<size_t>(n));
  24465. }
  24466. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24467. << "attempt " << attempt;
  24468. // Send the header of a Binary message but only the first prefix_len bytes
  24469. // of its payload, leaving the reader thread stalled inside the payload.
  24470. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24471. expected.substr(0, prefix_len)))
  24472. << "attempt " << attempt;
  24473. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24474. peer_stalled = true;
  24475. // Let close() send its Close frame and park in its own read before the
  24476. // rest of the payload arrives, so both threads are waiting for it.
  24477. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24478. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24479. close_frame += static_cast<char>(0x03); // status 1000
  24480. close_frame += static_cast<char>(0xE8);
  24481. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24482. << "attempt " << attempt;
  24483. // Closing the peer releases the reader thread even on the buggy path,
  24484. // where it waits for bytes another thread already consumed.
  24485. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24486. detail::close_socket(sock);
  24487. sock = INVALID_SOCKET;
  24488. wait_for(handler_done);
  24489. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24490. }
  24491. std::lock_guard<std::mutex> guard(received_mutex);
  24492. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24493. << "a message in flight when close() ran was dropped";
  24494. for (size_t i = 0; i < received.size(); i++) {
  24495. EXPECT_EQ(expected, received[i]) << "message " << i;
  24496. }
  24497. }
  24498. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24499. // returning the socket, or INVALID_SOCKET.
  24500. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24501. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24502. if (sock == INVALID_SOCKET) { return sock; }
  24503. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24504. sockaddr_in addr{};
  24505. addr.sin_family = AF_INET;
  24506. addr.sin_port = htons(static_cast<uint16_t>(port));
  24507. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24508. std::string req = "GET " + path +
  24509. " HTTP/1.1\r\n"
  24510. "Host: 127.0.0.1\r\n"
  24511. "Upgrade: websocket\r\n"
  24512. "Connection: Upgrade\r\n"
  24513. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24514. "Sec-WebSocket-Version: 13\r\n"
  24515. "\r\n";
  24516. std::string res;
  24517. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24518. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24519. static_cast<ssize_t>(req.size())) {
  24520. char c;
  24521. while (res.find("\r\n\r\n") == std::string::npos &&
  24522. ::recv(sock, &c, 1, 0) == 1) {
  24523. res += c;
  24524. }
  24525. }
  24526. if (res.find(" 101 ") == std::string::npos) {
  24527. detail::close_socket(sock);
  24528. return INVALID_SOCKET;
  24529. }
  24530. return sock;
  24531. }
  24532. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24533. // The payload must fit the 7-bit length field.
  24534. static std::string masked_frame(uint8_t first_byte,
  24535. const std::string &payload) {
  24536. std::string f;
  24537. f += static_cast<char>(first_byte);
  24538. f += static_cast<char>(0x80 | payload.size());
  24539. f.append(4, '\0');
  24540. return f + payload;
  24541. }
  24542. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24543. std::atomic<bool> done{false};
  24544. std::string received;
  24545. Server svr;
  24546. svr.set_websocket_ping_interval(0);
  24547. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24548. std::string msg;
  24549. if (ws.read(msg) == ws::Binary) { received = msg; }
  24550. done = true;
  24551. });
  24552. auto port = svr.bind_to_any_port("127.0.0.1");
  24553. std::thread t([&]() { svr.listen_after_bind(); });
  24554. auto se = detail::scope_exit([&] {
  24555. svr.stop();
  24556. t.join();
  24557. });
  24558. svr.wait_until_ready();
  24559. auto sock = connect_raw_websocket(port, "/ws");
  24560. ASSERT_NE(INVALID_SOCKET, sock);
  24561. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24562. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24563. masked_frame(0x89, "p") + // FIN + Ping
  24564. masked_frame(0x80, "lo"); // FIN + Continuation
  24565. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24566. for (int i = 0; i < 500 && !done; i++) {
  24567. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24568. }
  24569. ASSERT_TRUE(done);
  24570. EXPECT_EQ("Hello", received);
  24571. // The Ping between the fragments is answered with a Pong.
  24572. char pong[3];
  24573. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24574. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24575. }
  24576. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24577. Server svr;
  24578. svr.set_websocket_ping_interval(-1);
  24579. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24580. std::string msg;
  24581. while (ws.read(msg)) {}
  24582. });
  24583. auto port = svr.bind_to_any_port("127.0.0.1");
  24584. std::thread t([&]() { svr.listen_after_bind(); });
  24585. auto se = detail::scope_exit([&] {
  24586. svr.stop();
  24587. t.join();
  24588. });
  24589. svr.wait_until_ready();
  24590. auto sock = connect_raw_websocket(port, "/ws");
  24591. ASSERT_NE(INVALID_SOCKET, sock);
  24592. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24593. // Nothing comes while the client stays quiet.
  24594. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24595. char c;
  24596. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24597. }
  24598. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24599. // and that has to end a read() already waiting on the peer, on every platform.
  24600. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24601. // The peer sends no pings, and its handler never calls read(), which is
  24602. // where pongs are written.
  24603. std::mutex mutex;
  24604. std::condition_variable cv;
  24605. auto release = false;
  24606. svr.set_websocket_ping_interval(0);
  24607. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24608. std::unique_lock<std::mutex> lock(mutex);
  24609. cv.wait(lock, [&] { return release; });
  24610. });
  24611. auto port = svr.bind_to_any_port(HOST);
  24612. std::thread t([&]() { svr.listen_after_bind(); });
  24613. auto se = detail::scope_exit([&] {
  24614. {
  24615. std::lock_guard<std::mutex> lock(mutex);
  24616. release = true;
  24617. }
  24618. cv.notify_all();
  24619. svr.stop();
  24620. t.join();
  24621. });
  24622. svr.wait_until_ready();
  24623. ws::WebSocketClient client(std::string(scheme) +
  24624. "://localhost:" + std::to_string(port) + "/ws");
  24625. #ifdef CPPHTTPLIB_SSL_ENABLED
  24626. client.enable_server_certificate_verification(false);
  24627. #endif
  24628. // A ping a second, given up on after two go unanswered: about 3s
  24629. client.set_websocket_ping_interval(1);
  24630. client.set_websocket_max_missed_pongs(2);
  24631. // Well past that, so that a read the timeout ends instead stands out
  24632. client.set_read_timeout(10);
  24633. ASSERT_TRUE(client.connect());
  24634. auto start = std::chrono::steady_clock::now();
  24635. std::string msg;
  24636. EXPECT_EQ(ws::Fail, client.read(msg));
  24637. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24638. std::chrono::steady_clock::now() - start)
  24639. .count(),
  24640. 6000);
  24641. EXPECT_FALSE(client.is_open());
  24642. }
  24643. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24644. Server svr;
  24645. check_pong_timeout_ends_read(svr, "ws");
  24646. }
  24647. #ifdef CPPHTTPLIB_SSL_ENABLED
  24648. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24649. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24650. ASSERT_TRUE(svr.is_valid());
  24651. check_pong_timeout_ends_read(svr, "wss");
  24652. }
  24653. #endif
  24654. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24655. Server svr;
  24656. svr.set_websocket_ping_interval(0);
  24657. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24658. std::string msg;
  24659. while (ws.read(msg)) {}
  24660. });
  24661. auto port = svr.bind_to_any_port("127.0.0.1");
  24662. std::thread t([&]() { svr.listen_after_bind(); });
  24663. auto se = detail::scope_exit([&] {
  24664. svr.stop();
  24665. t.join();
  24666. });
  24667. svr.wait_until_ready();
  24668. // Each Close payload and the reply it should get: an echo when valid, 1002
  24669. // otherwise.
  24670. std::vector<std::pair<std::string, std::string>> cases = {
  24671. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24672. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24673. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24674. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24675. };
  24676. // Also between the fragments of a message.
  24677. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24678. for (const auto &c : cases) {
  24679. auto sock = connect_raw_websocket(port, "/ws");
  24680. ASSERT_NE(INVALID_SOCKET, sock);
  24681. auto frames = prefix + masked_frame(0x88, c.first);
  24682. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24683. std::string reply;
  24684. char buf[256];
  24685. while (reply.size() < 2 + c.second.size()) {
  24686. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24687. if (n <= 0) { break; }
  24688. reply.append(buf, static_cast<size_t>(n));
  24689. }
  24690. detail::close_socket(sock);
  24691. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24692. c.second,
  24693. reply);
  24694. }
  24695. }
  24696. }
  24697. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24698. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24699. protected:
  24700. void SetUp() override {
  24701. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24702. SERVER_PRIVATE_KEY_FILE);
  24703. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24704. std::string msg;
  24705. ws::ReadResult ret;
  24706. while ((ret = ws.read(msg))) {
  24707. if (ret == ws::Binary) {
  24708. ws.send(msg.data(), msg.size());
  24709. } else {
  24710. ws.send(msg);
  24711. }
  24712. }
  24713. });
  24714. port_ = server_->bind_to_any_port(HOST);
  24715. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24716. server_->wait_until_ready();
  24717. }
  24718. void TearDown() override {
  24719. server_->stop();
  24720. if (server_thread_.joinable()) { server_thread_.join(); }
  24721. }
  24722. std::unique_ptr<SSLServer> server_;
  24723. std::thread server_thread_;
  24724. int port_ = 0;
  24725. };
  24726. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24727. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24728. {
  24729. ws::WebSocketClient client(url);
  24730. client.enable_server_certificate_verification(false);
  24731. auto calls = 0;
  24732. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24733. calls++;
  24734. return false;
  24735. });
  24736. EXPECT_FALSE(client.connect());
  24737. EXPECT_GT(calls, 0);
  24738. }
  24739. {
  24740. ws::WebSocketClient client(url);
  24741. client.enable_server_certificate_verification(false);
  24742. client.set_session_verifier([](tls::session_t) {
  24743. return SSLVerifierResponse::CertificateRejected;
  24744. });
  24745. EXPECT_FALSE(client.connect());
  24746. }
  24747. {
  24748. ws::WebSocketClient client(url);
  24749. client.enable_server_certificate_verification(false);
  24750. client.set_session_verifier([](tls::session_t) {
  24751. return SSLVerifierResponse::CertificateAccepted;
  24752. });
  24753. EXPECT_TRUE(client.connect());
  24754. }
  24755. }
  24756. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24757. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24758. "/ws-echo");
  24759. client.enable_server_certificate_verification(false);
  24760. ASSERT_TRUE(client.connect());
  24761. ASSERT_TRUE(client.is_open());
  24762. ASSERT_TRUE(client.send("Hello WSS"));
  24763. std::string msg;
  24764. EXPECT_EQ(ws::Text, client.read(msg));
  24765. EXPECT_EQ("Hello WSS", msg);
  24766. client.close();
  24767. }
  24768. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24769. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24770. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24771. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24772. // client (without calling close() first) is the only path that runs
  24773. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24774. // bug exactly.
  24775. //
  24776. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24777. // when linked against an instrumented libssl; run under Valgrind to catch it
  24778. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24779. // suite (the freed session otherwise stalls on the close handshake) — this test
  24780. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24781. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24782. {
  24783. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24784. "/ws-echo");
  24785. client.enable_server_certificate_verification(false);
  24786. client.set_read_timeout(2, 0);
  24787. client.set_write_timeout(2, 0);
  24788. ASSERT_TRUE(client.connect());
  24789. ASSERT_TRUE(client.is_open());
  24790. ASSERT_TRUE(client.send("still open"));
  24791. // Intentionally do NOT call client.close(): leaving scope runs
  24792. // shutdown_and_close() with the WebSocket still open, which must send the
  24793. // close frame while the TLS session is still alive.
  24794. }
  24795. }
  24796. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24797. // shutdown_and_close() at the start of connect(), reproducing the same
  24798. // use-after-free within the test body rather than at scope exit. The second
  24799. // connect must succeed and echo, proving the close handshake ran over a live
  24800. // session. See the note above about memory-tool requirements.
  24801. TEST_F(WebSocketSSLIntegrationTest,
  24802. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24803. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24804. "/ws-echo");
  24805. client.enable_server_certificate_verification(false);
  24806. client.set_read_timeout(2, 0);
  24807. client.set_write_timeout(2, 0);
  24808. ASSERT_TRUE(client.connect());
  24809. ASSERT_TRUE(client.is_open());
  24810. ASSERT_TRUE(client.send("still open"));
  24811. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24812. // the still-open connection, which must not touch a freed TLS session.
  24813. ASSERT_TRUE(client.connect());
  24814. ASSERT_TRUE(client.is_open());
  24815. ASSERT_TRUE(client.send("after reconnect"));
  24816. std::string msg;
  24817. EXPECT_EQ(ws::Text, client.read(msg));
  24818. EXPECT_EQ("after reconnect", msg);
  24819. client.close();
  24820. }
  24821. #endif
  24822. #ifdef CPPHTTPLIB_SSL_ENABLED
  24823. class WebSocketSSLCATest : public ::testing::Test {
  24824. protected:
  24825. void SetUp() override {
  24826. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24827. SERVER_PRIVATE_KEY_FILE);
  24828. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24829. std::string msg;
  24830. while (ws.read(msg)) {
  24831. ws.send(msg);
  24832. }
  24833. });
  24834. port_ = server_->bind_to_any_port("127.0.0.1");
  24835. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24836. server_->wait_until_ready();
  24837. }
  24838. void TearDown() override {
  24839. server_->stop();
  24840. if (server_thread_.joinable()) { server_thread_.join(); }
  24841. }
  24842. std::string url() const {
  24843. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24844. }
  24845. std::unique_ptr<SSLServer> server_;
  24846. std::thread server_thread_;
  24847. int port_ = 0;
  24848. };
  24849. // A custom CA loaded as PEM verifies the server with full certificate
  24850. // verification enabled
  24851. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24852. ws::WebSocketClient client(url());
  24853. std::string cert;
  24854. read_file(SERVER_CERT2_FILE, cert);
  24855. client.load_ca_cert_store(cert.c_str(), cert.size());
  24856. ASSERT_TRUE(client.connect());
  24857. ASSERT_TRUE(client.send("hello"));
  24858. std::string msg;
  24859. EXPECT_EQ(ws::Text, client.read(msg));
  24860. EXPECT_EQ("hello", msg);
  24861. client.close();
  24862. }
  24863. // A custom CA that does not cover the server must fail verification (the
  24864. // custom CA is exclusive; system certs are not loaded alongside it)
  24865. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24866. ws::WebSocketClient client(url());
  24867. std::string cert;
  24868. read_file(CLIENT_CA_CERT_FILE, cert);
  24869. client.load_ca_cert_store(cert.c_str(), cert.size());
  24870. auto res = client.connect();
  24871. ASSERT_FALSE(res);
  24872. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24873. EXPECT_EQ(-1, res.status());
  24874. EXPECT_NE(0u, res.ssl_backend_error());
  24875. }
  24876. // The same CA as a file path rather than PEM in memory
  24877. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24878. ws::WebSocketClient client(url());
  24879. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24880. ASSERT_TRUE(client.connect());
  24881. ASSERT_TRUE(client.send("hello"));
  24882. std::string msg;
  24883. EXPECT_EQ(ws::Text, client.read(msg));
  24884. EXPECT_EQ("hello", msg);
  24885. client.close();
  24886. }
  24887. // ...and a CA file that does not cover the server still fails, so it is the
  24888. // path above that decides the outcome
  24889. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24890. ws::WebSocketClient client(url());
  24891. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24892. ASSERT_FALSE(client.connect());
  24893. }
  24894. // Regression test: reconnecting with a native custom CA store used to reuse
  24895. // a store handle the previous TLS context had already freed (use-after-free
  24896. // under the OpenSSL backend). The context now lives as long as the client.
  24897. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24898. ws::WebSocketClient client(url());
  24899. std::string cert;
  24900. read_file(SERVER_CERT2_FILE, cert);
  24901. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24902. ASSERT_TRUE(client.connect());
  24903. client.close();
  24904. ASSERT_TRUE(client.connect());
  24905. ASSERT_TRUE(client.send("again"));
  24906. std::string msg;
  24907. EXPECT_EQ(ws::Text, client.read(msg));
  24908. EXPECT_EQ("again", msg);
  24909. client.close();
  24910. }
  24911. // Regression test: a certificate with a trusted chain but no identity match
  24912. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24913. // verification entirely for IP hosts, so this connection succeeded there.
  24914. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24915. // chain verification while the identity check must still fail.
  24916. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24917. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24918. ASSERT_TRUE(svr.is_valid());
  24919. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24920. std::string msg;
  24921. while (ws.read(msg)) {
  24922. ws.send(msg);
  24923. }
  24924. });
  24925. auto port = svr.bind_to_any_port("127.0.0.1");
  24926. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24927. auto se = detail::scope_exit([&] {
  24928. svr.stop();
  24929. t.join();
  24930. });
  24931. svr.wait_until_ready();
  24932. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24933. "/echo");
  24934. std::string cert;
  24935. read_file(SERVER_CERT_FILE, cert);
  24936. client.load_ca_cert_store(cert.c_str(), cert.size());
  24937. ASSERT_FALSE(client.connect());
  24938. }
  24939. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24940. // SNI, so nothing binds the host name to the TLS session. These bind the
  24941. // server to "localhost" instead, the only shape that exercises the SNI and
  24942. // hostname-verification path with certificate verification left enabled.
  24943. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24944. protected:
  24945. void Start(const char *cert_file) {
  24946. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24947. SERVER_PRIVATE_KEY_FILE);
  24948. ASSERT_TRUE(server_->is_valid());
  24949. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24950. std::string msg;
  24951. while (ws.read(msg)) {
  24952. ws.send(msg);
  24953. }
  24954. });
  24955. port_ = server_->bind_to_any_port("localhost");
  24956. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24957. server_->wait_until_ready();
  24958. }
  24959. void TearDown() override {
  24960. if (server_) { server_->stop(); }
  24961. if (server_thread_.joinable()) { server_thread_.join(); }
  24962. }
  24963. std::string url() const {
  24964. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24965. }
  24966. std::unique_ptr<SSLServer> server_;
  24967. std::thread server_thread_;
  24968. int port_ = 0;
  24969. };
  24970. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24971. // out and the connection is usable
  24972. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24973. Start(SERVER_CERT2_FILE);
  24974. ws::WebSocketClient client(url());
  24975. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24976. ASSERT_TRUE(client.connect());
  24977. ASSERT_TRUE(client.send("hello"));
  24978. std::string msg;
  24979. EXPECT_EQ(ws::Text, client.read(msg));
  24980. EXPECT_EQ("hello", msg);
  24981. client.close();
  24982. }
  24983. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24984. // while the identity check must still reject "localhost"
  24985. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24986. Start(SERVER_CERT_FILE);
  24987. ws::WebSocketClient client(url());
  24988. client.set_ca_cert_path(SERVER_CERT_FILE);
  24989. auto res = client.connect();
  24990. ASSERT_FALSE(res);
  24991. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24992. EXPECT_EQ(-1, res.status());
  24993. }
  24994. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24995. // disabled: the chain is still checked, only the identity check is skipped
  24996. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24997. Start(SERVER_CERT_FILE);
  24998. ws::WebSocketClient client(url());
  24999. client.set_ca_cert_path(SERVER_CERT_FILE);
  25000. client.enable_server_hostname_verification(false);
  25001. ASSERT_TRUE(client.connect());
  25002. ASSERT_TRUE(client.send("hello"));
  25003. std::string msg;
  25004. EXPECT_EQ(ws::Text, client.read(msg));
  25005. EXPECT_EQ("hello", msg);
  25006. client.close();
  25007. }
  25008. // A CA that did not sign the server certificate fails the chain, even though
  25009. // the name would match
  25010. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25011. Start(SERVER_CERT2_FILE);
  25012. ws::WebSocketClient client(url());
  25013. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25014. ASSERT_FALSE(client.connect());
  25015. }
  25016. // With verification disabled, neither the chain nor the name is checked
  25017. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25018. Start(SERVER_CERT_FILE);
  25019. ws::WebSocketClient client(url());
  25020. client.enable_server_certificate_verification(false);
  25021. ASSERT_TRUE(client.connect());
  25022. ASSERT_TRUE(client.send("hello"));
  25023. std::string msg;
  25024. EXPECT_EQ(ws::Text, client.read(msg));
  25025. EXPECT_EQ("hello", msg);
  25026. client.close();
  25027. }
  25028. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25029. protected:
  25030. void SetUp() override {
  25031. server_ = httplib::detail::make_unique<SSLServer>(
  25032. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25033. ASSERT_TRUE(server_->is_valid());
  25034. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25035. std::string msg;
  25036. while (ws.read(msg)) {
  25037. ws.send(msg);
  25038. }
  25039. });
  25040. port_ = server_->bind_to_any_port("localhost");
  25041. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25042. server_->wait_until_ready();
  25043. }
  25044. void TearDown() override {
  25045. server_->stop();
  25046. if (server_thread_.joinable()) { server_thread_.join(); }
  25047. }
  25048. std::string url() const {
  25049. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25050. }
  25051. void ConnectWithClientCert(const std::string &client_cert_file,
  25052. const std::string &client_private_key_file,
  25053. const char *private_key_password) {
  25054. std::string cert_pem, key_pem;
  25055. read_file(client_cert_file, cert_pem);
  25056. read_file(client_private_key_file, key_pem);
  25057. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25058. key_pem.c_str(), key_pem.size(),
  25059. private_key_password};
  25060. ConnectWithPem(pem);
  25061. }
  25062. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25063. ws::WebSocketClient client(url(), pem);
  25064. ASSERT_TRUE(client.is_valid());
  25065. client.enable_server_certificate_verification(false);
  25066. ASSERT_TRUE(client.connect());
  25067. ASSERT_TRUE(client.send("hello"));
  25068. std::string msg;
  25069. EXPECT_EQ(ws::Text, client.read(msg));
  25070. EXPECT_EQ("hello", msg);
  25071. client.close();
  25072. }
  25073. std::unique_ptr<SSLServer> server_;
  25074. std::thread server_thread_;
  25075. int port_ = 0;
  25076. };
  25077. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25078. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25079. }
  25080. // Control for the tests above: the fixture's server really does require a
  25081. // client certificate, so it is the PEM the constructor installed that decides
  25082. // the outcome.
  25083. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25084. ws::WebSocketClient client(url());
  25085. ASSERT_TRUE(client.is_valid());
  25086. client.enable_server_certificate_verification(false);
  25087. EXPECT_FALSE(client.connect());
  25088. }
  25089. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25090. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25091. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25092. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25093. }
  25094. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25095. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25096. std::string cert_pem, key_pem;
  25097. read_file(CLIENT_CERT_FILE, cert_pem);
  25098. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25099. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25100. std::vector<char> key(key_pem.begin(), key_pem.end());
  25101. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25102. key.size(), nullptr};
  25103. ConnectWithPem(pem);
  25104. }
  25105. #endif
  25106. #if !defined(_WIN32)
  25107. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25108. auto secret_dir = std::string("./symlink_test_secret");
  25109. auto served_dir = std::string("./symlink_test_served");
  25110. auto secret_file = secret_dir + "/secret.txt";
  25111. auto symlink_path = served_dir + "/escape";
  25112. // Setup: create directories and files
  25113. mkdir(secret_dir.c_str(), 0755);
  25114. mkdir(served_dir.c_str(), 0755);
  25115. {
  25116. std::ofstream ofs(secret_file);
  25117. ofs << "SECRET_DATA";
  25118. }
  25119. // Create symlink using absolute path so it resolves correctly
  25120. #ifdef PATH_MAX
  25121. char abs_secret[PATH_MAX];
  25122. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25123. #else
  25124. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25125. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25126. ASSERT_NE(nullptr, abs_secret);
  25127. #endif
  25128. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25129. auto se = detail::scope_exit([&] {
  25130. unlink(symlink_path.c_str());
  25131. unlink(secret_file.c_str());
  25132. rmdir(served_dir.c_str());
  25133. rmdir(secret_dir.c_str());
  25134. });
  25135. Server svr;
  25136. svr.set_mount_point("/", served_dir);
  25137. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25138. auto se2 = detail::scope_exit([&] {
  25139. svr.stop();
  25140. listen_thread.join();
  25141. });
  25142. svr.wait_until_ready();
  25143. Client cli("localhost", PORT);
  25144. // Symlink pointing outside base dir should be blocked
  25145. auto res = cli.Get("/escape/secret.txt");
  25146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25147. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25148. }
  25149. #endif
  25150. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25151. // "GET /smuggled" request), reads the first response, and only then sends the
  25152. // embedded request as the body. Returns how many times /smuggled ran.
  25153. //
  25154. // The body is sent AFTER receiving the first response (as in the original
  25155. // PoC) so that the stream_line_reader cannot buffer it together with the
  25156. // headers of the first request.
  25157. static int count_smuggled_requests(const std::string &outer_head,
  25158. std::string &first_response) {
  25159. Server svr;
  25160. svr.set_mount_point("/", "./www");
  25161. std::atomic<int> smuggled_count(0);
  25162. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25163. smuggled_count++;
  25164. res.set_content("oops", "text/plain");
  25165. });
  25166. svr.Post("/post", [&](const Request &req, Response &res) {
  25167. res.set_content(req.body, "text/plain");
  25168. });
  25169. auto port = svr.bind_to_any_port("localhost");
  25170. thread t = thread([&] { svr.listen_after_bind(); });
  25171. auto se = detail::scope_exit([&] {
  25172. svr.stop();
  25173. t.join();
  25174. });
  25175. svr.wait_until_ready();
  25176. auto error = Error::Success;
  25177. auto sock = detail::create_client_socket(
  25178. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25179. /*connection_timeout_sec=*/2, 0,
  25180. /*read_timeout_sec=*/2, 0,
  25181. /*write_timeout_sec=*/2, 0, std::string(), error);
  25182. EXPECT_NE(INVALID_SOCKET, sock);
  25183. if (sock == INVALID_SOCKET) { return -1; }
  25184. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25185. // The "smuggled" request will be sent as the body of the outer request
  25186. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25187. "Host: localhost\r\n"
  25188. "Connection: close\r\n"
  25189. "\r\n";
  25190. auto head = outer_head;
  25191. auto len = std::to_string(smuggled.size());
  25192. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25193. pos = head.find("{len}", pos + len.size())) {
  25194. head.replace(pos, 5, len);
  25195. }
  25196. // Step 1: Send only the outer request headers (no body yet)
  25197. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25198. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25199. // Step 2: Read the first response
  25200. char buf[4096];
  25201. for (;;) {
  25202. auto n = recv(sock, buf, sizeof(buf), 0);
  25203. if (n <= 0) break;
  25204. first_response.append(buf, static_cast<size_t>(n));
  25205. // Stop once we have a complete response (headers + body)
  25206. auto hdr_end = first_response.find("\r\n\r\n");
  25207. if (hdr_end != std::string::npos) {
  25208. // Check for Content-Length to know when the body is complete
  25209. auto cl_pos = first_response.find("Content-Length:");
  25210. if (cl_pos != std::string::npos) {
  25211. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25212. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25213. auto cl = std::stoul(
  25214. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25215. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25216. } else {
  25217. break; // No Content-Length, assume headers-only response
  25218. }
  25219. }
  25220. }
  25221. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25222. // vulnerable server the keep-alive loop reads this as a second request. The
  25223. // server may already have closed the connection, so the result is ignored.
  25224. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25225. // Half-close so that a server which drained the body sees EOF and closes,
  25226. // instead of the read below waiting for the read timeout.
  25227. #ifdef _WIN32
  25228. ::shutdown(sock, SD_SEND);
  25229. #else
  25230. ::shutdown(sock, SHUT_WR);
  25231. #endif
  25232. // Step 4: Read until the server closes the connection
  25233. for (;;) {
  25234. auto n = recv(sock, buf, sizeof(buf), 0);
  25235. if (n <= 0) break;
  25236. }
  25237. return smuggled_count.load();
  25238. }
  25239. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25240. // A GET request with Content-Length to a static file handler must have its
  25241. // body drained before the keep-alive connection is reused. Otherwise the
  25242. // unread body bytes are interpreted as the next HTTP request.
  25243. std::string first_response;
  25244. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25245. "Host: localhost\r\n"
  25246. "Content-Length: {len}\r\n"
  25247. "\r\n",
  25248. first_response));
  25249. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25250. }
  25251. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25252. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25253. // be answered with 400 and the connection closed. Treating it as "no body"
  25254. // leaves the body to be parsed as the next request.
  25255. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25256. const char *targets[] = {
  25257. "GET /file", // handler that never reads the body
  25258. "GET /not-found", // no handler matches (404)
  25259. "POST /post", // handler that reads the body
  25260. };
  25261. for (auto target : targets) {
  25262. for (auto value : values) {
  25263. std::string first_response;
  25264. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25265. " HTTP/1.1\r\n"
  25266. "Host: localhost\r\n"
  25267. "Content-Length: " +
  25268. value + "\r\n\r\n",
  25269. first_response))
  25270. << target << " with Content-Length: " << value;
  25271. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25272. << target << " with Content-Length: " << value;
  25273. }
  25274. }
  25275. }
  25276. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25277. // A 400 for an unparseable request line leaves the rest of the message
  25278. // unread, so the connection must be closed rather than reused.
  25279. std::string first_response;
  25280. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25281. "Host: localhost\r\n"
  25282. "Content-Length: {len}\r\n"
  25283. "\r\n",
  25284. first_response));
  25285. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25286. }
  25287. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25288. // Same as above for a header block that fails to parse.
  25289. std::string first_response;
  25290. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25291. "Host: localhost\r\n"
  25292. "Bad Header\r\n"
  25293. "Content-Length: {len}\r\n"
  25294. "\r\n",
  25295. first_response));
  25296. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25297. }
  25298. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25299. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25300. // server must not read another request on that connection, even when the
  25301. // request had no body to drain.
  25302. std::string first_response;
  25303. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25304. "Host: localhost\r\n"
  25305. "\r\n",
  25306. first_response));
  25307. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25308. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25309. }
  25310. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25311. // A content reader that stops early leaves the stream inside the body.
  25312. // Draining the whole Content-Length from there, or reading the body again,
  25313. // reads into the next request, and whatever follows is parsed as a request
  25314. // of its own.
  25315. Server svr;
  25316. std::atomic<int> smuggled_count(0);
  25317. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25318. svr.Post("/upload", [](const Request &req, Response &res,
  25319. const ContentReader &content_reader) {
  25320. // Stop at the last chunk, so the whole body has been read however it
  25321. // arrives.
  25322. auto length = req.get_header_value_u64("Content-Length");
  25323. size_t total = 0;
  25324. auto consumed = content_reader([&](const char *, size_t n) {
  25325. total += n;
  25326. return total < length;
  25327. });
  25328. EXPECT_FALSE(consumed);
  25329. if (req.has_param("retry")) {
  25330. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25331. }
  25332. // Replace the 400 the aborted read set, which would close the connection.
  25333. res.set_redirect("/done");
  25334. });
  25335. auto port = svr.bind_to_any_port(HOST);
  25336. thread t = thread([&] { svr.listen_after_bind(); });
  25337. auto se = detail::scope_exit([&] {
  25338. svr.stop();
  25339. t.join();
  25340. });
  25341. svr.wait_until_ready();
  25342. // A front end sees the second request as a POST whose body is the GET. The
  25343. // first body is as long as the POST's headers, so draining it again reads
  25344. // exactly those and leaves the GET to be parsed next.
  25345. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25346. "Host: localhost\r\n"
  25347. "\r\n";
  25348. std::string second_head = "POST /post HTTP/1.1\r\n"
  25349. "Host: localhost\r\n"
  25350. "Content-Length: " +
  25351. std::to_string(inner.size()) +
  25352. "\r\n"
  25353. "\r\n";
  25354. for (auto target : {"/upload", "/upload?retry"}) {
  25355. smuggled_count = 0;
  25356. std::string request = "POST " + std::string(target) +
  25357. " HTTP/1.1\r\n"
  25358. "Host: localhost\r\n"
  25359. "Content-Length: " +
  25360. std::to_string(second_head.size()) +
  25361. "\r\n"
  25362. "\r\n" +
  25363. std::string(second_head.size(), 'A') + second_head +
  25364. inner;
  25365. std::string response;
  25366. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25367. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25368. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25369. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25370. EXPECT_EQ(0, smuggled_count.load()) << target;
  25371. }
  25372. }
  25373. // An error response closes the connection anyway, so the body is left unread
  25374. // with a redirect, such as one to a login page.
  25375. static void serve_redirects(Server &svr,
  25376. const std::function<void(int)> &client) {
  25377. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25378. res.set_redirect("/login");
  25379. return Server::HandlerResponse::Handled;
  25380. });
  25381. auto port = svr.bind_to_any_port(HOST);
  25382. ASSERT_GT(port, 0);
  25383. thread t = thread([&] { svr.listen_after_bind(); });
  25384. auto se = detail::scope_exit([&] {
  25385. svr.stop();
  25386. t.join();
  25387. ASSERT_FALSE(svr.is_running());
  25388. });
  25389. svr.wait_until_ready();
  25390. client(port);
  25391. }
  25392. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25393. Server svr;
  25394. serve_redirects(svr, [](int port) {
  25395. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25396. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25397. std::to_string(body.size()) + "\r\n\r\n" + body +
  25398. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25399. std::string resp;
  25400. ASSERT_TRUE(send_request(1, req, &resp, port));
  25401. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25402. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25403. });
  25404. }
  25405. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25406. Server svr;
  25407. svr.set_read_timeout(0, 200000);
  25408. serve_redirects(svr, [](int port) {
  25409. // A byte every 100 ms keeps each read within the read timeout, but not the
  25410. // body as a whole, so the server closes and the bytes sent after that fail.
  25411. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25412. "Content-Length: 10\r\n\r\n"};
  25413. parts.resize(11, "x");
  25414. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25415. });
  25416. }
  25417. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25418. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25419. // must be rejected with 400 Bad Request.
  25420. Server svr;
  25421. svr.Post("/test", [&](const Request &, Response &res) {
  25422. res.set_content("ok", "text/plain");
  25423. });
  25424. thread t = thread([&] { svr.listen(HOST, PORT); });
  25425. auto se = detail::scope_exit([&] {
  25426. svr.stop();
  25427. t.join();
  25428. ASSERT_FALSE(svr.is_running());
  25429. });
  25430. svr.wait_until_ready();
  25431. // Exact "chunked"
  25432. {
  25433. auto req = "POST /test HTTP/1.1\r\n"
  25434. "Host: localhost\r\n"
  25435. "Content-Length: 5\r\n"
  25436. "Transfer-Encoding: chunked\r\n"
  25437. "Connection: close\r\n"
  25438. "\r\n"
  25439. "hello";
  25440. std::string response;
  25441. ASSERT_TRUE(send_request(1, req, &response));
  25442. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25443. response.substr(0, response.find("\r\n")));
  25444. }
  25445. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25446. {
  25447. auto req = "POST /test HTTP/1.1\r\n"
  25448. "Host: localhost\r\n"
  25449. "Content-Length: 5\r\n"
  25450. "Transfer-Encoding: gzip, chunked\r\n"
  25451. "Connection: close\r\n"
  25452. "\r\n"
  25453. "hello";
  25454. std::string response;
  25455. ASSERT_TRUE(send_request(1, req, &response));
  25456. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25457. response.substr(0, response.find("\r\n")));
  25458. }
  25459. }
  25460. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25461. Server svr;
  25462. svr.Post("/test", [&](const Request &, Response &res) {
  25463. res.set_content("ok", "text/plain");
  25464. });
  25465. thread t = thread([&] { svr.listen(HOST, PORT); });
  25466. auto se = detail::scope_exit([&] {
  25467. svr.stop();
  25468. t.join();
  25469. ASSERT_FALSE(svr.is_running());
  25470. });
  25471. svr.wait_until_ready();
  25472. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25473. // length cannot be determined, so the server must answer 400 and close
  25474. // rather than treat the request as bodyless and leave the body in the
  25475. // socket for the next request to pick up.
  25476. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25477. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25478. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25479. std::string response;
  25480. ASSERT_TRUE(send_request(1, req, &response));
  25481. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25482. response.substr(0, response.find("\r\n")))
  25483. << transfer_encoding;
  25484. }
  25485. // RFC 9110 5.3: the codings may also be split across several
  25486. // Transfer-Encoding lines, which combine in the order they were received.
  25487. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25488. // just like the single-line "chunked, gzip" above.
  25489. {
  25490. auto req = "POST /test HTTP/1.1\r\n"
  25491. "Host: localhost\r\n"
  25492. "Transfer-Encoding: chunked\r\n"
  25493. "Transfer-Encoding: gzip\r\n"
  25494. "\r\n"
  25495. "0\r\n\r\n";
  25496. std::string response;
  25497. ASSERT_TRUE(send_request(1, req, &response));
  25498. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25499. response.substr(0, response.find("\r\n")));
  25500. }
  25501. }
  25502. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25503. Server svr;
  25504. svr.Post("/test", [&](const Request &, Response &res) {
  25505. res.set_content("ok", "text/plain");
  25506. });
  25507. auto port = svr.bind_to_any_port(HOST);
  25508. ASSERT_GT(port, 0);
  25509. thread t = thread([&] { svr.listen_after_bind(); });
  25510. auto se = detail::scope_exit([&] {
  25511. svr.stop();
  25512. t.join();
  25513. ASSERT_FALSE(svr.is_running());
  25514. });
  25515. svr.wait_until_ready();
  25516. for (auto transfer_encoding :
  25517. {"Transfer-Encoding: gzip, chunked\r\n",
  25518. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25519. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25520. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25521. transfer_encoding + "\r\n0\r\n\r\n";
  25522. std::string response;
  25523. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25524. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25525. response.substr(0, response.find("\r\n")))
  25526. << transfer_encoding;
  25527. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25528. << transfer_encoding;
  25529. }
  25530. }
  25531. // Regression for issue #2450: a DELETE without Content-Length on a
  25532. // keep-alive connection must not let the post-response drain consume the
  25533. // next request's bytes.
  25534. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25535. Server svr;
  25536. std::atomic<int> delete_count(0);
  25537. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25538. delete_count++;
  25539. res.status = StatusCode::NoContent_204;
  25540. });
  25541. auto port = svr.bind_to_any_port(HOST);
  25542. thread t = thread([&] { svr.listen_after_bind(); });
  25543. auto se = detail::scope_exit([&] {
  25544. svr.stop();
  25545. t.join();
  25546. });
  25547. svr.wait_until_ready();
  25548. auto error = Error::Success;
  25549. auto sock = detail::create_client_socket(
  25550. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25551. /*connection_timeout_sec=*/2, 0,
  25552. /*read_timeout_sec=*/2, 0,
  25553. /*write_timeout_sec=*/2, 0, std::string(), error);
  25554. ASSERT_NE(INVALID_SOCKET, sock);
  25555. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25556. auto send_request_and_read_response = [&](const std::string &req,
  25557. std::string &out) -> bool {
  25558. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25559. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25560. char buf[4096];
  25561. for (;;) {
  25562. auto n = recv(sock, buf, sizeof(buf), 0);
  25563. if (n <= 0) { return !out.empty(); }
  25564. out.append(buf, static_cast<size_t>(n));
  25565. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25566. }
  25567. };
  25568. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25569. "Host: localhost\r\n"
  25570. "\r\n";
  25571. std::string resp1;
  25572. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25573. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25574. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25575. "Host: localhost\r\n"
  25576. "Connection: close\r\n"
  25577. "\r\n";
  25578. std::string resp2;
  25579. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25580. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25581. EXPECT_EQ(2, delete_count.load());
  25582. }
  25583. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25584. Server svr;
  25585. svr.Post("/ingest", [&](const Request &, Response &res,
  25586. const ContentReader &content_reader) {
  25587. auto consumed = content_reader([](const char *, size_t) { return false; });
  25588. EXPECT_FALSE(consumed);
  25589. res.status = StatusCode::Conflict_409;
  25590. res.set_header("Connection", "close");
  25591. });
  25592. auto port = svr.bind_to_any_port(HOST);
  25593. thread t = thread([&] { svr.listen_after_bind(); });
  25594. auto se = detail::scope_exit([&] {
  25595. svr.stop();
  25596. t.join();
  25597. });
  25598. svr.wait_until_ready();
  25599. auto error = Error::Success;
  25600. auto sock = detail::create_client_socket(
  25601. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25602. /*connection_timeout_sec=*/2, 0,
  25603. /*read_timeout_sec=*/1, 0,
  25604. /*write_timeout_sec=*/2, 0, std::string(), error);
  25605. ASSERT_NE(INVALID_SOCKET, sock);
  25606. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25607. std::string request = "POST /ingest HTTP/1.1\r\n"
  25608. "Host: localhost\r\n"
  25609. "Transfer-Encoding: chunked\r\n"
  25610. "\r\n"
  25611. "4\r\n"
  25612. "data\r\n";
  25613. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25614. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25615. std::string response;
  25616. ssize_t received = 0;
  25617. do {
  25618. char buf[4096];
  25619. received = recv(sock, buf, sizeof(buf), 0);
  25620. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25621. } while (received > 0);
  25622. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25623. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25624. EXPECT_EQ(0, received);
  25625. }
  25626. namespace no_proxy_test {
  25627. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25628. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25629. // calling listen().
  25630. class ScopedServer {
  25631. public:
  25632. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25633. ~ScopedServer() {
  25634. svr_.stop();
  25635. if (th_.joinable()) { th_.join(); }
  25636. }
  25637. Server &svr() { return svr_; }
  25638. int port() const { return port_; }
  25639. void listen() {
  25640. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25641. svr_.wait_until_ready();
  25642. }
  25643. private:
  25644. Server svr_;
  25645. std::thread th_;
  25646. int port_ = 0;
  25647. };
  25648. class ProxyAndTargetServers {
  25649. public:
  25650. ProxyAndTargetServers() {
  25651. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25652. proxy_hits_++;
  25653. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25654. res.set_content("via-proxy", "text/plain");
  25655. });
  25656. target_.Get(".*", [this](const Request &req, Response &res) {
  25657. target_hits_++;
  25658. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25659. res.set_content("direct", "text/plain");
  25660. });
  25661. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25662. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25663. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25664. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25665. proxy_mock_.wait_until_ready();
  25666. target_.wait_until_ready();
  25667. }
  25668. ~ProxyAndTargetServers() {
  25669. proxy_mock_.stop();
  25670. target_.stop();
  25671. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25672. if (target_thread_.joinable()) { target_thread_.join(); }
  25673. }
  25674. Server &proxy_mock() { return proxy_mock_; }
  25675. Server &target() { return target_; }
  25676. int proxy_port() const { return proxy_port_; }
  25677. int target_port() const { return target_port_; }
  25678. int proxy_hits() const { return proxy_hits_.load(); }
  25679. int target_hits() const { return target_hits_.load(); }
  25680. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25681. void reset_counters() {
  25682. proxy_hits_ = 0;
  25683. target_hits_ = 0;
  25684. last_had_proxy_authz_ = false;
  25685. }
  25686. private:
  25687. Server proxy_mock_;
  25688. Server target_;
  25689. std::thread proxy_thread_;
  25690. std::thread target_thread_;
  25691. int proxy_port_ = 0;
  25692. int target_port_ = 0;
  25693. std::atomic<int> proxy_hits_{0};
  25694. std::atomic<int> target_hits_{0};
  25695. std::atomic<bool> last_had_proxy_authz_{false};
  25696. };
  25697. inline std::unique_ptr<Client> make_client(const std::string &host,
  25698. ProxyAndTargetServers &s) {
  25699. auto cli = detail::make_unique<Client>(host, s.target_port());
  25700. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25701. cli->set_proxy("127.0.0.1", s.proxy_port());
  25702. return cli;
  25703. }
  25704. } // namespace no_proxy_test
  25705. using no_proxy_test::make_client;
  25706. using no_proxy_test::ProxyAndTargetServers;
  25707. // A stream request carries the credentials a buffered request does
  25708. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25709. no_proxy_test::ScopedServer origin;
  25710. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25711. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25712. });
  25713. origin.listen();
  25714. Client cli("127.0.0.1", origin.port());
  25715. cli.set_basic_auth("user", "pass");
  25716. auto handle = cli.open_stream("GET", "/x");
  25717. ASSERT_TRUE(handle.is_valid());
  25718. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25719. Client bearer("127.0.0.1", origin.port());
  25720. bearer.set_bearer_token_auth("tok");
  25721. auto handle2 = bearer.open_stream("GET", "/x");
  25722. ASSERT_TRUE(handle2.is_valid());
  25723. EXPECT_EQ("Bearer tok", read_all(handle2));
  25724. }
  25725. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25726. // takes its own credentials, as for a buffered request
  25727. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25728. std::string target, authz, proxy_authz;
  25729. no_proxy_test::ScopedServer proxy;
  25730. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25731. target = req.target;
  25732. authz = req.get_header_value("Authorization");
  25733. proxy_authz = req.get_header_value("Proxy-Authorization");
  25734. res.set_content("ok", "text/plain");
  25735. });
  25736. proxy.listen();
  25737. Client cli("origin.example", 8080);
  25738. cli.set_proxy("127.0.0.1", proxy.port());
  25739. cli.set_proxy_basic_auth("puser", "ppass");
  25740. cli.set_basic_auth("user", "pass");
  25741. auto handle = cli.open_stream("GET", "/x");
  25742. ASSERT_TRUE(handle.is_valid());
  25743. EXPECT_EQ("ok", read_all(handle));
  25744. EXPECT_EQ("http://origin.example:8080/x", target);
  25745. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25746. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25747. }
  25748. // In absolute-form the path follows the authority, so a path that does not
  25749. // begin with '/' would make the proxy connect to another host
  25750. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  25751. std::vector<std::string> targets;
  25752. no_proxy_test::ScopedServer proxy;
  25753. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25754. targets.push_back(req.target);
  25755. res.set_content("ok", "text/plain");
  25756. });
  25757. proxy.listen();
  25758. Client cli("origin.example", 8080);
  25759. cli.set_proxy("127.0.0.1", proxy.port());
  25760. cli.set_basic_auth("user", "pass");
  25761. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  25762. auto res = cli.Get(path);
  25763. EXPECT_FALSE(res) << path;
  25764. auto handle = cli.open_stream("GET", path);
  25765. EXPECT_FALSE(handle.is_valid()) << path;
  25766. }
  25767. EXPECT_TRUE(targets.empty());
  25768. auto res = cli.Get("/x");
  25769. ASSERT_TRUE(res);
  25770. ASSERT_EQ(1u, targets.size());
  25771. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  25772. }
  25773. TEST(NoProxyTest, ExactHostnameBypasses) {
  25774. ProxyAndTargetServers s;
  25775. auto cli = make_client("example.com", s);
  25776. cli->set_no_proxy({"example.com"});
  25777. auto res = cli->Get("/");
  25778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25779. EXPECT_EQ(0, s.proxy_hits());
  25780. EXPECT_EQ(1, s.target_hits());
  25781. }
  25782. TEST(NoProxyTest, SubdomainBypasses) {
  25783. ProxyAndTargetServers s;
  25784. auto cli = make_client("foo.example.com", s);
  25785. cli->set_no_proxy({"example.com"});
  25786. auto res = cli->Get("/");
  25787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25788. EXPECT_EQ(0, s.proxy_hits());
  25789. EXPECT_EQ(1, s.target_hits());
  25790. }
  25791. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25792. // Regression guard: "evilexample.com" must not be considered a subdomain
  25793. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25794. // check would let traffic bypass the proxy and leak credentials direct
  25795. // to the attacker host.
  25796. ProxyAndTargetServers s;
  25797. auto cli = make_client("evilexample.com", s);
  25798. cli->set_no_proxy({"example.com"});
  25799. auto res = cli->Get("/");
  25800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25801. EXPECT_GE(s.proxy_hits(), 1);
  25802. EXPECT_EQ(0, s.target_hits());
  25803. }
  25804. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25805. ProxyAndTargetServers s;
  25806. auto cli = make_client("example.com.evil.com", s);
  25807. cli->set_no_proxy({"example.com"});
  25808. auto res = cli->Get("/");
  25809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25810. EXPECT_GE(s.proxy_hits(), 1);
  25811. EXPECT_EQ(0, s.target_hits());
  25812. }
  25813. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25814. ProxyAndTargetServers s;
  25815. auto cli = make_client("example.com", s);
  25816. cli->set_no_proxy({".example.com"});
  25817. auto res = cli->Get("/");
  25818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25819. EXPECT_EQ(0, s.proxy_hits());
  25820. EXPECT_EQ(1, s.target_hits());
  25821. }
  25822. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25823. ProxyAndTargetServers s;
  25824. auto cli = make_client("Example.COM", s);
  25825. cli->set_no_proxy({"EXAMPLE.com"});
  25826. auto res = cli->Get("/");
  25827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25828. EXPECT_EQ(0, s.proxy_hits());
  25829. EXPECT_EQ(1, s.target_hits());
  25830. }
  25831. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25832. ProxyAndTargetServers s;
  25833. auto cli = make_client("example.com.", s);
  25834. cli->set_no_proxy({"example.com"});
  25835. auto res = cli->Get("/");
  25836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25837. EXPECT_EQ(0, s.proxy_hits());
  25838. EXPECT_EQ(1, s.target_hits());
  25839. }
  25840. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25841. // Trailing dots must be normalized on BOTH sides — host and entry.
  25842. // An implementation that only strips the host-side trailing dot would
  25843. // fail to match host "example.com" against entry "example.com." because
  25844. // a literal substring search would compare 11 chars against 12.
  25845. ProxyAndTargetServers s;
  25846. auto cli = make_client("example.com", s);
  25847. cli->set_no_proxy({"example.com."});
  25848. auto res = cli->Get("/");
  25849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25850. EXPECT_EQ(0, s.proxy_hits());
  25851. EXPECT_EQ(1, s.target_hits());
  25852. }
  25853. TEST(NoProxyTest, WildcardBypassesEverything) {
  25854. ProxyAndTargetServers s;
  25855. auto cli = make_client("anything.invalid.test", s);
  25856. cli->set_no_proxy({"*"});
  25857. auto res = cli->Get("/");
  25858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25859. EXPECT_EQ(0, s.proxy_hits());
  25860. EXPECT_EQ(1, s.target_hits());
  25861. }
  25862. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25863. ProxyAndTargetServers s;
  25864. Client cli("127.0.0.1", s.target_port());
  25865. cli.set_proxy("127.0.0.1", s.proxy_port());
  25866. cli.set_no_proxy({"127.0.0.1"});
  25867. auto res = cli.Get("/");
  25868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25869. EXPECT_EQ(0, s.proxy_hits());
  25870. EXPECT_EQ(1, s.target_hits());
  25871. }
  25872. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25873. ProxyAndTargetServers s;
  25874. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25875. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25876. cli.set_proxy("127.0.0.1", s.proxy_port());
  25877. cli.set_no_proxy({"::1"});
  25878. auto res = cli.Get("/");
  25879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25880. EXPECT_EQ(0, s.proxy_hits());
  25881. EXPECT_EQ(1, s.target_hits());
  25882. }
  25883. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25884. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25885. // must still be recognized as IPv6 for CIDR matching. Implementations
  25886. // that detect IPv6 only when the host begins with '[' would parse the
  25887. // host as a hostname and miss the match.
  25888. ProxyAndTargetServers s;
  25889. Client cli("fe80::1", s.target_port());
  25890. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25891. cli.set_proxy("127.0.0.1", s.proxy_port());
  25892. cli.set_no_proxy({"fe80::/10"});
  25893. auto res = cli.Get("/");
  25894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25895. EXPECT_EQ(0, s.proxy_hits());
  25896. EXPECT_EQ(1, s.target_hits());
  25897. }
  25898. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25899. ProxyAndTargetServers s;
  25900. Client cli("::1", s.target_port());
  25901. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25902. cli.set_proxy("127.0.0.1", s.proxy_port());
  25903. cli.set_no_proxy({"[::1]"});
  25904. auto res = cli.Get("/");
  25905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25906. EXPECT_EQ(0, s.proxy_hits());
  25907. EXPECT_EQ(1, s.target_hits());
  25908. }
  25909. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25910. ProxyAndTargetServers s;
  25911. Client cli("fe80::1", s.target_port());
  25912. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25913. cli.set_proxy("127.0.0.1", s.proxy_port());
  25914. cli.set_no_proxy({"[fe80::]/10"});
  25915. auto res = cli.Get("/");
  25916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25917. EXPECT_EQ(0, s.proxy_hits());
  25918. EXPECT_EQ(1, s.target_hits());
  25919. }
  25920. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25921. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25922. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25923. // tricks via address-family conversion.
  25924. ProxyAndTargetServers s;
  25925. Client cli("::ffff:127.0.0.1", s.target_port());
  25926. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25927. cli.set_proxy("127.0.0.1", s.proxy_port());
  25928. cli.set_no_proxy({"127.0.0.1"});
  25929. auto res = cli.Get("/");
  25930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25931. EXPECT_GE(s.proxy_hits(), 1);
  25932. EXPECT_EQ(0, s.target_hits());
  25933. }
  25934. TEST(NoProxyTest, IPv4CidrMatch) {
  25935. ProxyAndTargetServers s;
  25936. Client cli("127.0.0.1", s.target_port());
  25937. cli.set_proxy("127.0.0.1", s.proxy_port());
  25938. cli.set_no_proxy({"127.0.0.0/8"});
  25939. auto res = cli.Get("/");
  25940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25941. EXPECT_EQ(0, s.proxy_hits());
  25942. EXPECT_EQ(1, s.target_hits());
  25943. }
  25944. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25945. ProxyAndTargetServers s;
  25946. Client cli("127.0.0.1", s.target_port());
  25947. cli.set_proxy("127.0.0.1", s.proxy_port());
  25948. cli.set_no_proxy({"10.0.0.0/8"});
  25949. auto res = cli.Get("/");
  25950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25951. EXPECT_GE(s.proxy_hits(), 1);
  25952. EXPECT_EQ(0, s.target_hits());
  25953. }
  25954. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25955. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25956. // IPv4 target matches.
  25957. ProxyAndTargetServers s;
  25958. Client cli("127.0.0.1", s.target_port());
  25959. cli.set_proxy("127.0.0.1", s.proxy_port());
  25960. cli.set_no_proxy({"0.0.0.0/0"});
  25961. auto res = cli.Get("/");
  25962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25963. EXPECT_EQ(0, s.proxy_hits());
  25964. EXPECT_EQ(1, s.target_hits());
  25965. }
  25966. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25967. ProxyAndTargetServers s;
  25968. Client cli("127.0.0.1", s.target_port());
  25969. cli.set_proxy("127.0.0.1", s.proxy_port());
  25970. cli.set_no_proxy({"127.0.0.1"});
  25971. auto res = cli.Get("/");
  25972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25973. EXPECT_EQ(0, s.proxy_hits());
  25974. EXPECT_EQ(1, s.target_hits());
  25975. }
  25976. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25977. ProxyAndTargetServers s;
  25978. Client cli("127.0.0.1", s.target_port());
  25979. cli.set_proxy("127.0.0.1", s.proxy_port());
  25980. cli.set_no_proxy({"127.0.0.0/33"});
  25981. auto res = cli.Get("/");
  25982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25983. EXPECT_GE(s.proxy_hits(), 1);
  25984. EXPECT_EQ(0, s.target_hits());
  25985. }
  25986. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25987. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25988. ProxyAndTargetServers s;
  25989. Client cli("127.0.0.1", s.target_port());
  25990. cli.set_proxy("127.0.0.1", s.proxy_port());
  25991. cli.set_no_proxy({"127.0.0.1/"});
  25992. auto res = cli.Get("/");
  25993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25994. EXPECT_GE(s.proxy_hits(), 1);
  25995. EXPECT_EQ(0, s.target_hits());
  25996. }
  25997. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25998. ProxyAndTargetServers s;
  25999. auto cli = make_client("internal.corp", s);
  26000. cli->set_proxy_basic_auth("u", "p");
  26001. cli->set_no_proxy({"internal.corp"});
  26002. auto res = cli->Get("/");
  26003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26004. EXPECT_EQ(1, s.target_hits());
  26005. EXPECT_EQ(0, s.proxy_hits());
  26006. EXPECT_FALSE(s.last_had_proxy_authz())
  26007. << "Proxy-Authorization must not be sent direct to the target";
  26008. }
  26009. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26010. ProxyAndTargetServers s;
  26011. auto cli = make_client("public.example", s);
  26012. cli->set_proxy_basic_auth("u", "p");
  26013. cli->set_no_proxy({"internal.corp"}); // does not match
  26014. auto res = cli->Get("/");
  26015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26016. EXPECT_GE(s.proxy_hits(), 1);
  26017. EXPECT_TRUE(s.last_had_proxy_authz());
  26018. }
  26019. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26020. std::atomic<int> hits{0};
  26021. std::atomic<int> hits_with_authz{0};
  26022. no_proxy_test::ScopedServer proxy_mock;
  26023. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26024. hits++;
  26025. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26026. if (req.target.find("/redir") != std::string::npos) {
  26027. res.set_redirect("http://other.example/landed");
  26028. } else {
  26029. res.set_content("via-proxy", "text/plain");
  26030. }
  26031. });
  26032. proxy_mock.listen();
  26033. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26034. hits = 0;
  26035. hits_with_authz = 0;
  26036. Client cli("public.example", 80);
  26037. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26038. cli.set_proxy_basic_auth(c.first, c.second);
  26039. cli.set_follow_location(true);
  26040. // The redirect to another host goes through the proxy as well
  26041. auto res = cli.Get("/redir");
  26042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26043. EXPECT_EQ(2, hits.load());
  26044. EXPECT_EQ(2, hits_with_authz.load());
  26045. }
  26046. }
  26047. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26048. ProxyAndTargetServers s;
  26049. auto cli = make_client("anything.test", s);
  26050. auto res = cli->Get("/");
  26051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26052. EXPECT_GE(s.proxy_hits(), 1);
  26053. EXPECT_EQ(0, s.target_hits());
  26054. }
  26055. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26056. ProxyAndTargetServers s;
  26057. auto cli = make_client("example.com", s);
  26058. cli->set_no_proxy({"example.com:8080"});
  26059. auto res = cli->Get("/");
  26060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26061. EXPECT_GE(s.proxy_hits(), 1);
  26062. EXPECT_EQ(0, s.target_hits());
  26063. }
  26064. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26065. ProxyAndTargetServers s;
  26066. auto cli = make_client("anything.test", s);
  26067. cli->set_no_proxy({"", " ", "\t"});
  26068. auto res = cli->Get("/");
  26069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26070. EXPECT_GE(s.proxy_hits(), 1);
  26071. EXPECT_EQ(0, s.target_hits());
  26072. }
  26073. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26074. // An entry with leading/trailing whitespace must still match — env-style
  26075. // values are commonly pasted with stray spaces and an implementation
  26076. // that feeds the raw token directly to inet_pton would fail to match
  26077. // valid CIDRs because of the spaces.
  26078. ProxyAndTargetServers s;
  26079. Client cli("127.0.0.1", s.target_port());
  26080. cli.set_proxy("127.0.0.1", s.proxy_port());
  26081. cli.set_no_proxy({" 127.0.0.0/8 "});
  26082. auto res = cli.Get("/");
  26083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26084. EXPECT_EQ(0, s.proxy_hits());
  26085. EXPECT_EQ(1, s.target_hits());
  26086. }
  26087. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26088. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26089. // go direct and must NOT carry Proxy-Authorization.
  26090. std::atomic<int> proxy_hits{0};
  26091. std::atomic<int> target_hits{0};
  26092. std::atomic<bool> target_saw_authz{false};
  26093. no_proxy_test::ScopedServer proxy_mock, target;
  26094. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26095. proxy_hits++;
  26096. res.status = 302;
  26097. res.set_header("Location", "http://127.0.0.1:" +
  26098. std::to_string(target.port()) + "/landed");
  26099. });
  26100. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26101. target_hits++;
  26102. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26103. res.set_content("direct", "text/plain");
  26104. });
  26105. proxy_mock.listen();
  26106. target.listen();
  26107. Client cli("public.example", target.port());
  26108. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26109. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26110. cli.set_proxy_basic_auth("u", "p");
  26111. cli.set_no_proxy({"127.0.0.1"});
  26112. cli.set_follow_location(true);
  26113. auto res = cli.Get("/redir");
  26114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26115. EXPECT_GE(proxy_hits.load(), 1);
  26116. EXPECT_GE(target_hits.load(), 1);
  26117. EXPECT_FALSE(target_saw_authz.load());
  26118. }
  26119. #ifdef CPPHTTPLIB_SSL_ENABLED
  26120. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26121. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26122. // proxy creds would be sent to the (possibly hostile) origin.
  26123. std::atomic<int> target_hits{0};
  26124. std::atomic<bool> target_saw_proxy_authz{false};
  26125. no_proxy_test::ScopedServer target;
  26126. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26127. target_hits++;
  26128. if (req.has_header("Proxy-Authorization")) {
  26129. target_saw_proxy_authz = true;
  26130. }
  26131. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26132. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26133. "nonce=\"abc\", algorithm=MD5");
  26134. });
  26135. target.listen();
  26136. // The proxy address is set to the target's port: the bypass MUST kick in;
  26137. // if it doesn't, the test still routes "via proxy" to the same server and
  26138. // the Proxy-Authorization assertion below catches the leak.
  26139. Client cli("evil.example", target.port());
  26140. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26141. cli.set_proxy("127.0.0.1", target.port());
  26142. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26143. cli.set_no_proxy({"evil.example"});
  26144. auto res = cli.Get("/x");
  26145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26146. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26147. EXPECT_EQ(1, target_hits.load());
  26148. EXPECT_FALSE(target_saw_proxy_authz.load());
  26149. }
  26150. #endif
  26151. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26152. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26153. std::atomic<int> proxy_hits{0};
  26154. std::atomic<int> bypass_hits{0};
  26155. std::atomic<bool> proxy_saw_c_url{false};
  26156. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26157. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26158. proxy_hits++;
  26159. if (req.path.find("/start") != std::string::npos) {
  26160. res.status = 302;
  26161. res.set_header("Location", "http://127.0.0.1:" +
  26162. std::to_string(bypass_server.port()) +
  26163. "/middle");
  26164. return;
  26165. }
  26166. if (req.path.find("/end") != std::string::npos) {
  26167. proxy_saw_c_url = true;
  26168. res.set_content("c-via-proxy", "text/plain");
  26169. return;
  26170. }
  26171. res.set_content("unexpected", "text/plain");
  26172. });
  26173. // public.example's "advertised" port is arbitrary (the request never lands
  26174. // there — it goes through the proxy), but use a dynamic value to stay
  26175. // friendly with sharded parallel runs.
  26176. int public_port = bypass_server.port();
  26177. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26178. bypass_hits++;
  26179. res.status = 302;
  26180. res.set_header("Location", "http://public.example:" +
  26181. std::to_string(public_port) + "/end");
  26182. });
  26183. proxy_mock.listen();
  26184. bypass_server.listen();
  26185. Client cli("public.example", public_port);
  26186. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26187. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26188. cli.set_no_proxy({"127.0.0.1"});
  26189. cli.set_follow_location(true);
  26190. auto res = cli.Get("/start");
  26191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26192. EXPECT_EQ(StatusCode::OK_200, res->status);
  26193. EXPECT_EQ("c-via-proxy", res->body);
  26194. EXPECT_GE(proxy_hits.load(), 2);
  26195. EXPECT_GE(bypass_hits.load(), 1);
  26196. EXPECT_TRUE(proxy_saw_c_url.load());
  26197. }
  26198. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26199. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26200. // request reconnects to the correct endpoint.
  26201. std::atomic<int> proxy_hits{0};
  26202. std::atomic<int> target_hits{0};
  26203. no_proxy_test::ScopedServer proxy_mock, target;
  26204. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26205. proxy_hits++;
  26206. res.set_content("via-proxy", "text/plain");
  26207. });
  26208. target.svr().Get(".*", [&](const Request &, Response &res) {
  26209. target_hits++;
  26210. res.set_content("direct", "text/plain");
  26211. });
  26212. proxy_mock.listen();
  26213. target.listen();
  26214. Client cli("public.example", target.port());
  26215. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26216. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26217. cli.set_keep_alive(true);
  26218. auto res1 = cli.Get("/a");
  26219. ASSERT_TRUE(res1);
  26220. EXPECT_EQ("via-proxy", res1->body);
  26221. EXPECT_EQ(1, proxy_hits.load());
  26222. EXPECT_EQ(0, target_hits.load());
  26223. cli.set_no_proxy({"public.example"});
  26224. auto res2 = cli.Get("/b");
  26225. ASSERT_TRUE(res2);
  26226. EXPECT_EQ("direct", res2->body);
  26227. EXPECT_EQ(1, proxy_hits.load());
  26228. EXPECT_EQ(1, target_hits.load());
  26229. }
  26230. // Forward declarations (see the base64_encode note).
  26231. namespace httplib {
  26232. namespace detail {
  26233. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26234. int shutdown_socket(socket_t sock) noexcept;
  26235. } // namespace detail
  26236. } // namespace httplib
  26237. namespace proxy_tunnel_test {
  26238. const char *const kTunnelEstablished =
  26239. "HTTP/1.1 200 Connection established\r\n\r\n";
  26240. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26241. using ConnectReply = std::function<std::string(const std::string &head)>;
  26242. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26243. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26244. class ScopedConnectProxy {
  26245. public:
  26246. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26247. : forward_port_(forward_port), reply_(std::move(reply)) {
  26248. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26249. if (listen_sock_ == INVALID_SOCKET) { return; }
  26250. auto a = loopback(0);
  26251. auto addr = reinterpret_cast<sockaddr *>(&a);
  26252. socklen_t alen = sizeof(a);
  26253. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26254. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26255. ::listen(listen_sock_, 4) != 0) {
  26256. return;
  26257. }
  26258. port_ = ntohs(a.sin_port);
  26259. th_ = std::thread([this] { run(); });
  26260. }
  26261. ~ScopedConnectProxy() {
  26262. if (th_.joinable()) {
  26263. stop_ = true;
  26264. auto wake = connect_to(port_);
  26265. th_.join();
  26266. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26267. }
  26268. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26269. }
  26270. int port() const { return port_; }
  26271. int connect_hits() const { return connect_hits_.load(); }
  26272. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26273. std::string connect_request() const {
  26274. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26275. return connect_request_;
  26276. }
  26277. private:
  26278. static sockaddr_in loopback(int port) {
  26279. sockaddr_in a{};
  26280. a.sin_family = AF_INET;
  26281. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26282. a.sin_port = htons(static_cast<unsigned short>(port));
  26283. return a;
  26284. }
  26285. static socket_t connect_to(int port) {
  26286. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26287. if (sock == INVALID_SOCKET) { return sock; }
  26288. auto a = loopback(port);
  26289. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26290. detail::close_socket(sock);
  26291. return INVALID_SOCKET;
  26292. }
  26293. return sock;
  26294. }
  26295. static bool send_all(socket_t sock, const char *data, size_t size) {
  26296. while (size > 0) {
  26297. auto n = detail::send_socket(sock, data, size, 0);
  26298. if (n <= 0) { return false; }
  26299. data += n;
  26300. size -= static_cast<size_t>(n);
  26301. }
  26302. return true;
  26303. }
  26304. void run() {
  26305. for (;;) {
  26306. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26307. if (stop_) {
  26308. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26309. return;
  26310. }
  26311. if (client == INVALID_SOCKET) { continue; }
  26312. serve(client);
  26313. detail::close_socket(client);
  26314. }
  26315. }
  26316. void serve(socket_t client) {
  26317. std::string head;
  26318. char buf[2048];
  26319. while (head.find("\r\n\r\n") == std::string::npos) {
  26320. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26321. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26322. if (n <= 0) { return; }
  26323. head.append(buf, static_cast<size_t>(n));
  26324. }
  26325. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26326. connect_hits_++;
  26327. {
  26328. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26329. connect_request_ = head;
  26330. }
  26331. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26332. if (!send_all(client, res.data(), res.size()) ||
  26333. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26334. return;
  26335. }
  26336. auto origin = connect_to(forward_port_);
  26337. if (origin == INVALID_SOCKET) { return; }
  26338. // When either side stops, shut both down so the other pump returns too.
  26339. auto pump = [&](socket_t from, socket_t to) {
  26340. char b[8192];
  26341. for (;;) {
  26342. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26343. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26344. }
  26345. detail::shutdown_socket(client);
  26346. detail::shutdown_socket(origin);
  26347. };
  26348. std::thread up([&] { pump(client, origin); });
  26349. pump(origin, client);
  26350. up.join();
  26351. detail::close_socket(origin);
  26352. }
  26353. int forward_port_;
  26354. ConnectReply reply_;
  26355. socket_t listen_sock_ = INVALID_SOCKET;
  26356. int port_ = 0;
  26357. std::thread th_;
  26358. std::atomic<bool> stop_{false};
  26359. std::atomic<int> connect_hits_{0};
  26360. mutable std::mutex connect_request_mutex_;
  26361. std::string connect_request_;
  26362. };
  26363. } // namespace proxy_tunnel_test
  26364. #ifdef CPPHTTPLIB_SSL_ENABLED
  26365. namespace proxy_tunnel_test {
  26366. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26367. class ScopedSSLServer {
  26368. public:
  26369. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26370. port_ = svr_.bind_to_any_port("127.0.0.1");
  26371. }
  26372. ~ScopedSSLServer() {
  26373. svr_.stop();
  26374. if (th_.joinable()) { th_.join(); }
  26375. }
  26376. SSLServer &svr() { return svr_; }
  26377. int port() const { return port_; }
  26378. void listen() {
  26379. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26380. svr_.wait_until_ready();
  26381. }
  26382. private:
  26383. SSLServer svr_;
  26384. std::thread th_;
  26385. int port_ = 0;
  26386. };
  26387. // Sends one request through the CONNECT proxy to the TLS origin with a
  26388. // credential configured for each hop, and checks that each credential reaches
  26389. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26390. // origin's (every header in origin_headers) on the tunnelled request.
  26391. void CredentialsStayWithTheirHop(
  26392. const std::function<void(SSLClient &)> &set_credentials,
  26393. const std::string &scheme,
  26394. const std::vector<std::string> &origin_headers = {"Authorization"},
  26395. bool stream = false) {
  26396. std::atomic<int> origin_hits{0};
  26397. std::atomic<bool> origin_saw_proxy_authz{false};
  26398. std::atomic<bool> origin_saw_headers{false};
  26399. ScopedSSLServer origin;
  26400. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26401. origin_hits++;
  26402. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26403. origin_saw_headers =
  26404. std::all_of(origin_headers.begin(), origin_headers.end(),
  26405. [&](const std::string &h) { return req.has_header(h); });
  26406. res.set_content("ok", "text/plain");
  26407. });
  26408. origin.listen();
  26409. ScopedConnectProxy proxy(origin.port());
  26410. ASSERT_NE(0, proxy.port());
  26411. // Pinned to 127.0.0.1 for the same reason as the test below.
  26412. SSLClient cli("127.0.0.1", origin.port());
  26413. cli.enable_server_certificate_verification(false);
  26414. cli.set_proxy("127.0.0.1", proxy.port());
  26415. set_credentials(cli);
  26416. if (stream) {
  26417. auto handle = cli.open_stream("GET", "/x");
  26418. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26419. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26420. } else {
  26421. auto res = cli.Get("/x");
  26422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26423. EXPECT_EQ(StatusCode::OK_200, res->status);
  26424. }
  26425. EXPECT_EQ(1, origin_hits.load());
  26426. EXPECT_EQ(1, proxy.connect_hits());
  26427. EXPECT_TRUE(origin_saw_headers.load());
  26428. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26429. << "Proxy-Authorization must not be sent inside the tunnel";
  26430. auto connect_req = proxy.connect_request();
  26431. EXPECT_NE(std::string::npos,
  26432. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26433. for (const auto &h : origin_headers) {
  26434. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26435. << h << " must not be sent to the proxy on CONNECT";
  26436. }
  26437. }
  26438. } // namespace proxy_tunnel_test
  26439. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26440. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26441. [](SSLClient &cli) {
  26442. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26443. cli.set_basic_auth("origin-user", "origin-pass");
  26444. },
  26445. "Basic");
  26446. }
  26447. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26448. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26449. [](SSLClient &cli) {
  26450. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26451. cli.set_basic_auth("origin-user", "origin-pass");
  26452. },
  26453. "Basic", {"Authorization"}, true);
  26454. }
  26455. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26456. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26457. [](SSLClient &cli) {
  26458. cli.set_proxy_bearer_token_auth("proxy-token");
  26459. cli.set_bearer_token_auth("origin-token");
  26460. },
  26461. "Bearer");
  26462. }
  26463. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26464. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26465. [](SSLClient &cli) {
  26466. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26467. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26468. {"Cookie", "sid=origin-session"},
  26469. {"X-Api-Key", "origin-key"}});
  26470. },
  26471. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26472. }
  26473. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26474. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26475. // retry; otherwise proxy creds would be sent to the origin.
  26476. std::atomic<int> origin_hits{0};
  26477. std::atomic<bool> origin_saw_proxy_authz{false};
  26478. proxy_tunnel_test::ScopedSSLServer origin;
  26479. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26480. origin_hits++;
  26481. if (req.has_header("Proxy-Authorization")) {
  26482. origin_saw_proxy_authz = true;
  26483. }
  26484. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26485. res.set_header("Proxy-Authenticate",
  26486. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26487. "algorithm=MD5");
  26488. });
  26489. origin.listen();
  26490. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26491. ASSERT_NE(0, proxy.port());
  26492. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26493. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26494. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26495. // and answer with its own status, making this test flaky.
  26496. SSLClient cli("127.0.0.1", origin.port());
  26497. cli.enable_server_certificate_verification(false);
  26498. cli.set_proxy("127.0.0.1", proxy.port());
  26499. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26500. auto res = cli.Get("/x");
  26501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26502. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26503. EXPECT_EQ(1, origin_hits.load());
  26504. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26505. EXPECT_EQ(1, proxy.connect_hits());
  26506. }
  26507. #endif
  26508. namespace proxy_tunnel_test {
  26509. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26510. // anything else gets a 407 with `challenge`.
  26511. ConnectReply require_proxy_auth(const std::string &expected,
  26512. const std::string &challenge) {
  26513. return [=](const std::string &head) -> std::string {
  26514. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26515. std::string::npos) {
  26516. return kTunnelEstablished;
  26517. }
  26518. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26519. "Proxy-Authenticate: " +
  26520. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26521. };
  26522. }
  26523. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26524. // request, then echoes.
  26525. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26526. ws.send(
  26527. "authorization:" + req.get_header_value("Authorization") +
  26528. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26529. std::string msg;
  26530. while (ws.read(msg)) {
  26531. ws.send(msg);
  26532. }
  26533. }
  26534. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26535. class ScopedWebSocketOrigin {
  26536. public:
  26537. ScopedWebSocketOrigin() {
  26538. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26539. server_.listen();
  26540. }
  26541. int port() const { return server_.port(); }
  26542. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26543. std::string url() const {
  26544. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26545. }
  26546. private:
  26547. no_proxy_test::ScopedServer server_;
  26548. };
  26549. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26550. // passed as a constructor header, and checks that each reaches only its hop.
  26551. void WebSocketCredentialsStayWithTheirHop(
  26552. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26553. const std::string &proxy_authz, const std::string &origin_authz) {
  26554. ScopedWebSocketOrigin origin;
  26555. ScopedConnectProxy proxy(
  26556. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26557. ASSERT_NE(0, proxy.port());
  26558. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26559. client.set_proxy("127.0.0.1", proxy.port());
  26560. set_proxy_credentials(client);
  26561. auto res = client.connect();
  26562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26563. std::string msg;
  26564. ASSERT_TRUE(client.read(msg));
  26565. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26566. client.close();
  26567. EXPECT_EQ(1, proxy.connect_hits());
  26568. EXPECT_EQ(std::string::npos,
  26569. proxy.connect_request().find("\r\nAuthorization: "))
  26570. << "origin credentials must not be sent to the proxy";
  26571. }
  26572. } // namespace proxy_tunnel_test
  26573. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26574. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26575. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26576. ASSERT_NE(0, proxy.port());
  26577. ws::WebSocketClient client(origin.url());
  26578. client.set_proxy("127.0.0.1", proxy.port());
  26579. auto res = client.connect();
  26580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26581. std::string msg;
  26582. ASSERT_TRUE(client.read(msg));
  26583. ASSERT_TRUE(client.send("hello"));
  26584. ASSERT_TRUE(client.read(msg));
  26585. EXPECT_EQ("hello", msg);
  26586. client.close();
  26587. EXPECT_EQ(1, proxy.connect_hits());
  26588. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26589. auto connect_req = proxy.connect_request();
  26590. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26591. EXPECT_NE(std::string::npos,
  26592. connect_req.find("\r\nHost: " + target + "\r\n"));
  26593. }
  26594. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26595. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26596. [](ws::WebSocketClient &cli) {
  26597. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26598. },
  26599. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26600. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26601. }
  26602. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26603. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26604. [](ws::WebSocketClient &cli) {
  26605. cli.set_proxy_bearer_token_auth("proxy-token");
  26606. },
  26607. "Bearer proxy-token", "Bearer origin-token");
  26608. }
  26609. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26610. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26611. proxy_tunnel_test::ScopedConnectProxy proxy(
  26612. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26613. "Basic " + detail::base64_encode("proxy-user:"),
  26614. "Basic realm=\"proxy\""));
  26615. ASSERT_NE(0, proxy.port());
  26616. ws::WebSocketClient client(origin.url());
  26617. client.set_proxy("127.0.0.1", proxy.port());
  26618. client.set_proxy_basic_auth("proxy-user", "");
  26619. auto res = client.connect();
  26620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26621. client.close();
  26622. EXPECT_EQ(1, proxy.connect_hits());
  26623. }
  26624. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26625. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26626. proxy_tunnel_test::ScopedConnectProxy proxy(
  26627. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26628. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26629. ASSERT_NE(0, proxy.port());
  26630. ws::WebSocketClient client(origin.url());
  26631. client.set_proxy("127.0.0.1", proxy.port());
  26632. auto res = client.connect();
  26633. EXPECT_FALSE(res);
  26634. EXPECT_EQ(Error::ProxyConnection, res.error());
  26635. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26636. EXPECT_EQ("Basic realm=\"proxy\"",
  26637. res.get_header_value("Proxy-Authenticate"));
  26638. EXPECT_FALSE(client.is_open());
  26639. }
  26640. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26641. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26642. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26643. ASSERT_NE(0, proxy.port());
  26644. ws::WebSocketClient client(origin.url());
  26645. client.set_proxy("127.0.0.1", proxy.port());
  26646. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26647. client.set_no_proxy({"127.0.0.1"});
  26648. auto res = client.connect();
  26649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26650. std::string msg;
  26651. ASSERT_TRUE(client.read(msg));
  26652. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26653. << "proxy credentials must not reach a bypassed origin";
  26654. client.close();
  26655. EXPECT_EQ(0, proxy.connect_hits());
  26656. }
  26657. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26658. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26659. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26660. ASSERT_NE(0, proxy.port());
  26661. ws::WebSocketClient client(origin.url());
  26662. client.set_proxy("127.0.0.1", proxy.port());
  26663. ASSERT_TRUE(client.connect());
  26664. ASSERT_TRUE(client.connect());
  26665. client.close();
  26666. EXPECT_EQ(2, proxy.connect_hits());
  26667. }
  26668. #ifdef CPPHTTPLIB_SSL_ENABLED
  26669. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26670. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26671. proxy_tunnel_test::ScopedConnectProxy proxy(
  26672. origin.port(), [](const std::string &head) -> std::string {
  26673. if (head.find(
  26674. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26675. std::string::npos) {
  26676. return proxy_tunnel_test::kTunnelEstablished;
  26677. }
  26678. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26679. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26680. "nonce=\"abc\", algorithm=MD5\r\n"
  26681. "Content-Length: 0\r\n\r\n";
  26682. });
  26683. ASSERT_NE(0, proxy.port());
  26684. ws::WebSocketClient client(origin.url());
  26685. client.set_proxy("127.0.0.1", proxy.port());
  26686. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26687. auto res = client.connect();
  26688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26689. std::string msg;
  26690. ASSERT_TRUE(client.read(msg));
  26691. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26692. client.close();
  26693. EXPECT_EQ(2, proxy.connect_hits());
  26694. }
  26695. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26696. proxy_tunnel_test::ScopedSSLServer origin;
  26697. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26698. origin.listen();
  26699. proxy_tunnel_test::ScopedConnectProxy proxy(
  26700. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26701. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26702. ASSERT_NE(0, proxy.port());
  26703. ws::WebSocketClient client(
  26704. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26705. client.enable_server_certificate_verification(false);
  26706. client.set_proxy("127.0.0.1", proxy.port());
  26707. client.set_proxy_bearer_token_auth("proxy-token");
  26708. auto res = client.connect();
  26709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26710. std::string msg;
  26711. ASSERT_TRUE(client.read(msg));
  26712. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26713. << "Proxy-Authorization must not be sent inside the tunnel";
  26714. client.close();
  26715. EXPECT_EQ(1, proxy.connect_hits());
  26716. }
  26717. #endif