test.cc 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  253. // Another socket in the working directory, which a Location can name as
  254. // its host
  255. const auto other_path = "other-" + pathname_.substr(2);
  256. httplib::Server svr;
  257. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  258. // An absolute Location naming the Host this client sends
  259. res.set_redirect("http://localhost" + pattern_);
  260. });
  261. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  262. res.set_redirect("http://" + other_path + pattern_);
  263. });
  264. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  265. res.set_redirect("http://mapped.test" + pattern_);
  266. });
  267. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  268. res.set_header("X-Auth", req.get_header_value("Authorization"));
  269. res.set_content(content_, "text/plain");
  270. });
  271. httplib::Server other;
  272. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  273. res.set_content("other", "text/plain");
  274. });
  275. std::thread t{[&] {
  276. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  277. }};
  278. std::thread t2{[&] {
  279. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  280. }};
  281. auto se = detail::scope_exit([&] {
  282. svr.stop();
  283. other.stop();
  284. t.join();
  285. t2.join();
  286. std::remove(other_path.c_str());
  287. });
  288. svr.wait_until_ready();
  289. other.wait_until_ready();
  290. httplib::Client cli{pathname_};
  291. cli.set_address_family(AF_UNIX);
  292. cli.set_follow_location(true);
  293. cli.set_bearer_token_auth("token");
  294. // Another host: the same socket, without the credentials
  295. auto res = cli.Get("/cross");
  296. ASSERT_TRUE(res) << "error: " << res.error();
  297. EXPECT_EQ(StatusCode::OK_200, res->status);
  298. EXPECT_EQ(content_, res->body);
  299. EXPECT_EQ("", res->get_header_value("X-Auth"));
  300. // localhost is this client's own host
  301. res = cli.Get("/redirect");
  302. ASSERT_TRUE(res) << "error: " << res.error();
  303. EXPECT_EQ(StatusCode::OK_200, res->status);
  304. EXPECT_EQ(content_, res->body);
  305. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  306. // A host the caller mapped to a socket goes there
  307. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  308. res = cli.Get("/mapped");
  309. ASSERT_TRUE(res) << "error: " << res.error();
  310. EXPECT_EQ(StatusCode::OK_200, res->status);
  311. EXPECT_EQ("other", res->body);
  312. }
  313. #ifndef _WIN32
  314. TEST(SocketStream, wait_writable_UNIX) {
  315. int fds[2];
  316. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  317. const auto asSocketStream = [&](socket_t fd,
  318. std::function<bool(Stream &)> func) {
  319. return detail::process_client_socket(
  320. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  321. };
  322. asSocketStream(fds[0], [&](Stream &s0) {
  323. EXPECT_EQ(s0.socket(), fds[0]);
  324. EXPECT_TRUE(s0.wait_writable());
  325. EXPECT_TRUE(s0.is_peer_alive());
  326. EXPECT_EQ(0, close(fds[1]));
  327. EXPECT_FALSE(s0.is_peer_alive());
  328. return true;
  329. });
  330. EXPECT_EQ(0, close(fds[0]));
  331. }
  332. TEST(SocketStream, wait_writable_INET) {
  333. sockaddr_in addr;
  334. memset(&addr, 0, sizeof(addr));
  335. addr.sin_family = AF_INET;
  336. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  337. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  338. int disconnected_svr_sock = -1;
  339. std::thread svr{[&] {
  340. const int s = socket(AF_INET, SOCK_STREAM, 0);
  341. ASSERT_LE(0, s);
  342. // PORT + 1 is shared with the SSL redirect tests and with
  343. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  344. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  345. // because that happens on a worker thread the ASSERT does not stop the
  346. // test: it runs on and fails at the disconnected_svr_sock check instead.
  347. default_socket_options(s);
  348. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  349. ASSERT_EQ(0, listen(s, 1));
  350. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  351. ASSERT_EQ(0, close(s));
  352. }};
  353. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  354. std::thread cli{[&] {
  355. const int s = socket(AF_INET, SOCK_STREAM, 0);
  356. ASSERT_LE(0, s);
  357. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  358. ASSERT_EQ(0, close(s));
  359. }};
  360. cli.join();
  361. svr.join();
  362. ASSERT_NE(disconnected_svr_sock, -1);
  363. const auto asSocketStream = [&](socket_t fd,
  364. std::function<bool(Stream &)> func) {
  365. return detail::process_client_socket(
  366. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  367. };
  368. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  369. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  370. // wait_writable() returns true because select_write() only checks if the
  371. // send buffer has space. Peer disconnection is detected later by send().
  372. EXPECT_TRUE(ss.wait_writable());
  373. return true;
  374. });
  375. ASSERT_EQ(0, close(disconnected_svr_sock));
  376. }
  377. #endif // #ifndef _WIN32
  378. TEST(SetSocketOptTest, TcpNoDelay) {
  379. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  380. ASSERT_NE(sock, INVALID_SOCKET);
  381. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  382. int val = 0;
  383. socklen_t len = sizeof(val);
  384. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  385. reinterpret_cast<char *>(&val), &len));
  386. EXPECT_NE(val, 0);
  387. detail::close_socket(sock);
  388. }
  389. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  390. // accept() reports failures through WSAGetLastError() on Windows and through
  391. // errno everywhere else. Asking the wrong one is what made the accept loop
  392. // treat every recoverable failure as fatal on Windows.
  393. struct Classification {
  394. bool resource;
  395. bool transient;
  396. };
  397. auto classify = [](int err) {
  398. #ifdef _WIN32
  399. WSASetLastError(err);
  400. #else
  401. errno = err;
  402. #endif
  403. // Read both before asserting: an assertion may clobber the error slot.
  404. Classification c;
  405. c.resource = detail::is_accept_resource_error();
  406. c.transient = detail::is_accept_transient_error();
  407. return c;
  408. };
  409. #ifdef _WIN32
  410. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  411. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  412. WSAECONNRESET, WSAECONNABORTED};
  413. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  414. #else
  415. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  416. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  417. ECONNABORTED};
  418. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  419. #endif
  420. for (auto err : resource_errors) {
  421. const auto c = classify(err);
  422. EXPECT_TRUE(c.resource) << "error " << err;
  423. EXPECT_FALSE(c.transient) << "error " << err;
  424. }
  425. for (auto err : transient_errors) {
  426. const auto c = classify(err);
  427. EXPECT_TRUE(c.transient) << "error " << err;
  428. EXPECT_FALSE(c.resource) << "error " << err;
  429. }
  430. for (auto err : fatal_errors) {
  431. const auto c = classify(err);
  432. EXPECT_FALSE(c.resource) << "error " << err;
  433. EXPECT_FALSE(c.transient) << "error " << err;
  434. }
  435. #ifdef _WIN32
  436. WSASetLastError(0);
  437. #else
  438. errno = 0;
  439. #endif
  440. }
  441. TEST(ClientTest, MoveConstructible) {
  442. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  443. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  444. }
  445. TEST(ClientTest, MoveAssignable) {
  446. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  447. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  448. }
  449. #ifdef _WIN32
  450. TEST(StartupTest, WSAStartup) {
  451. WSADATA wsaData;
  452. int ret = WSAStartup(0x0002, &wsaData);
  453. ASSERT_EQ(0, ret);
  454. }
  455. #endif
  456. TEST(DecodePathTest, PercentCharacter) {
  457. EXPECT_EQ(
  458. decode_path_component(
  459. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  460. U8("descrip=Gastos áéíóúñÑ 6"));
  461. }
  462. TEST(DecodePathTest, PercentCharacterNUL) {
  463. string expected;
  464. expected.push_back('x');
  465. expected.push_back('\0');
  466. expected.push_back('x');
  467. EXPECT_EQ(decode_path_component("x%00x"), expected);
  468. }
  469. TEST(DecodePathTest, UnicodeEncoding) {
  470. // %u0041 = 'A' (1-byte UTF-8)
  471. EXPECT_EQ("A", decode_path_component("%u0041"));
  472. // %u00E9 = 'é' (2-byte UTF-8)
  473. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  474. // %u3042 = 'あ' (3-byte UTF-8)
  475. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  476. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  477. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  478. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  479. // neighbours)
  480. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  481. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  482. }
  483. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  484. // A sign or whitespace inside the two-character escape window must not be
  485. // accepted as a valid percent-encoding; the sequence is passed through
  486. // literally, matching decode_uri_component / decode_path_component.
  487. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  488. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  489. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  490. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  491. // Well-formed escapes still decode.
  492. EXPECT_EQ("-", decode_query_component("%2D", false));
  493. EXPECT_EQ("A", decode_query_component("%41", false));
  494. }
  495. TEST(SanitizeFilenameTest, VariousPatterns) {
  496. // Path traversal
  497. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  498. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  499. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  500. // Normal and edge cases
  501. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  502. EXPECT_EQ("filename.txt",
  503. httplib::sanitize_filename("/path/to/filename.txt"));
  504. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  505. EXPECT_EQ("", httplib::sanitize_filename(".."));
  506. EXPECT_EQ("", httplib::sanitize_filename(""));
  507. // Null bytes stripped
  508. EXPECT_EQ("safe.txt",
  509. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  510. // Whitespace-only rejected
  511. EXPECT_EQ("", httplib::sanitize_filename(" "));
  512. }
  513. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  514. // before it is dropped; anywhere else it is an ordinary file name character.
  515. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  516. #ifdef _WIN32
  517. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  518. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  519. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  520. #else
  521. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  522. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  523. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  524. #endif
  525. }
  526. // Forward declaration (see the base64_encode note below): split builds move the
  527. // definition into httplib.cc, so re-declaring it here lets the test link.
  528. namespace httplib {
  529. namespace detail {
  530. bool is_chunked_transfer_encoding(const Headers &headers);
  531. } // namespace detail
  532. } // namespace httplib
  533. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  534. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  535. auto make = [](std::initializer_list<const char *> lines) {
  536. Headers h;
  537. for (auto te : lines) {
  538. if (te) { h.emplace("Transfer-Encoding", te); }
  539. }
  540. return h;
  541. };
  542. // Sole coding, matched case-insensitively.
  543. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  544. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  545. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  546. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  547. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  548. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  549. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  550. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  551. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  552. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  553. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  554. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  555. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  556. // were received, into one list. Headers preserves that order, so the answer
  557. // is decided by the last coding of the last line and the order the lines
  558. // arrived in is significant.
  559. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  560. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  561. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  562. // The split can fall anywhere in the list.
  563. EXPECT_TRUE(
  564. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  565. EXPECT_FALSE(
  566. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  567. // A trailing line naming no coding leaves the list ending in nothing, so it
  568. // must not inherit the chunked from the line before it.
  569. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  570. }
  571. // Forward declarations (see the base64_encode note below).
  572. namespace httplib {
  573. namespace detail {
  574. bool parse_status_line(const char *line, std::string &version, int &status,
  575. std::string &reason);
  576. std::string file_extension(const std::string &path);
  577. std::string
  578. find_content_type(const std::string &path,
  579. const std::map<std::string, std::string> &user_data,
  580. const std::string &default_content_type);
  581. bool can_compress_content_type(const std::string &content_type);
  582. bool is_prohibited_header_name(const std::string &name);
  583. bool is_valid_path(const std::string &path);
  584. #ifdef CPPHTTPLIB_SSL_ENABLED
  585. bool match_hostname(const std::string &pattern, const std::string &hostname);
  586. #endif
  587. } // namespace detail
  588. } // namespace httplib
  589. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  590. struct {
  591. const char *line;
  592. const char *version;
  593. int status;
  594. const char *reason;
  595. } cases[] = {
  596. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  597. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  598. // The reason phrase may be empty, or left out along with its space.
  599. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  600. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  601. };
  602. for (const auto &c : cases) {
  603. std::string version;
  604. int status = 0;
  605. std::string reason = "unset";
  606. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  607. << c.line;
  608. EXPECT_EQ(c.version, version);
  609. EXPECT_EQ(c.status, status);
  610. EXPECT_EQ(c.reason, reason);
  611. }
  612. }
  613. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  614. const char *lines[] = {
  615. "HTTP/2 200 OK\r\n",
  616. "HTTP/1.2 200 OK\r\n",
  617. "HTTP/1.1 20 OK\r\n",
  618. "HTTP/1.1 2000 OK\r\n",
  619. "HTTP/1.1 2x0 OK\r\n",
  620. "HTTP/1.1 200 OK\r\n",
  621. "HTTP/1.1 200OK\r\n",
  622. "HTTP/1.1 200 O\rK\r\n",
  623. "HTTP/1.1 200 OK",
  624. "HTTP/1.1 200 OK\r\nX",
  625. "",
  626. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  627. "HTTP/1.1 200 OK\n",
  628. #endif
  629. };
  630. for (auto line : lines) {
  631. std::string version;
  632. int status = 0;
  633. std::string reason;
  634. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  635. << line;
  636. }
  637. }
  638. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  639. // Long enough to overflow the stack when matched with std::regex.
  640. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  641. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  642. std::string version;
  643. int status = 0;
  644. std::string reason;
  645. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  646. EXPECT_EQ(200, status);
  647. EXPECT_EQ(long_reason, reason);
  648. }
  649. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  650. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  651. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  652. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  653. EXPECT_EQ("", detail::file_extension("noext"));
  654. EXPECT_EQ("", detail::file_extension("a."));
  655. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  656. EXPECT_EQ("", detail::file_extension("a.b-c"));
  657. // Long enough to overflow the stack when matched with std::regex.
  658. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  659. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  660. }
  661. #ifdef CPPHTTPLIB_SSL_ENABLED
  662. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  663. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  664. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  665. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  666. // A wildcard needs two labels after it, in the leftmost label only
  667. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  668. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  669. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  670. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  671. EXPECT_FALSE(
  672. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  673. // No name may have an empty label
  674. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  675. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  676. }
  677. #endif
  678. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  679. detail::case_ignore::hash hash;
  680. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  681. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  682. // Long enough to overflow the stack if hashed one call per character.
  683. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  684. }
  685. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  686. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  687. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  688. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  689. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  690. // Same 26-bit hash as html, svg and js.
  691. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  692. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  693. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  694. }
  695. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  696. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  697. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  698. }
  699. }
  700. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  701. // name anywhere else.
  702. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  703. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  704. #ifdef _WIN32
  705. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  706. #else
  707. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  708. #endif
  709. }
  710. }
  711. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  712. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  713. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  714. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  715. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  716. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  717. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  718. // Same 26-bit hash as application/json.
  719. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  720. }
  721. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  722. Request req;
  723. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  724. EXPECT_TRUE(req.is_multipart_form_data());
  725. std::string boundary;
  726. EXPECT_TRUE(detail::parse_multipart_boundary(
  727. req.get_header_value("Content-Type"), boundary));
  728. EXPECT_EQ("x", boundary);
  729. }
  730. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  731. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  732. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  733. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  734. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  735. // Same 26-bit hash as REMOTE_ADDR.
  736. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  737. }
  738. // Forward declaration: in split builds split.py strips `inline` and moves the
  739. // definition into httplib.cc, so detail::base64_encode is not visible from the
  740. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  741. // in both header-only and split builds.
  742. namespace httplib {
  743. namespace detail {
  744. std::string base64_encode(const std::string &in);
  745. } // namespace detail
  746. } // namespace httplib
  747. TEST(Base64EncodeTest, KnownAnswers) {
  748. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  749. // where the accumulator's top bit is already set before the next shift.
  750. EXPECT_EQ("", detail::base64_encode(""));
  751. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  752. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  753. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  754. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  755. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  756. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  757. // High bytes keep the top bit set across several rounds.
  758. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  759. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  760. }
  761. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  762. string unescapedCharacters = "-_.!~*'()";
  763. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  764. }
  765. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  766. string reservedCharacters = ";,/?:@&=+$";
  767. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  768. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  769. }
  770. TEST(ClientQueryOrder, PreserveOrder) {
  771. // This test reproduces Issue #2259: client may reorder query parameters
  772. // when sending a GET request. The expected behavior is that the client
  773. // preserves the original query string order when the caller supplied it
  774. // as part of the path.
  775. Server svr;
  776. svr.Get("/", [&](const Request &req, Response &res) {
  777. // Echo back the raw target so the test can assert ordering
  778. res.set_content(req.target, "text/plain");
  779. });
  780. std::thread t{[&] { svr.listen(HOST, PORT); }};
  781. auto se = detail::scope_exit([&] {
  782. svr.stop();
  783. t.join();
  784. ASSERT_FALSE(svr.is_running());
  785. });
  786. svr.wait_until_ready();
  787. Client cli(HOST, PORT);
  788. ASSERT_TRUE(cli.is_valid());
  789. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  790. auto res = cli.Get(original);
  791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  792. // Expect the echoed target to exactly match the original path (order
  793. // preserved)
  794. EXPECT_EQ(res->body, original);
  795. }
  796. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  797. string chineseCharacters = U8("中国語");
  798. string russianCharacters = U8("дом");
  799. string brazilianCharacters = U8("óculos");
  800. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  801. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  802. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  803. "%D0%B4%D0%BE%D0%BC");
  804. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  805. }
  806. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  807. string unescapedCharacters = "-_.!~*'()";
  808. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  809. }
  810. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  811. string reservedCharacters = ";,/?:@&=+$";
  812. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  813. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  814. }
  815. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  816. string chineseCharacters = U8("中国語");
  817. string russianCharacters = U8("дом");
  818. string brazilianCharacters = U8("óculos");
  819. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  820. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  821. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  822. "%D0%B4%D0%BE%D0%BC");
  823. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  824. }
  825. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  826. // Issue #2082 use case: encoding path component with ampersand
  827. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  828. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  829. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  830. }
  831. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  832. string unescapedCharacters = "-_.!~*'()";
  833. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  834. }
  835. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  836. string reservedCharacters = ";,/?:@&=+$#";
  837. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  838. }
  839. TEST(EncodeUriTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  846. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  847. }
  848. TEST(EncodeUriTest, TestCompleteUri) {
  849. string uri =
  850. "https://example.com/path/to/resource?query=value&param=test#fragment";
  851. EXPECT_EQ(
  852. httplib::encode_uri(uri),
  853. "https://example.com/path/to/resource?query=value&param=test#fragment");
  854. }
  855. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  856. string uri =
  857. "https://example.com/path with spaces/file name.html?q=hello world";
  858. EXPECT_EQ(httplib::encode_uri(uri),
  859. "https://example.com/path%20with%20spaces/"
  860. "file%20name.html?q=hello%20world");
  861. }
  862. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  863. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  864. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  865. }
  866. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  867. string unescapedCharacters = "-_.!~*'()";
  868. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  869. }
  870. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  871. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  872. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  873. string encodedBrazilian = "%C3%B3culos";
  874. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  875. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  876. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  877. }
  878. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  879. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  880. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  881. "Piri Tommy Villiers - on & on");
  882. }
  883. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  884. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  885. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  886. }
  887. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  888. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  889. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  890. }
  891. TEST(DecodeUriTest, TestUTF8Characters) {
  892. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  893. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  894. string encodedBrazilian = "%C3%B3culos";
  895. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  896. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  897. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  898. }
  899. TEST(DecodeUriTest, TestCompleteUri) {
  900. string encodedUri = "https://example.com/path%20with%20spaces/"
  901. "file%20name.html?q=hello%20world";
  902. EXPECT_EQ(
  903. httplib::decode_uri(encodedUri),
  904. "https://example.com/path with spaces/file name.html?q=hello world");
  905. }
  906. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  907. string original =
  908. "https://example.com/path with spaces/file name.html?q=hello world";
  909. string encoded = httplib::encode_uri(original);
  910. string decoded = httplib::decode_uri(encoded);
  911. EXPECT_EQ(decoded, original);
  912. }
  913. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  914. // decode_uri is the inverse of encode_uri: an escaped reserved character
  915. // stays encoded so it is not promoted into a real delimiter, while
  916. // non-reserved escapes still decode (like JS decodeURI).
  917. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  918. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  919. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  920. "%3F%3A%40%26%3D%2B%24%2C%3B");
  921. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  922. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  923. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  924. "http://example.com/a%2Fb");
  925. // decode_uri_component still decodes the reserved character.
  926. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  927. }
  928. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  929. string original = "Piri Tommy Villiers - on & on";
  930. string encoded = httplib::encode_uri_component(original);
  931. string decoded = httplib::decode_uri_component(encoded);
  932. EXPECT_EQ(decoded, original);
  933. }
  934. TEST(TrimTests, TrimStringTests) {
  935. EXPECT_EQ("abc", detail::trim_copy("abc"));
  936. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  937. EXPECT_TRUE(detail::trim_copy("").empty());
  938. }
  939. TEST(AsciiTest, LocaleIndependentClassification) {
  940. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  941. // which consult the global C locale: std::isalnum(0xC5) can return true
  942. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  943. // helpers must classify every byte by the ASCII grammar alone.
  944. for (int i = 0; i < 256; i++) {
  945. auto c = static_cast<char>(i);
  946. auto is_digit = i >= '0' && i <= '9';
  947. auto is_upper = i >= 'A' && i <= 'Z';
  948. auto is_lower = i >= 'a' && i <= 'z';
  949. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  950. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  951. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  952. << "byte " << i;
  953. }
  954. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  955. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  956. // Non-ASCII bytes must be percent-encoded, never passed through as
  957. // alphanumeric.
  958. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  959. }
  960. TEST(FromCharsTest, Double) {
  961. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  962. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  963. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  964. auto parse = [](const std::string &s, double &v) {
  965. return detail::from_chars(s.data(), s.data() + s.size(), v);
  966. };
  967. double v = -1.0;
  968. // Representative quality values.
  969. EXPECT_EQ(parse("0", v).ec, std::errc{});
  970. EXPECT_DOUBLE_EQ(v, 0.0);
  971. EXPECT_EQ(parse("1", v).ec, std::errc{});
  972. EXPECT_DOUBLE_EQ(v, 1.0);
  973. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  974. EXPECT_DOUBLE_EQ(v, 0.8);
  975. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  976. EXPECT_DOUBLE_EQ(v, 0.001);
  977. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  978. EXPECT_DOUBLE_EQ(v, 1.0);
  979. // A missing integer or fractional part is tolerated.
  980. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  981. EXPECT_DOUBLE_EQ(v, 0.5);
  982. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  983. EXPECT_DOUBLE_EQ(v, 5.0);
  984. // Values outside [0, 1] still parse; the caller range-checks them.
  985. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  986. EXPECT_DOUBLE_EQ(v, 123.456);
  987. // Stops at the first byte that is not part of the number and reports where.
  988. std::string trailing = "0.9, text/html";
  989. auto r = parse(trailing, v);
  990. EXPECT_EQ(r.ec, std::errc{});
  991. EXPECT_DOUBLE_EQ(v, 0.9);
  992. EXPECT_EQ(*r.ptr, ',');
  993. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  994. // outright, and an 'e'/'E' simply ends the number.
  995. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  996. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  997. std::string exp_input = "1.5e3";
  998. r = parse(exp_input, v);
  999. EXPECT_EQ(r.ec, std::errc{});
  1000. EXPECT_DOUBLE_EQ(v, 1.5);
  1001. EXPECT_EQ(*r.ptr, 'e');
  1002. // Invalid inputs.
  1003. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1004. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1005. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1006. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1007. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1008. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1009. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1010. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1011. std::errc{});
  1012. EXPECT_DOUBLE_EQ(v, 0.0);
  1013. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1014. std::errc{});
  1015. EXPECT_GE(v, 0.0);
  1016. EXPECT_LE(v, 1.0);
  1017. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1018. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1019. }
  1020. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1021. // Simple case without quality values
  1022. std::vector<std::string> result1;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "text/html,application/json,text/plain", result1));
  1025. EXPECT_EQ(result1.size(), 3U);
  1026. EXPECT_EQ(result1[0], "text/html");
  1027. EXPECT_EQ(result1[1], "application/json");
  1028. EXPECT_EQ(result1[2], "text/plain");
  1029. // With quality values
  1030. std::vector<std::string> result2;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1033. EXPECT_EQ(result2.size(), 3U);
  1034. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1035. EXPECT_EQ(result2[1], "text/html");
  1036. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1037. }
  1038. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1039. // Mixed with and without quality values
  1040. std::vector<std::string> result;
  1041. EXPECT_TRUE(detail::parse_accept_header(
  1042. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1043. EXPECT_EQ(result.size(), 3U);
  1044. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1045. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1046. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1047. }
  1048. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1049. // Empty header
  1050. std::vector<std::string> empty_result;
  1051. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1052. EXPECT_TRUE(empty_result.empty());
  1053. // Single type
  1054. std::vector<std::string> single_result;
  1055. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1056. EXPECT_EQ(single_result.size(), 1U);
  1057. EXPECT_EQ(single_result[0], "application/json");
  1058. // Wildcard types
  1059. std::vector<std::string> wildcard_result;
  1060. EXPECT_TRUE(detail::parse_accept_header(
  1061. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1062. EXPECT_EQ(wildcard_result.size(), 3U);
  1063. EXPECT_EQ(wildcard_result[0], "application/json");
  1064. EXPECT_EQ(wildcard_result[1], "text/*");
  1065. EXPECT_EQ(wildcard_result[2], "*/*");
  1066. }
  1067. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1068. // Common browser Accept header
  1069. std::vector<std::string> browser_result;
  1070. EXPECT_TRUE(
  1071. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1072. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1073. browser_result));
  1074. EXPECT_EQ(browser_result.size(), 6U);
  1075. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1076. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1077. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1078. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1079. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1080. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1081. // API client header
  1082. std::vector<std::string> api_result;
  1083. EXPECT_TRUE(detail::parse_accept_header(
  1084. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1085. api_result));
  1086. EXPECT_EQ(api_result.size(), 3U);
  1087. EXPECT_EQ(api_result[0], "application/json");
  1088. EXPECT_EQ(api_result[1], "application/xml");
  1089. EXPECT_EQ(api_result[2], "text/plain");
  1090. }
  1091. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1092. // Quality value with 3 decimal places
  1093. std::vector<std::string> decimal_result;
  1094. EXPECT_TRUE(detail::parse_accept_header(
  1095. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1096. EXPECT_EQ(decimal_result.size(), 2U);
  1097. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1098. EXPECT_EQ(decimal_result[1], "text/html");
  1099. // Zero quality (should still be included but with lowest priority)
  1100. std::vector<std::string> zero_q_result;
  1101. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1102. zero_q_result));
  1103. EXPECT_EQ(zero_q_result.size(), 2U);
  1104. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1105. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1106. // No spaces around commas
  1107. std::vector<std::string> no_space_result;
  1108. EXPECT_TRUE(detail::parse_accept_header(
  1109. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1110. no_space_result));
  1111. EXPECT_EQ(no_space_result.size(), 3U);
  1112. EXPECT_EQ(no_space_result[0], "text/html");
  1113. EXPECT_EQ(no_space_result[1], "application/json");
  1114. EXPECT_EQ(no_space_result[2], "text/plain");
  1115. }
  1116. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1117. // Quality values always use '.' as the decimal separator, so parsing must
  1118. // not depend on the process locale. An embedding application may have
  1119. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1120. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1121. std::string saved = cur ? cur : "C";
  1122. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1123. "fr_FR.UTF-8"};
  1124. bool switched = false;
  1125. for (const auto loc : comma_locales) {
  1126. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1127. std::localeconv()->decimal_point[0] == ',') {
  1128. switched = true;
  1129. break;
  1130. }
  1131. }
  1132. if (!switched) {
  1133. std::setlocale(LC_NUMERIC, saved.c_str());
  1134. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1135. }
  1136. // The higher-weighted type appears later in the list, so a correct parse
  1137. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1138. // sensitive parse reads both weights as 0 and leaves the original order.
  1139. std::vector<std::string> result;
  1140. EXPECT_TRUE(detail::parse_accept_header(
  1141. "application/json;q=0.1,text/html;q=0.9", result));
  1142. ASSERT_EQ(result.size(), 2U);
  1143. EXPECT_EQ(result[0], "text/html");
  1144. EXPECT_EQ(result[1], "application/json");
  1145. std::setlocale(LC_NUMERIC, saved.c_str());
  1146. }
  1147. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1148. std::vector<std::string> result;
  1149. // Invalid quality value (> 1.0)
  1150. EXPECT_FALSE(
  1151. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1152. // Invalid quality value (< 0.0)
  1153. EXPECT_FALSE(
  1154. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1155. // Invalid quality value (not a number)
  1156. EXPECT_FALSE(detail::parse_accept_header(
  1157. "text/html;q=invalid,application/json", result));
  1158. // A valid numeric prefix does not make the entire quality value valid.
  1159. EXPECT_FALSE(detail::parse_accept_header(
  1160. "text/html;q=0.5junk,application/json", result));
  1161. // Empty quality value
  1162. EXPECT_FALSE(
  1163. detail::parse_accept_header("text/html;q=,application/json", result));
  1164. // Invalid media type format (no slash and not wildcard)
  1165. EXPECT_FALSE(
  1166. detail::parse_accept_header("invalidtype,application/json", result));
  1167. // Valid cases should still work
  1168. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1169. EXPECT_EQ(result.size(), 1U);
  1170. EXPECT_EQ(result[0], "*/*");
  1171. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1172. EXPECT_EQ(result.size(), 1U);
  1173. EXPECT_EQ(result[0], "*");
  1174. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1175. EXPECT_EQ(result.size(), 1U);
  1176. EXPECT_EQ(result[0], "text/*");
  1177. }
  1178. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1179. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1180. // and must not be answered with 400 Bad Request.
  1181. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1182. struct {
  1183. const char *value;
  1184. std::vector<std::string> expected;
  1185. } cases[] = {
  1186. {",application/json", {"application/json"}},
  1187. {"text/html,", {"text/html"}},
  1188. {"text/html,,*/*", {"text/html", "*/*"}},
  1189. // An empty element may be spelled with whitespace in it
  1190. {"text/html, , application/json", {"text/html", "application/json"}},
  1191. // Nothing but empty elements is an empty list, which means the same
  1192. // thing as no Accept header at all
  1193. {",,,", {}},
  1194. // Quality values still apply across ignored empty elements
  1195. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1196. };
  1197. for (const auto &c : cases) {
  1198. std::vector<std::string> result;
  1199. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1200. << "value: " << c.value;
  1201. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1202. }
  1203. // An invalid entry is still rejected when empty elements surround it
  1204. std::vector<std::string> result;
  1205. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1206. }
  1207. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1208. // or ';' inside one does not end the list element or the parameter. Section
  1209. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1210. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1211. struct {
  1212. const char *value;
  1213. std::vector<std::string> expected;
  1214. } cases[] = {
  1215. {"text/html;profile=\"a,b\",application/json",
  1216. {"text/html", "application/json"}},
  1217. // A "q=" inside a quoted value is not the weight
  1218. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1219. {"text/html", "application/json"}},
  1220. // The weight after a quoted value still applies
  1221. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1222. {"application/json", "text/html"}},
  1223. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1224. {"application/json", "text/html"}},
  1225. {"text/html;profile=\"a\\\"b\",application/json",
  1226. {"text/html", "application/json"}},
  1227. // An escaped backslash does not escape the '"' after it
  1228. {"text/html;profile=\"a\\\\\",application/json",
  1229. {"text/html", "application/json"}},
  1230. };
  1231. for (const auto &c : cases) {
  1232. std::vector<std::string> result;
  1233. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1234. << "value: " << c.value;
  1235. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1236. }
  1237. }
  1238. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1239. Server svr;
  1240. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1241. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1242. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1243. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1244. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1245. res.set_content("ok", "text/plain");
  1246. });
  1247. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1248. EXPECT_TRUE(false);
  1249. res.set_content("bad request", "text/plain");
  1250. });
  1251. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1252. auto se = detail::scope_exit([&] {
  1253. svr.stop();
  1254. listen_thread.join();
  1255. ASSERT_FALSE(svr.is_running());
  1256. });
  1257. svr.wait_until_ready();
  1258. Client cli("localhost", PORT);
  1259. {
  1260. auto res = cli.Get(
  1261. "/accept_ok",
  1262. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1264. EXPECT_EQ(StatusCode::OK_200, res->status);
  1265. }
  1266. {
  1267. auto res = cli.Get("/accept_bad_request",
  1268. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1271. }
  1272. }
  1273. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1274. Server svr;
  1275. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1276. res.set_content("ok", "text/plain");
  1277. });
  1278. std::atomic<int> start_count{0};
  1279. std::atomic<bool> running_when_called{false};
  1280. svr.set_start_handler([&]() {
  1281. running_when_called = svr.is_running();
  1282. start_count++;
  1283. });
  1284. auto port = svr.bind_to_any_port(HOST);
  1285. std::thread t([&]() { svr.listen_after_bind(); });
  1286. auto se = detail::scope_exit([&] {
  1287. svr.stop();
  1288. t.join();
  1289. ASSERT_FALSE(svr.is_running());
  1290. });
  1291. svr.wait_until_ready();
  1292. // A successful request proves the accept loop is running, which the start
  1293. // handler precedes; so by now the handler must have run exactly once.
  1294. Client cli(HOST, port);
  1295. cli.set_connection_timeout(std::chrono::seconds(5));
  1296. auto res = cli.Get("/");
  1297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1298. EXPECT_EQ(StatusCode::OK_200, res->status);
  1299. EXPECT_EQ(1, start_count.load());
  1300. EXPECT_TRUE(running_when_called.load());
  1301. }
  1302. TEST(DivideTest, DivideStringTests) {
  1303. auto divide = [](const std::string &str, char d) {
  1304. std::string lhs;
  1305. std::string rhs;
  1306. detail::divide(str, d,
  1307. [&](const char *lhs_data, std::size_t lhs_size,
  1308. const char *rhs_data, std::size_t rhs_size) {
  1309. lhs.assign(lhs_data, lhs_size);
  1310. rhs.assign(rhs_data, rhs_size);
  1311. });
  1312. return std::make_pair(std::move(lhs), std::move(rhs));
  1313. };
  1314. {
  1315. const auto res = divide("", '=');
  1316. EXPECT_EQ(res.first, "");
  1317. EXPECT_EQ(res.second, "");
  1318. }
  1319. {
  1320. const auto res = divide("=", '=');
  1321. EXPECT_EQ(res.first, "");
  1322. EXPECT_EQ(res.second, "");
  1323. }
  1324. {
  1325. const auto res = divide(" ", '=');
  1326. EXPECT_EQ(res.first, " ");
  1327. EXPECT_EQ(res.second, "");
  1328. }
  1329. {
  1330. const auto res = divide("a", '=');
  1331. EXPECT_EQ(res.first, "a");
  1332. EXPECT_EQ(res.second, "");
  1333. }
  1334. {
  1335. const auto res = divide("a=", '=');
  1336. EXPECT_EQ(res.first, "a");
  1337. EXPECT_EQ(res.second, "");
  1338. }
  1339. {
  1340. const auto res = divide("=b", '=');
  1341. EXPECT_EQ(res.first, "");
  1342. EXPECT_EQ(res.second, "b");
  1343. }
  1344. {
  1345. const auto res = divide("a=b", '=');
  1346. EXPECT_EQ(res.first, "a");
  1347. EXPECT_EQ(res.second, "b");
  1348. }
  1349. {
  1350. const auto res = divide("a=b=", '=');
  1351. EXPECT_EQ(res.first, "a");
  1352. EXPECT_EQ(res.second, "b=");
  1353. }
  1354. {
  1355. const auto res = divide("a=b=c", '=');
  1356. EXPECT_EQ(res.first, "a");
  1357. EXPECT_EQ(res.second, "b=c");
  1358. }
  1359. }
  1360. TEST(SplitTest, ParseQueryString) {
  1361. string s = "key1=val1&key2=val2&key3=val3";
  1362. Params dic;
  1363. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1364. [&](const char *b, const char *e) {
  1365. string key, val;
  1366. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1367. if (key.empty()) {
  1368. key.assign(b2, e2);
  1369. } else {
  1370. val.assign(b2, e2);
  1371. }
  1372. });
  1373. dic.emplace(key, val);
  1374. });
  1375. EXPECT_EQ("val1", dic.find("key1")->second);
  1376. EXPECT_EQ("val2", dic.find("key2")->second);
  1377. EXPECT_EQ("val3", dic.find("key3")->second);
  1378. }
  1379. TEST(SplitTest, ParseInvalidQueryTests) {
  1380. {
  1381. string s = " ";
  1382. Params dict;
  1383. detail::parse_query_text(s, dict);
  1384. EXPECT_TRUE(dict.empty());
  1385. }
  1386. {
  1387. string s = " = =";
  1388. Params dict;
  1389. detail::parse_query_text(s, dict);
  1390. EXPECT_TRUE(dict.empty());
  1391. }
  1392. }
  1393. TEST(ParseQueryTest, ParseQueryString) {
  1394. {
  1395. std::string s = "key1=val1&key2=val2&key3=val3";
  1396. Params dic;
  1397. detail::parse_query_text(s, dic);
  1398. EXPECT_EQ("val1", dic.find("key1")->second);
  1399. EXPECT_EQ("val2", dic.find("key2")->second);
  1400. EXPECT_EQ("val3", dic.find("key3")->second);
  1401. }
  1402. {
  1403. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1404. Params dic;
  1405. detail::parse_query_text(s, dic);
  1406. EXPECT_EQ("", dic.find("key1")->second);
  1407. EXPECT_EQ("val1", dic.find("key2")->second);
  1408. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1409. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1410. }
  1411. }
  1412. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1413. Params dic;
  1414. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1415. dic.emplace("key1", "val1");
  1416. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1417. dic.emplace("key2", "val2");
  1418. dic.emplace("key3", "val3");
  1419. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1420. }
  1421. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1422. Params params;
  1423. params.emplace("a", "1");
  1424. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1425. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1426. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1427. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1428. // Long enough to overflow the stack when matched with std::regex.
  1429. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1430. EXPECT_EQ("/p?" + long_query + "&a=1",
  1431. append_query_params("/p?" + long_query, params));
  1432. }
  1433. // Joins every entry of a Headers or Params into "key=value " so a whole
  1434. // traversal can be compared in one assertion. Both are instantiations of the
  1435. // same insertion-ordered container, so one helper serves both.
  1436. template <typename Map> static std::string entries_to_string(const Map &m) {
  1437. std::string s;
  1438. for (const auto &entry : m) {
  1439. s += entry.first + "=" + entry.second + " ";
  1440. }
  1441. return s;
  1442. }
  1443. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1444. // Params used to be a std::multimap, which sorted by name and handed the
  1445. // caller's query back alphabetised. A client signing its query string could
  1446. // not reproduce the order it asked for.
  1447. Params dic;
  1448. dic.emplace("zulu", "1");
  1449. dic.emplace("alpha", "2");
  1450. dic.emplace("mike", "3");
  1451. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1452. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1453. }
  1454. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1455. Params dic;
  1456. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1457. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1458. }
  1459. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1460. Request req;
  1461. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1462. req.params);
  1463. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1464. EXPECT_EQ("first", req.get_param_value("tag"));
  1465. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1466. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1467. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1468. EXPECT_EQ("", req.get_param_value("tag", 3));
  1469. }
  1470. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1471. // Params shares its container with Headers, which matches field names
  1472. // case-insensitively. Parameter names must not pick that up.
  1473. Params dic;
  1474. dic.emplace("Key", "upper");
  1475. dic.emplace("key", "lower");
  1476. EXPECT_EQ(2U, dic.size());
  1477. EXPECT_EQ(1U, dic.count("Key"));
  1478. EXPECT_EQ(1U, dic.count("key"));
  1479. EXPECT_EQ("upper", dic.find("Key")->second);
  1480. EXPECT_EQ("lower", dic.find("key")->second);
  1481. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1482. }
  1483. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1484. Server svr;
  1485. std::string order;
  1486. svr.Get("/order", [&](const Request &req, Response &res) {
  1487. order = entries_to_string(req.params);
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. Client cli(HOST, port);
  1499. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1500. ASSERT_TRUE(res);
  1501. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1502. }
  1503. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1504. Server svr;
  1505. std::string field_order, file_order;
  1506. svr.Post("/order", [&](const Request &req, Response &res) {
  1507. for (const auto &field : req.form.fields) {
  1508. field_order += field.first + "=" + field.second.content + " ";
  1509. }
  1510. for (const auto &file : req.form.files) {
  1511. file_order += file.first + "=" + file.second.filename + " ";
  1512. }
  1513. res.set_content("ok", "text/plain");
  1514. });
  1515. auto port = svr.bind_to_any_port(HOST);
  1516. thread t = thread([&] { svr.listen_after_bind(); });
  1517. auto se = detail::scope_exit([&] {
  1518. svr.stop();
  1519. t.join();
  1520. ASSERT_FALSE(svr.is_running());
  1521. });
  1522. svr.wait_until_ready();
  1523. UploadFormDataItems items = {
  1524. {"zulu", "1", "", ""},
  1525. {"alpha", "2", "", ""},
  1526. {"mike", "3", "", ""},
  1527. {"zebra", "z", "z.txt", "text/plain"},
  1528. {"apple", "a", "a.txt", "text/plain"},
  1529. };
  1530. Client cli(HOST, port);
  1531. auto res = cli.Post("/order", items);
  1532. ASSERT_TRUE(res);
  1533. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1534. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1535. }
  1536. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1537. Server svr;
  1538. std::vector<std::string> values;
  1539. std::string first, second, out_of_range, order;
  1540. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1541. values = req.form.get_fields("tag");
  1542. first = req.form.get_field("tag", 0);
  1543. second = req.form.get_field("tag", 1);
  1544. out_of_range = req.form.get_field("tag", 2);
  1545. for (const auto &field : req.form.fields) {
  1546. order += field.first + "=" + field.second.content + " ";
  1547. }
  1548. res.set_content("ok", "text/plain");
  1549. });
  1550. auto port = svr.bind_to_any_port(HOST);
  1551. thread t = thread([&] { svr.listen_after_bind(); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. t.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1559. // not adjacent in the container.
  1560. UploadFormDataItems items = {
  1561. {"tag", "first", "", ""},
  1562. {"other", "x", "", ""},
  1563. {"tag", "second", "", ""},
  1564. };
  1565. Client cli(HOST, port);
  1566. auto res = cli.Post("/repeated", items);
  1567. ASSERT_TRUE(res);
  1568. ASSERT_EQ(2U, values.size());
  1569. EXPECT_EQ("first", values[0]);
  1570. EXPECT_EQ("second", values[1]);
  1571. EXPECT_EQ("first", first);
  1572. EXPECT_EQ("second", second);
  1573. // std::multimap already kept entries sharing a name in insertion order, so
  1574. // everything above passes without this change too. The whole traversal is
  1575. // what tells the two apart: sorting by name would hoist "other" to the front
  1576. // and the two "tag" parts would end up adjacent.
  1577. EXPECT_EQ("tag=first other=x tag=second ", order);
  1578. // Advancing past the last entry of a name used to run off the container;
  1579. // the container's saturating increment makes it return the default instead.
  1580. EXPECT_EQ("", out_of_range);
  1581. }
  1582. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1583. Server svr;
  1584. std::string file_names;
  1585. svr.Post("/upload", [&](const Request &req, Response &res) {
  1586. for (const auto &file : req.form.files) {
  1587. file_names += file.first + "|" + file.second.filename + " ";
  1588. }
  1589. res.set_content("ok", "text/plain");
  1590. });
  1591. auto port = svr.bind_to_any_port(HOST);
  1592. thread t = thread([&] { svr.listen_after_bind(); });
  1593. auto se = detail::scope_exit([&] {
  1594. svr.stop();
  1595. t.join();
  1596. ASSERT_FALSE(svr.is_running());
  1597. });
  1598. svr.wait_until_ready();
  1599. // A trailing backslash would otherwise escape the closing quote.
  1600. UploadFormDataItems items = {
  1601. {"dir\\", "x", "a.txt", "text/plain"},
  1602. {"b", "y", "a\\\\b.txt", "text/plain"},
  1603. };
  1604. Client cli(HOST, port);
  1605. auto res = cli.Post("/upload", items);
  1606. ASSERT_TRUE(res);
  1607. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1608. }
  1609. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1610. // Server::read_content() keeps a FormFields::iterator alive across the
  1611. // content callbacks that fill the part it points at. The container is
  1612. // vector-backed, so a later emplace can reallocate and invalidate an older
  1613. // iterator; 64 parts grow the vector through seven reallocations, which
  1614. // checks that every part's content still lands in its own entry.
  1615. const size_t part_count = 64;
  1616. // One formula for both the parts sent and the values expected back, so the
  1617. // two cannot drift apart.
  1618. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1619. auto content_of = [](size_t i) {
  1620. return std::string(64, static_cast<char>('a' + (i % 26)));
  1621. };
  1622. Server svr;
  1623. std::vector<std::pair<std::string, std::string>> received;
  1624. svr.Post("/many", [&](const Request &req, Response &res) {
  1625. for (const auto &field : req.form.fields) {
  1626. received.emplace_back(field.first, field.second.content);
  1627. }
  1628. res.set_content("ok", "text/plain");
  1629. });
  1630. auto port = svr.bind_to_any_port(HOST);
  1631. thread t = thread([&] { svr.listen_after_bind(); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. t.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. UploadFormDataItems items;
  1639. for (size_t i = 0; i < part_count; i++) {
  1640. items.push_back({name_of(i), content_of(i), "", ""});
  1641. }
  1642. Client cli(HOST, port);
  1643. auto res = cli.Post("/many", items);
  1644. ASSERT_TRUE(res);
  1645. ASSERT_EQ(part_count, received.size());
  1646. for (size_t i = 0; i < part_count; i++) {
  1647. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1648. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1649. }
  1650. }
  1651. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1652. string content_type = "multipart/form-data; boundary=something";
  1653. string boundary;
  1654. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(boundary, "something");
  1657. }
  1658. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1659. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1660. string boundary;
  1661. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1662. EXPECT_TRUE(ret);
  1663. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1666. string content_type =
  1667. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1668. string boundary;
  1669. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1670. EXPECT_TRUE(ret);
  1671. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1672. }
  1673. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1674. string content_type =
  1675. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1676. string boundary;
  1677. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1678. EXPECT_TRUE(ret);
  1679. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1680. }
  1681. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1682. const string boundary(70, 'a');
  1683. string content_type = "multipart/form-data; boundary=" + boundary;
  1684. string parsed;
  1685. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1686. EXPECT_TRUE(ret);
  1687. EXPECT_EQ(parsed, boundary);
  1688. }
  1689. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1690. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1691. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1692. string parsed;
  1693. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1694. EXPECT_FALSE(ret);
  1695. }
  1696. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1697. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1698. // is 72 characters on the wire and still valid.
  1699. const string boundary(70, 'a');
  1700. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1701. string parsed;
  1702. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1703. EXPECT_EQ(parsed, boundary);
  1704. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1705. parsed.clear();
  1706. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1709. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1710. // The parameter parser must not treat that '=' as the key/value separator.
  1711. string content_type =
  1712. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1713. "charset=UTF-8";
  1714. string parsed;
  1715. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1716. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1717. }
  1718. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1719. // A ';' inside the quoted-string is part of the value, not a parameter
  1720. // separator, so it must not truncate the boundary.
  1721. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1722. string parsed;
  1723. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1724. EXPECT_EQ(parsed, "a;b");
  1725. }
  1726. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1727. string parsed;
  1728. EXPECT_TRUE(detail::parse_multipart_boundary(
  1729. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1730. EXPECT_EQ("a\\b", parsed);
  1731. EXPECT_TRUE(detail::parse_multipart_boundary(
  1732. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1733. EXPECT_EQ("a\"b", parsed);
  1734. }
  1735. TEST(ParseDispositionParamsTest, QuotedValues) {
  1736. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1737. // ';' and '=' are ordinary characters inside one.
  1738. struct {
  1739. const char *value;
  1740. std::vector<std::pair<const char *, const char *>> expected;
  1741. } cases[] = {
  1742. {"name=\"file1\"; filename=\"a.txt\"",
  1743. {{"name", "file1"}, {"filename", "a.txt"}}},
  1744. // Whitespace around '=' and ';' is still trimmed
  1745. {"name=\"file2\" ;filename = \"a.html\"",
  1746. {{"name", "file2"}, {"filename", "a.html"}}},
  1747. // '=' inside the value used to leave only the text after the last one
  1748. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1749. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1750. {"name=\"x=y\"", {{"name", "x=y"}}},
  1751. // ';' inside the value used to truncate the pair and leave a bogus one
  1752. {"name=\"file3\"; filename=\"a;b.txt\"",
  1753. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1754. // An unquoted value keeps working, and so does filename*
  1755. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1756. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1757. // A parameter with no key is dropped rather than turned into one whose
  1758. // key is the value
  1759. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1760. // An escaped quote does not end the value
  1761. {"name=\"a\\\"; filename=evil.php\"",
  1762. {{"name", "a\"; filename=evil.php"}}},
  1763. // Other backslashes, as in a Windows path, are kept
  1764. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1765. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1766. };
  1767. for (const auto &c : cases) {
  1768. Params params;
  1769. detail::parse_disposition_params(c.value, params);
  1770. for (const auto &kv : c.expected) {
  1771. auto it = params.find(kv.first);
  1772. ASSERT_NE(it, params.end())
  1773. << "value: " << c.value << ", key: " << kv.first;
  1774. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1775. }
  1776. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1777. }
  1778. }
  1779. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1780. Server svr;
  1781. std::string filename;
  1782. std::string content;
  1783. svr.Post("/upload", [&](const Request &req, Response &) {
  1784. const auto &file = req.form.get_file("file");
  1785. filename = file.filename;
  1786. content = file.content;
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. std::string body = "--B\r\n"
  1796. "Content-Disposition: form-data; name=\"file\"; "
  1797. "filename=\"a.txt\"\r\n"
  1798. "Content-Type: text/plain\r\n"
  1799. "\r\n"
  1800. "hello\r\n"
  1801. "--B--\r\n";
  1802. Client cli(HOST, PORT);
  1803. auto res = cli.Post(
  1804. "/upload",
  1805. [&](size_t offset, DataSink &sink) {
  1806. if (offset < body.size()) {
  1807. sink.write(&body[offset], 1);
  1808. } else {
  1809. sink.done();
  1810. }
  1811. return true;
  1812. },
  1813. "multipart/form-data; boundary=B");
  1814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1815. EXPECT_EQ(StatusCode::OK_200, res->status);
  1816. EXPECT_EQ("a.txt", filename);
  1817. EXPECT_EQ("hello", content);
  1818. }
  1819. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1820. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1821. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1822. Server svr;
  1823. std::string field_value, file_name, file_filename;
  1824. bool has_field = false, has_file = false;
  1825. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1826. has_field = req.form.has_field("x=y");
  1827. field_value = req.form.get_field("x=y");
  1828. has_file = req.form.has_file("file1");
  1829. const auto &file = req.form.get_file("file1");
  1830. file_name = file.name;
  1831. file_filename = file.filename;
  1832. res.set_content("ok", "text/plain");
  1833. });
  1834. auto port = svr.bind_to_any_port(HOST);
  1835. thread t = thread([&] { svr.listen_after_bind(); });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. t.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. UploadFormDataItems items = {
  1843. {"x=y", "field-value", "", ""},
  1844. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1845. };
  1846. Client cli(HOST, port);
  1847. auto res = cli.Post("/quoted", items);
  1848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1849. ASSERT_EQ(StatusCode::OK_200, res->status);
  1850. EXPECT_TRUE(has_field);
  1851. EXPECT_EQ("field-value", field_value);
  1852. EXPECT_TRUE(has_file);
  1853. EXPECT_EQ("file1", file_name);
  1854. EXPECT_EQ("a;b=report.pdf", file_filename);
  1855. }
  1856. TEST(GetHeaderValueTest, DefaultValue) {
  1857. Headers headers = {{"Dummy", "Dummy"}};
  1858. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1859. EXPECT_STREQ("text/plain", val);
  1860. }
  1861. TEST(GetHeaderValueTest, DefaultValueInt) {
  1862. Headers headers = {{"Dummy", "Dummy"}};
  1863. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1864. EXPECT_EQ(100ull, val);
  1865. }
  1866. TEST(GetHeaderValueTest, RegularValue) {
  1867. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1868. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1869. EXPECT_STREQ("text/html", val);
  1870. }
  1871. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1872. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1873. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1874. EXPECT_STREQ("text/html", val);
  1875. }
  1876. TEST(GetHeaderValueTest, SetContent) {
  1877. Response res;
  1878. res.set_content("html", "text/html");
  1879. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1880. res.set_content("text", "text/plain");
  1881. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1882. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1883. }
  1884. TEST(GetHeaderValueTest, RegularValueInt) {
  1885. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1887. EXPECT_EQ(100ull, val);
  1888. }
  1889. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1890. Headers headers = {{"Content-Length", "x"}};
  1891. auto is_invalid_value = false;
  1892. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1893. is_invalid_value);
  1894. EXPECT_EQ(0ull, val);
  1895. EXPECT_TRUE(is_invalid_value);
  1896. }
  1897. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1898. // An all-digit value that overflows size_t must be reported as invalid, not
  1899. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1900. // a large length to a small one on 32-bit builds, leaving the framing length
  1901. // wrong while is_invalid_value stayed false.
  1902. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1903. auto is_invalid_value = false;
  1904. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1905. is_invalid_value);
  1906. EXPECT_TRUE(is_invalid_value);
  1907. // A well-formed length is unaffected.
  1908. Headers ok = {{"Content-Length", "1234"}};
  1909. is_invalid_value = false;
  1910. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1911. is_invalid_value);
  1912. EXPECT_EQ(1234ull, val);
  1913. EXPECT_FALSE(is_invalid_value);
  1914. }
  1915. TEST(GetHeaderValueTest, Range) {
  1916. {
  1917. Headers headers = {make_range_header({{1, -1}})};
  1918. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1919. EXPECT_STREQ("bytes=1-", val);
  1920. }
  1921. {
  1922. Headers headers = {make_range_header({{-1, 1}})};
  1923. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1924. EXPECT_STREQ("bytes=-1", val);
  1925. }
  1926. {
  1927. Headers headers = {make_range_header({{1, 10}})};
  1928. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1929. EXPECT_STREQ("bytes=1-10", val);
  1930. }
  1931. {
  1932. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1933. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1934. EXPECT_STREQ("bytes=1-10, 100-", val);
  1935. }
  1936. {
  1937. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1938. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1939. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1940. }
  1941. {
  1942. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1943. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1944. EXPECT_STREQ("bytes=0-0, -1", val);
  1945. }
  1946. }
  1947. TEST(BearerTokenAuthTest, SchemeValidation) {
  1948. // A value shorter than "Bearer " must not throw from the fixed-length
  1949. // substr, and a non-Bearer scheme must not be reported as a token.
  1950. struct {
  1951. const char *value;
  1952. const char *expected;
  1953. } cases[] = {
  1954. {"x", ""},
  1955. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1956. {"Bearer abc123", "abc123"},
  1957. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1958. };
  1959. for (const auto &c : cases) {
  1960. Request req;
  1961. req.set_header("Authorization", c.value);
  1962. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1963. }
  1964. }
  1965. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1966. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1967. // to depend on the standard library (libstdc++ handed back duplicates in
  1968. // reverse insertion order, libc++ in insertion order).
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "gzip");
  1971. req.set_header("Accept-Encoding", "deflate");
  1972. req.set_header("Accept-Encoding", "br");
  1973. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1974. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1975. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1976. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1977. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1978. }
  1979. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1980. Request req;
  1981. req.set_header("X-Test", "only");
  1982. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1983. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1984. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1985. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1986. }
  1987. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1988. Request req;
  1989. req.set_header("X-First", "1");
  1990. req.set_header("X-Test", "2");
  1991. req.params.emplace("first", "1");
  1992. req.params.emplace("test", "2");
  1993. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1994. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1995. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1996. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1997. // The second one is negative when read as a signed value
  1998. const auto max_id = (std::numeric_limits<size_t>::max)();
  1999. for (auto id : {max_id / 2, max_id}) {
  2000. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2001. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2002. EXPECT_EQ("", req.get_param_value("test", id));
  2003. EXPECT_EQ("", req.form.get_field("test", id));
  2004. EXPECT_EQ("", req.form.get_file("test", id).content);
  2005. }
  2006. }
  2007. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2008. Headers headers;
  2009. headers.emplace("Host", "example.com");
  2010. headers.emplace("Accept-Encoding", "gzip");
  2011. headers.emplace("User-Agent", "test");
  2012. headers.emplace("Accept-Encoding", "deflate");
  2013. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2014. "Accept-Encoding=deflate ",
  2015. entries_to_string(headers));
  2016. }
  2017. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2018. Headers headers = {{"Content-Type", "text/html"},
  2019. {"CONTENT-TYPE", "text/xml"}};
  2020. EXPECT_EQ(2U, headers.count("content-type"));
  2021. auto it = headers.find("content-type");
  2022. ASSERT_TRUE(it != headers.end());
  2023. EXPECT_EQ("text/html", it->second);
  2024. }
  2025. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2026. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2027. // drop only those fields and leave everything positioned between them.
  2028. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2029. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2030. auto rng = headers.equal_range("a");
  2031. headers.erase(rng.first, rng.second);
  2032. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2033. }
  2034. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2035. Headers headers = {
  2036. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2037. EXPECT_EQ(3U, headers.erase("A"));
  2038. EXPECT_EQ(0U, headers.count("A"));
  2039. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2040. }
  2041. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2042. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2043. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2044. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2045. }
  2046. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2047. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2048. headers.emplace_front("Host", "example.com");
  2049. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2050. entries_to_string(headers));
  2051. }
  2052. TEST(ParseHeaderValueTest, Range) {
  2053. {
  2054. Ranges ranges;
  2055. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2056. EXPECT_TRUE(ret);
  2057. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2058. }
  2059. {
  2060. Ranges ranges;
  2061. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2062. EXPECT_TRUE(ret);
  2063. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2064. }
  2065. {
  2066. Ranges ranges;
  2067. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2068. EXPECT_TRUE(ret);
  2069. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2070. }
  2071. {
  2072. Ranges ranges;
  2073. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2074. EXPECT_FALSE(ret);
  2075. }
  2076. {
  2077. Ranges ranges;
  2078. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2079. EXPECT_TRUE(ret);
  2080. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2081. }
  2082. {
  2083. Ranges ranges;
  2084. auto ret =
  2085. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2086. EXPECT_TRUE(ret);
  2087. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2088. }
  2089. {
  2090. Ranges ranges;
  2091. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2092. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2093. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2094. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2095. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2096. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2097. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2098. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2099. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2100. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2101. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2102. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2103. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2104. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2105. EXPECT_FALSE(
  2106. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2107. EXPECT_TRUE(ranges.empty());
  2108. }
  2109. {
  2110. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2111. // remainder of the representation, so it stays accepted.
  2112. Ranges ranges;
  2113. auto ret =
  2114. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2115. EXPECT_TRUE(ret);
  2116. ASSERT_EQ(1u, ranges.size());
  2117. EXPECT_EQ(0, ranges[0].first);
  2118. EXPECT_EQ(-1, ranges[0].second);
  2119. }
  2120. // RFC 9110 14.1: range unit names are case-insensitive.
  2121. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2122. Ranges ranges;
  2123. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2124. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2125. }
  2126. }
  2127. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2128. Request req;
  2129. req.set_header("Accept-Encoding", "gzip");
  2130. Response res;
  2131. res.set_header("Content-Type", "text/plain");
  2132. auto ret = detail::encoding_type(req, res);
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #else
  2136. EXPECT_TRUE(ret == detail::EncodingType::None);
  2137. #endif
  2138. }
  2139. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2140. Request req;
  2141. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2142. Response res;
  2143. res.set_header("Content-Type", "text/plain");
  2144. auto ret = detail::encoding_type(req, res);
  2145. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2146. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2147. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2149. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2151. #else
  2152. EXPECT_TRUE(ret == detail::EncodingType::None);
  2153. #endif
  2154. }
  2155. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2156. Request req;
  2157. req.set_header("Accept-Encoding",
  2158. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2159. Response res;
  2160. res.set_header("Content-Type", "text/plain");
  2161. auto ret = detail::encoding_type(req, res);
  2162. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2163. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2164. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2165. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2166. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2168. #else
  2169. EXPECT_TRUE(ret == detail::EncodingType::None);
  2170. #endif
  2171. }
  2172. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2173. // All supported encodings rejected with q=0 should return None
  2174. Request req;
  2175. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2176. Response res;
  2177. res.set_header("Content-Type", "text/plain");
  2178. auto ret = detail::encoding_type(req, res);
  2179. EXPECT_TRUE(ret == detail::EncodingType::None);
  2180. }
  2181. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2182. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2183. Request req;
  2184. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2185. Response res;
  2186. res.set_header("Content-Type", "text/plain");
  2187. auto ret = detail::encoding_type(req, res);
  2188. EXPECT_TRUE(ret == detail::EncodingType::None);
  2189. }
  2190. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2191. Request req;
  2192. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2193. Response res;
  2194. res.set_header("Content-Type", "text/plain");
  2195. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2196. }
  2197. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2198. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2199. Request req;
  2200. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2201. Response res;
  2202. res.set_header("Content-Type", "text/plain");
  2203. auto ret = detail::encoding_type(req, res);
  2204. EXPECT_TRUE(ret == detail::EncodingType::None);
  2205. }
  2206. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2207. // RFC 7231: Accept-Encoding values are case-insensitive
  2208. Request req;
  2209. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2210. Response res;
  2211. res.set_header("Content-Type", "text/plain");
  2212. auto ret = detail::encoding_type(req, res);
  2213. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2214. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2215. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2216. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2217. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2218. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2219. #else
  2220. EXPECT_TRUE(ret == detail::EncodingType::None);
  2221. #endif
  2222. }
  2223. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2224. // q value should determine priority, not hardcoded order
  2225. Request req;
  2226. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2227. Response res;
  2228. res.set_header("Content-Type", "text/plain");
  2229. auto ret = detail::encoding_type(req, res);
  2230. // gzip has highest q=1.0, so it should be selected even though
  2231. // br and zstd are also supported
  2232. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2233. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2234. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2235. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2236. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2237. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2238. #else
  2239. EXPECT_TRUE(ret == detail::EncodingType::None);
  2240. #endif
  2241. }
  2242. TEST(BufferStreamTest, read) {
  2243. detail::BufferStream strm1;
  2244. Stream &strm = strm1;
  2245. EXPECT_EQ(5, strm.write("hello"));
  2246. char buf[512];
  2247. EXPECT_EQ(2, strm.read(buf, 2));
  2248. EXPECT_EQ('h', buf[0]);
  2249. EXPECT_EQ('e', buf[1]);
  2250. EXPECT_EQ(2, strm.read(buf, 2));
  2251. EXPECT_EQ('l', buf[0]);
  2252. EXPECT_EQ('l', buf[1]);
  2253. EXPECT_EQ(1, strm.read(buf, 1));
  2254. EXPECT_EQ('o', buf[0]);
  2255. EXPECT_EQ(0, strm.read(buf, 1));
  2256. }
  2257. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2258. auto host = "www.httpwatch.com";
  2259. auto ip = hosted_at(host);
  2260. EXPECT_EQ("23.96.13.243", ip);
  2261. std::vector<std::string> addrs;
  2262. hosted_at(host, addrs);
  2263. EXPECT_EQ(1u, addrs.size());
  2264. }
  2265. #if 0 // It depends on each test environment...
  2266. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2267. auto host = "www.youtube.com";
  2268. std::vector<std::string> addrs;
  2269. hosted_at(host, addrs);
  2270. EXPECT_EQ(20u, addrs.size());
  2271. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2272. EXPECT_TRUE(it != addrs.end());
  2273. }
  2274. #endif
  2275. class ChunkedEncodingTest : public ::testing::Test {
  2276. protected:
  2277. ChunkedEncodingTest()
  2278. : cli_(HOST, PORT)
  2279. #ifdef CPPHTTPLIB_SSL_ENABLED
  2280. ,
  2281. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2282. #endif
  2283. {
  2284. cli_.set_connection_timeout(2);
  2285. #ifdef CPPHTTPLIB_SSL_ENABLED
  2286. cli_.enable_server_certificate_verification(false);
  2287. #endif
  2288. }
  2289. virtual void SetUp() {
  2290. read_file("./image.jpg", image_data_);
  2291. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2292. res.set_content("Hello World!", "text/plain");
  2293. });
  2294. svr_.Get(
  2295. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2296. res.set_chunked_content_provider(
  2297. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2298. size_t remaining = image_data_.size() - offset;
  2299. if (remaining == 0) {
  2300. sink.done();
  2301. } else {
  2302. constexpr size_t CHUNK_SIZE = 1024;
  2303. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2304. sink.write(&image_data_[offset], send_size);
  2305. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2306. }
  2307. return true;
  2308. });
  2309. });
  2310. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2311. svr_.wait_until_ready();
  2312. }
  2313. virtual void TearDown() {
  2314. svr_.stop();
  2315. if (!request_threads_.empty()) {
  2316. std::this_thread::sleep_for(std::chrono::seconds(1));
  2317. for (auto &t : request_threads_) {
  2318. t.join();
  2319. }
  2320. }
  2321. t_.join();
  2322. }
  2323. #ifdef CPPHTTPLIB_SSL_ENABLED
  2324. SSLClient cli_;
  2325. SSLServer svr_;
  2326. #else
  2327. Client cli_;
  2328. Server svr_;
  2329. #endif
  2330. thread t_;
  2331. std::vector<thread> request_threads_;
  2332. std::string image_data_;
  2333. };
  2334. TEST_F(ChunkedEncodingTest, NormalGet) {
  2335. auto res = cli_.Get("/chunked");
  2336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2337. std::string out;
  2338. read_file("./image.jpg", out);
  2339. EXPECT_EQ(StatusCode::OK_200, res->status);
  2340. EXPECT_EQ(out, res->body);
  2341. }
  2342. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2343. std::string body;
  2344. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2345. body.append(data, data_length);
  2346. return true;
  2347. });
  2348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2349. std::string out;
  2350. read_file("./image.jpg", out);
  2351. EXPECT_EQ(StatusCode::OK_200, res->status);
  2352. EXPECT_EQ(out, body);
  2353. }
  2354. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2355. std::string body;
  2356. auto res = cli_.Get(
  2357. "/chunked",
  2358. [&](const Response &response) {
  2359. EXPECT_EQ(StatusCode::OK_200, response.status);
  2360. return true;
  2361. },
  2362. [&](const char *data, size_t data_length) {
  2363. body.append(data, data_length);
  2364. return true;
  2365. });
  2366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2367. std::string out;
  2368. read_file("./image.jpg", out);
  2369. EXPECT_EQ(StatusCode::OK_200, res->status);
  2370. EXPECT_EQ(out, body);
  2371. }
  2372. TEST(RangeTest, FromHTTPBin_Online) {
  2373. auto host = "httpbingo.org";
  2374. auto path = std::string{"/range/32"};
  2375. #ifdef CPPHTTPLIB_SSL_ENABLED
  2376. auto port = 443;
  2377. SSLClient cli(host, port);
  2378. #else
  2379. auto port = 80;
  2380. Client cli(host, port);
  2381. #endif
  2382. cli.set_connection_timeout(5);
  2383. {
  2384. auto res = cli.Get(path);
  2385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2386. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2387. EXPECT_EQ(StatusCode::OK_200, res->status);
  2388. }
  2389. {
  2390. Headers headers = {make_range_header({{1, -1}})};
  2391. auto res = cli.Get(path, headers);
  2392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2393. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2395. }
  2396. {
  2397. Headers headers = {make_range_header({{1, 10}})};
  2398. auto res = cli.Get(path, headers);
  2399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2400. EXPECT_EQ("bcdefghijk", res->body);
  2401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2402. }
  2403. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2404. // entire resource, while the original httpbin returned 200. Both are
  2405. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2406. {
  2407. Headers headers = {make_range_header({{0, 31}})};
  2408. auto res = cli.Get(path, headers);
  2409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2410. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2411. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2412. res->status == StatusCode::PartialContent_206);
  2413. }
  2414. {
  2415. Headers headers = {make_range_header({{0, -1}})};
  2416. auto res = cli.Get(path, headers);
  2417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2418. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2419. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2420. res->status == StatusCode::PartialContent_206);
  2421. }
  2422. // go-httpbin returns 206 with clamped range for over-range requests,
  2423. // while the original httpbin returned 416. Both behaviors are observed
  2424. // in real servers, so we only verify the request succeeds.
  2425. {
  2426. Headers headers = {make_range_header({{0, 32}})};
  2427. auto res = cli.Get(path, headers);
  2428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2429. }
  2430. }
  2431. TEST(RangeTest, IgnoredForPost) {
  2432. Server svr;
  2433. svr.Post("/", [](const Request &, Response &res) {
  2434. res.set_content("abcdefg", "text/plain");
  2435. });
  2436. auto port = svr.bind_to_any_port(HOST);
  2437. ASSERT_GT(port, 0);
  2438. thread t = thread([&] { svr.listen_after_bind(); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. t.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli(HOST, port);
  2446. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2447. auto res = cli.Post("/", Headers{{"Range", range}});
  2448. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2449. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2450. EXPECT_EQ("abcdefg", res->body) << range;
  2451. }
  2452. }
  2453. TEST(RangeTest, IgnoredForUnknownUnit) {
  2454. Server svr;
  2455. svr.Get("/", [](const Request &, Response &res) {
  2456. res.set_content("abcdefg", "text/plain");
  2457. });
  2458. auto port = svr.bind_to_any_port(HOST);
  2459. ASSERT_GT(port, 0);
  2460. thread t = thread([&] { svr.listen_after_bind(); });
  2461. auto se = detail::scope_exit([&] {
  2462. svr.stop();
  2463. t.join();
  2464. ASSERT_FALSE(svr.is_running());
  2465. });
  2466. svr.wait_until_ready();
  2467. Client cli(HOST, port);
  2468. for (auto range : {"items=1-2", "none=x"}) {
  2469. auto res = cli.Get("/", Headers{{"Range", range}});
  2470. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2471. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2472. EXPECT_EQ("abcdefg", res->body) << range;
  2473. }
  2474. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2475. ASSERT_TRUE(res) << to_string(res.error());
  2476. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2477. }
  2478. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2479. auto host = "unresolvableaddress.local";
  2480. auto path = std::string{"/"};
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. auto port = 443;
  2483. SSLClient cli(host, port);
  2484. #else
  2485. auto port = 80;
  2486. Client cli(host, port);
  2487. #endif
  2488. cli.set_connection_timeout(1);
  2489. {
  2490. auto res = cli.Get(path);
  2491. ASSERT_FALSE(res);
  2492. }
  2493. std::this_thread::sleep_for(std::chrono::seconds(8));
  2494. }
  2495. #if defined(__linux__) && defined(__GLIBC__) && \
  2496. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2497. // Forward declaration: in split builds split.py strips `inline` and moves the
  2498. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2499. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2500. // against the symbol in both header-only and split builds.
  2501. namespace httplib {
  2502. namespace detail {
  2503. int getaddrinfo_with_timeout(const char *node, const char *service,
  2504. const struct addrinfo *hints,
  2505. struct addrinfo **res, time_t timeout_sec);
  2506. } // namespace detail
  2507. } // namespace httplib
  2508. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2509. //
  2510. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2511. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2512. // gai_suspend() call hits the connection timeout the function calls
  2513. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2514. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2515. // still alive and still references the now-destroyed stack frame.
  2516. //
  2517. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2518. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2519. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2520. // and runs them in a container.
  2521. namespace {
  2522. bool should_run_issue_2431_tests() {
  2523. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2524. return v && *v && std::string(v) != "0";
  2525. }
  2526. std::string unique_unresolvable_host(int n) {
  2527. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2528. // glibc still asks the configured nameserver — which is exactly the path
  2529. // we want to exercise. A unique label per call avoids the resolver cache.
  2530. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2531. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2532. std::to_string(n) + ".invalid";
  2533. }
  2534. } // namespace
  2535. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2536. if (!should_run_issue_2431_tests()) {
  2537. GTEST_SKIP()
  2538. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2539. }
  2540. for (int i = 0; i < 8; ++i) {
  2541. struct addrinfo hints;
  2542. memset(&hints, 0, sizeof(hints));
  2543. hints.ai_family = AF_UNSPEC;
  2544. hints.ai_socktype = SOCK_STREAM;
  2545. auto host = unique_unresolvable_host(i);
  2546. struct addrinfo *result = nullptr;
  2547. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2548. &result, /*timeout_sec=*/1);
  2549. if (rc == 0 && result) { freeaddrinfo(result); }
  2550. }
  2551. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2552. // stack region they still believe holds their gaicb.
  2553. std::this_thread::sleep_for(std::chrono::seconds(3));
  2554. }
  2555. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2556. if (!should_run_issue_2431_tests()) {
  2557. GTEST_SKIP()
  2558. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2559. }
  2560. std::atomic<bool> stop{false};
  2561. std::vector<std::thread> threads;
  2562. for (int t = 0; t < 8; ++t) {
  2563. threads.emplace_back([t, &stop] {
  2564. int i = 0;
  2565. while (!stop.load(std::memory_order_relaxed)) {
  2566. struct addrinfo hints;
  2567. memset(&hints, 0, sizeof(hints));
  2568. hints.ai_family = AF_UNSPEC;
  2569. hints.ai_socktype = SOCK_STREAM;
  2570. auto host = unique_unresolvable_host(t * 100000 + i++);
  2571. struct addrinfo *result = nullptr;
  2572. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2573. &result, /*timeout_sec=*/1);
  2574. if (rc == 0 && result) { freeaddrinfo(result); }
  2575. }
  2576. });
  2577. }
  2578. std::this_thread::sleep_for(std::chrono::seconds(8));
  2579. stop.store(true, std::memory_order_relaxed);
  2580. for (auto &th : threads) {
  2581. th.join();
  2582. }
  2583. std::this_thread::sleep_for(std::chrono::seconds(3));
  2584. }
  2585. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2586. if (!should_run_issue_2431_tests()) {
  2587. GTEST_SKIP()
  2588. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2589. }
  2590. std::atomic<bool> stop{false};
  2591. std::vector<std::thread> threads;
  2592. for (int t = 0; t < 8; ++t) {
  2593. threads.emplace_back([t, &stop] {
  2594. int i = 0;
  2595. while (!stop.load(std::memory_order_relaxed)) {
  2596. auto host = unique_unresolvable_host(t * 100000 + i++);
  2597. Client cli(host, 80);
  2598. cli.set_connection_timeout(1, 0);
  2599. cli.set_read_timeout(1, 0);
  2600. cli.set_write_timeout(1, 0);
  2601. (void)cli.Get("/");
  2602. }
  2603. });
  2604. }
  2605. std::this_thread::sleep_for(std::chrono::seconds(8));
  2606. stop.store(true, std::memory_order_relaxed);
  2607. for (auto &th : threads) {
  2608. th.join();
  2609. }
  2610. std::this_thread::sleep_for(std::chrono::seconds(3));
  2611. }
  2612. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2613. TEST(ConnectionErrorTest, InvalidHost) {
  2614. auto host = "-abcde.com";
  2615. #ifdef CPPHTTPLIB_SSL_ENABLED
  2616. auto port = 443;
  2617. SSLClient cli(host, port);
  2618. #else
  2619. auto port = 80;
  2620. Client cli(host, port);
  2621. #endif
  2622. cli.set_connection_timeout(std::chrono::seconds(2));
  2623. auto res = cli.Get("/");
  2624. ASSERT_TRUE(!res);
  2625. EXPECT_EQ(Error::Connection, res.error());
  2626. }
  2627. TEST(ConnectionErrorTest, InvalidHost2) {
  2628. auto host = "httpcan.org/";
  2629. #ifdef CPPHTTPLIB_SSL_ENABLED
  2630. SSLClient cli(host);
  2631. #else
  2632. Client cli(host);
  2633. #endif
  2634. cli.set_connection_timeout(std::chrono::seconds(2));
  2635. auto res = cli.Get("/");
  2636. ASSERT_TRUE(!res);
  2637. EXPECT_EQ(Error::Connection, res.error());
  2638. }
  2639. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2640. auto host = "httpcan.org/";
  2641. #ifdef CPPHTTPLIB_SSL_ENABLED
  2642. SSLClient cli(host);
  2643. #else
  2644. Client cli(host);
  2645. #endif
  2646. cli.set_connection_timeout(std::chrono::seconds(2));
  2647. auto res = cli.Get("/");
  2648. ASSERT_TRUE(!res);
  2649. stringstream s;
  2650. s << "error code: " << res.error();
  2651. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2652. }
  2653. TEST(ConnectionErrorTest, InvalidPort) {
  2654. auto host = "localhost";
  2655. auto port = 44380;
  2656. #ifdef CPPHTTPLIB_SSL_ENABLED
  2657. SSLClient cli(host, port);
  2658. #else
  2659. Client cli(host, port);
  2660. #endif
  2661. cli.set_connection_timeout(std::chrono::seconds(2));
  2662. auto res = cli.Get("/");
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_TRUE(Error::Connection == res.error() ||
  2665. Error::ConnectionTimeout == res.error());
  2666. }
  2667. TEST(ConnectionErrorTest, Timeout_Online) {
  2668. auto host = "google.com";
  2669. #ifdef CPPHTTPLIB_SSL_ENABLED
  2670. auto port = 44380;
  2671. SSLClient cli(host, port);
  2672. #else
  2673. auto port = 8080;
  2674. Client cli(host, port);
  2675. #endif
  2676. cli.set_connection_timeout(std::chrono::seconds(2));
  2677. // only probe one address type so that the error reason
  2678. // correlates to the timed-out IPv4, not the unsupported
  2679. // IPv6 connection attempt
  2680. cli.set_address_family(AF_INET);
  2681. auto res = cli.Get("/");
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2684. }
  2685. TEST(CancelTest, NoCancel_Online) {
  2686. auto host = "httpbingo.org";
  2687. auto path = std::string{"/range/32"};
  2688. #ifdef CPPHTTPLIB_SSL_ENABLED
  2689. auto port = 443;
  2690. SSLClient cli(host, port);
  2691. #else
  2692. auto port = 80;
  2693. Client cli(host, port);
  2694. #endif
  2695. cli.set_connection_timeout(std::chrono::seconds(5));
  2696. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2698. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2699. EXPECT_EQ(StatusCode::OK_200, res->status);
  2700. }
  2701. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2702. // Use /bytes with a large payload so that the DownloadProgress callback
  2703. // (which only fires for Content-Length responses) is invoked before the
  2704. // entire body is received, giving cancellation a chance to fire.
  2705. auto host = "httpbingo.org";
  2706. auto path = std::string{"/bytes/524288"};
  2707. #ifdef CPPHTTPLIB_SSL_ENABLED
  2708. auto port = 443;
  2709. SSLClient cli(host, port);
  2710. #else
  2711. auto port = 80;
  2712. Client cli(host, port);
  2713. #endif
  2714. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2715. cli.set_connection_timeout(std::chrono::seconds(5));
  2716. ASSERT_TRUE(!res);
  2717. EXPECT_EQ(Error::Canceled, res.error());
  2718. }
  2719. TEST(CancelTest, WithCancelLargePayload_Online) {
  2720. auto host = "httpbingo.org";
  2721. auto path = std::string{"/bytes/524288"};
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. auto port = 443;
  2724. SSLClient cli(host, port);
  2725. #else
  2726. auto port = 80;
  2727. Client cli(host, port);
  2728. #endif
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. uint32_t count = 0;
  2731. auto res =
  2732. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelPost) {
  2737. Server svr;
  2738. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2758. Server svr;
  2759. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadPost) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. TEST(CancelTest, NoCancelPut) {
  2800. Server svr;
  2801. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("Hello World!", "text/plain");
  2803. });
  2804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2805. auto se = detail::scope_exit([&] {
  2806. svr.stop();
  2807. thread.join();
  2808. ASSERT_FALSE(svr.is_running());
  2809. });
  2810. svr.wait_until_ready();
  2811. Client cli(HOST, PORT);
  2812. cli.set_connection_timeout(std::chrono::seconds(5));
  2813. auto res =
  2814. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2815. "application/json", [](uint64_t, uint64_t) { return true; });
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ("Hello World!", res->body);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. }
  2820. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2821. Server svr;
  2822. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2823. res.set_content("Hello World!", "text/plain");
  2824. });
  2825. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2826. auto se = detail::scope_exit([&] {
  2827. svr.stop();
  2828. thread.join();
  2829. ASSERT_FALSE(svr.is_running());
  2830. });
  2831. svr.wait_until_ready();
  2832. Client cli(HOST, PORT);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. TEST(CancelTest, WithCancelLargePayloadPut) {
  2841. Server svr;
  2842. svr.set_payload_max_length(200 * 1024 * 1024);
  2843. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2844. res.set_content(LARGE_DATA, "text/plain");
  2845. });
  2846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. Client cli(HOST, PORT);
  2854. cli.set_payload_max_length(200 * 1024 * 1024);
  2855. cli.set_connection_timeout(std::chrono::seconds(5));
  2856. auto res =
  2857. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2858. "application/json", [](uint64_t, uint64_t) { return false; });
  2859. ASSERT_TRUE(!res);
  2860. EXPECT_EQ(Error::Canceled, res.error());
  2861. }
  2862. TEST(CancelTest, NoCancelPatch) {
  2863. Server svr;
  2864. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2865. res.set_content("Hello World!", "text/plain");
  2866. });
  2867. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2868. auto se = detail::scope_exit([&] {
  2869. svr.stop();
  2870. thread.join();
  2871. ASSERT_FALSE(svr.is_running());
  2872. });
  2873. svr.wait_until_ready();
  2874. Client cli(HOST, PORT);
  2875. cli.set_connection_timeout(std::chrono::seconds(5));
  2876. auto res =
  2877. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2878. "application/json", [](uint64_t, uint64_t) { return true; });
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ("Hello World!", res->body);
  2881. EXPECT_EQ(StatusCode::OK_200, res->status);
  2882. }
  2883. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2884. Server svr;
  2885. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2886. res.set_content("Hello World!", "text/plain");
  2887. });
  2888. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. thread.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. Client cli(HOST, PORT);
  2896. cli.set_connection_timeout(std::chrono::seconds(5));
  2897. auto res =
  2898. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2899. "application/json", [](uint64_t, uint64_t) { return false; });
  2900. ASSERT_TRUE(!res);
  2901. EXPECT_EQ(Error::Canceled, res.error());
  2902. }
  2903. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2904. Server svr;
  2905. svr.set_payload_max_length(200 * 1024 * 1024);
  2906. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2907. res.set_content(LARGE_DATA, "text/plain");
  2908. });
  2909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2910. auto se = detail::scope_exit([&] {
  2911. svr.stop();
  2912. thread.join();
  2913. ASSERT_FALSE(svr.is_running());
  2914. });
  2915. svr.wait_until_ready();
  2916. Client cli(HOST, PORT);
  2917. cli.set_payload_max_length(200 * 1024 * 1024);
  2918. cli.set_connection_timeout(std::chrono::seconds(5));
  2919. auto res =
  2920. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2921. "application/json", [](uint64_t, uint64_t) { return false; });
  2922. ASSERT_TRUE(!res);
  2923. EXPECT_EQ(Error::Canceled, res.error());
  2924. }
  2925. TEST(CancelTest, NoCancelDelete) {
  2926. Server svr;
  2927. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2928. res.set_content("Hello World!", "text/plain");
  2929. });
  2930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2931. auto se = detail::scope_exit([&] {
  2932. svr.stop();
  2933. thread.join();
  2934. ASSERT_FALSE(svr.is_running());
  2935. });
  2936. svr.wait_until_ready();
  2937. Client cli(HOST, PORT);
  2938. cli.set_connection_timeout(std::chrono::seconds(5));
  2939. auto res =
  2940. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2941. "application/json", [](uint64_t, uint64_t) { return true; });
  2942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2943. EXPECT_EQ("Hello World!", res->body);
  2944. EXPECT_EQ(StatusCode::OK_200, res->status);
  2945. }
  2946. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2947. Server svr;
  2948. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2949. res.set_content("Hello World!", "text/plain");
  2950. });
  2951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2952. auto se = detail::scope_exit([&] {
  2953. svr.stop();
  2954. thread.join();
  2955. ASSERT_FALSE(svr.is_running());
  2956. });
  2957. svr.wait_until_ready();
  2958. Client cli(HOST, PORT);
  2959. cli.set_connection_timeout(std::chrono::seconds(5));
  2960. auto res =
  2961. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2962. "application/json", [](uint64_t, uint64_t) { return false; });
  2963. ASSERT_TRUE(!res);
  2964. EXPECT_EQ(Error::Canceled, res.error());
  2965. }
  2966. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2967. Server svr;
  2968. svr.set_payload_max_length(200 * 1024 * 1024);
  2969. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2970. res.set_content(LARGE_DATA, "text/plain");
  2971. });
  2972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2973. auto se = detail::scope_exit([&] {
  2974. svr.stop();
  2975. thread.join();
  2976. ASSERT_FALSE(svr.is_running());
  2977. });
  2978. svr.wait_until_ready();
  2979. Client cli(HOST, PORT);
  2980. cli.set_payload_max_length(200 * 1024 * 1024);
  2981. cli.set_connection_timeout(std::chrono::seconds(5));
  2982. auto res =
  2983. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2984. "application/json", [](uint64_t, uint64_t) { return false; });
  2985. ASSERT_TRUE(!res);
  2986. EXPECT_EQ(Error::Canceled, res.error());
  2987. }
  2988. // One stop() from another thread ends a request that waits for the response
  2989. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2990. Server svr;
  2991. std::atomic<bool> received{false};
  2992. std::atomic<bool> done{false};
  2993. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2994. received.store(true);
  2995. while (!done.load()) {
  2996. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2997. }
  2998. res.set_content("Hello World!", "text/plain");
  2999. });
  3000. auto port = svr.bind_to_any_port(HOST);
  3001. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3002. Client cli(HOST, port);
  3003. cli.set_read_timeout(std::chrono::seconds(30));
  3004. std::future<Result> request;
  3005. auto se = detail::scope_exit([&] {
  3006. done.store(true);
  3007. svr.stop();
  3008. thread.join();
  3009. ASSERT_FALSE(svr.is_running());
  3010. });
  3011. svr.wait_until_ready();
  3012. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3013. for (int i = 0; i < 500 && !received.load(); ++i) {
  3014. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3015. }
  3016. ASSERT_TRUE(received.load());
  3017. // Let the client block in the wait for the response
  3018. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3019. auto start = std::chrono::steady_clock::now();
  3020. cli.stop();
  3021. ASSERT_EQ(std::future_status::ready,
  3022. request.wait_for(std::chrono::seconds(5)));
  3023. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3024. auto res = request.get();
  3025. ASSERT_TRUE(!res);
  3026. EXPECT_EQ(Error::Read, res.error());
  3027. }
  3028. // A listener whose backlog completes the TCP connections of clients, and that
  3029. // never answers them
  3030. struct SilentListener {
  3031. socket_t sock = INVALID_SOCKET;
  3032. sockaddr_in addr{};
  3033. int port = 0;
  3034. explicit SilentListener(int backlog = 1) {
  3035. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3036. addr.sin_family = AF_INET;
  3037. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3038. socklen_t len = sizeof(addr);
  3039. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3040. ::listen(sock, backlog) != 0 ||
  3041. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3042. detail::close_socket(sock);
  3043. sock = INVALID_SOCKET;
  3044. }
  3045. port = ntohs(addr.sin_port);
  3046. }
  3047. ~SilentListener() { detail::close_socket(sock); }
  3048. // The next connection, whose reads give up after 5 seconds
  3049. socket_t accept() const {
  3050. auto peer = ::accept(sock, nullptr, nullptr);
  3051. if (peer != INVALID_SOCKET) {
  3052. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3053. }
  3054. return peer;
  3055. }
  3056. };
  3057. static bool receives_a_byte(socket_t peer) {
  3058. char c = 0;
  3059. return detail::read_socket(peer, &c, 1, 0) == 1;
  3060. }
  3061. // Runs op, stops cli once the listener receives the first byte op sends, and
  3062. // expects op to end with error soon after
  3063. template <typename ClientType, typename Op>
  3064. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3065. Op op, Error error = Error::Canceled) {
  3066. auto ended = std::async(std::launch::async, op);
  3067. auto peer = listener.accept();
  3068. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3069. ASSERT_NE(INVALID_SOCKET, peer);
  3070. ASSERT_TRUE(receives_a_byte(peer));
  3071. cli.stop();
  3072. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3073. EXPECT_EQ(error, ended.get());
  3074. }
  3075. // Stops itself from another thread as the connection opens, the last moment a
  3076. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3077. // waits for the connection fails the test instead of hanging it.
  3078. class StoppedAsConnectedClient : public ClientImpl {
  3079. public:
  3080. using ClientImpl::ClientImpl;
  3081. protected:
  3082. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3083. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3084. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3085. stopper_.wait_for(std::chrono::seconds(1));
  3086. return true;
  3087. }
  3088. private:
  3089. std::future<void> stopper_;
  3090. };
  3091. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3092. SilentListener listener;
  3093. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3094. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3095. cli.set_read_timeout(std::chrono::seconds(3));
  3096. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3097. auto peer = listener.accept();
  3098. EXPECT_FALSE(receives_a_byte(peer));
  3099. detail::close_socket(peer);
  3100. auto handle = cli.open_stream("GET", "/");
  3101. EXPECT_FALSE(handle.is_valid());
  3102. EXPECT_EQ(Error::Canceled, handle.error);
  3103. peer = listener.accept();
  3104. EXPECT_FALSE(receives_a_byte(peer));
  3105. detail::close_socket(peer);
  3106. }
  3107. #ifdef __linux__
  3108. // A connect that a listener with a full backlog never completes
  3109. TEST(ClientStopTest, StopEndsAConnect) {
  3110. SilentListener listener(0);
  3111. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3112. std::vector<socket_t> backlog;
  3113. auto close_backlog = detail::scope_exit([&] {
  3114. for (auto sock : backlog) {
  3115. detail::close_socket(sock);
  3116. }
  3117. });
  3118. for (int i = 0; i < 8; i++) {
  3119. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3120. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3121. sizeof(listener.addr));
  3122. backlog.push_back(sock);
  3123. }
  3124. Client cli("127.0.0.1", listener.port);
  3125. cli.set_connection_timeout(std::chrono::seconds(3));
  3126. auto ended =
  3127. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3128. // A stop() before the request starts does not apply to it, so it repeats
  3129. auto status = std::future_status::timeout;
  3130. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3131. cli.stop();
  3132. status = ended.wait_for(std::chrono::milliseconds(10));
  3133. }
  3134. EXPECT_EQ(std::future_status::ready, status);
  3135. EXPECT_EQ(Error::Canceled, ended.get());
  3136. }
  3137. #endif
  3138. // The stream holds the socket while it waits for the head, out of the reach
  3139. // of shutdown()
  3140. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3141. SilentListener listener;
  3142. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3143. Client cli("127.0.0.1", listener.port);
  3144. cli.set_read_timeout(std::chrono::seconds(3));
  3145. expect_stop_ends(
  3146. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3147. Error::Read);
  3148. }
  3149. #ifdef CPPHTTPLIB_SSL_ENABLED
  3150. // A server that never answers the ClientHello
  3151. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3152. SilentListener listener;
  3153. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3154. SSLClient cli("127.0.0.1", listener.port);
  3155. cli.enable_server_certificate_verification(false);
  3156. cli.set_connection_timeout(std::chrono::seconds(3));
  3157. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3158. expect_stop_ends(cli, listener,
  3159. [&] { return cli.open_stream("GET", "/").error; });
  3160. }
  3161. // A proxy that takes the CONNECT and never answers it
  3162. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3163. SilentListener listener;
  3164. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3165. SSLClient cli("example.com", 443);
  3166. cli.set_proxy("127.0.0.1", listener.port);
  3167. cli.set_read_timeout(std::chrono::seconds(3));
  3168. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3169. }
  3170. #endif
  3171. // A read timeout past what the clock reaches waits for the response
  3172. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3173. SilentListener listener;
  3174. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3175. Client cli("127.0.0.1", listener.port);
  3176. cli.set_read_timeout(
  3177. static_cast<time_t>((std::min)(static_cast<long long>(
  3178. (std::numeric_limits<time_t>::max)()),
  3179. 10000000000LL)),
  3180. 0);
  3181. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3182. auto peer = listener.accept();
  3183. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3184. ASSERT_NE(INVALID_SOCKET, peer);
  3185. ASSERT_TRUE(receives_a_byte(peer));
  3186. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3187. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3188. "Connection: close\r\n\r\nok";
  3189. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3190. auto result = res.get();
  3191. ASSERT_TRUE(result);
  3192. EXPECT_EQ("ok", result->body);
  3193. }
  3194. static std::string remove_whitespace(const std::string &input) {
  3195. std::string output;
  3196. output.reserve(input.size());
  3197. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3198. [](unsigned char c) { return !std::isspace(c); });
  3199. return output;
  3200. }
  3201. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3202. auto host = "httpbingo.org";
  3203. auto path = std::string{"/basic-auth/hello/world"};
  3204. #ifdef CPPHTTPLIB_SSL_ENABLED
  3205. auto port = 443;
  3206. SSLClient cli(host, port);
  3207. #else
  3208. auto port = 80;
  3209. Client cli(host, port);
  3210. #endif
  3211. {
  3212. auto res = cli.Get(path);
  3213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3214. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3215. }
  3216. {
  3217. auto res = cli.Get(
  3218. path, Headers{make_basic_authentication_header("hello", "world")});
  3219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3220. auto body = remove_whitespace(res->body);
  3221. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3222. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3223. EXPECT_EQ(StatusCode::OK_200, res->status);
  3224. }
  3225. {
  3226. cli.set_basic_auth("hello", "world");
  3227. auto res = cli.Get(path);
  3228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3229. auto body = remove_whitespace(res->body);
  3230. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3231. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3232. EXPECT_EQ(StatusCode::OK_200, res->status);
  3233. }
  3234. {
  3235. cli.set_basic_auth("hello", "bad");
  3236. auto res = cli.Get(path);
  3237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3238. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3239. }
  3240. {
  3241. cli.set_basic_auth("bad", "world");
  3242. auto res = cli.Get(path);
  3243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3244. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3245. }
  3246. }
  3247. #ifdef CPPHTTPLIB_SSL_ENABLED
  3248. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3249. auto host = "httpbingo.org";
  3250. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3251. auto paths = std::vector<std::string>{
  3252. "/digest-auth/auth/hello/world/MD5",
  3253. "/digest-auth/auth/hello/world/SHA-256",
  3254. };
  3255. auto port = 443;
  3256. SSLClient cli(host, port);
  3257. {
  3258. auto res = cli.Get(unauth_path);
  3259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3260. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3261. }
  3262. {
  3263. cli.set_digest_auth("hello", "world");
  3264. for (const auto &path : paths) {
  3265. auto res = cli.Get(path.c_str());
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. auto body = remove_whitespace(res->body);
  3268. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3269. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. cli.set_digest_auth("hello", "bad");
  3273. for (const auto &path : paths) {
  3274. auto res = cli.Get(path.c_str());
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3277. }
  3278. }
  3279. }
  3280. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3281. // comma-separated list of challenges, and each challenge may itself carry a
  3282. // comma-separated auth-param list, so a server can legally offer Basic
  3283. // before Digest, either as two field lines or packed into one. Runs one 401
  3284. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3285. // value() joins them in receipt order) and checks that the retry carries a
  3286. // well-formed Digest Authorization header naming expected_realm.
  3287. static void
  3288. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3289. const std::string &expected_realm) {
  3290. std::atomic<int> hits{0};
  3291. Server svr;
  3292. svr.Get("/x", [&](const Request &req, Response &res) {
  3293. if (++hits == 1) {
  3294. res.status = StatusCode::Unauthorized_401;
  3295. for (const auto &challenge : challenges) {
  3296. res.set_header("WWW-Authenticate", challenge);
  3297. }
  3298. } else {
  3299. auto authorization = req.get_header_value("Authorization");
  3300. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3301. EXPECT_NE(std::string::npos,
  3302. authorization.find("realm=\"" + expected_realm + "\""));
  3303. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3304. res.set_content("ok", "text/plain");
  3305. }
  3306. });
  3307. auto port = svr.bind_to_any_port(HOST);
  3308. std::thread t([&]() { svr.listen_after_bind(); });
  3309. auto se = detail::scope_exit([&] {
  3310. svr.stop();
  3311. t.join();
  3312. });
  3313. svr.wait_until_ready();
  3314. Client cli(HOST, port);
  3315. cli.set_digest_auth("hello", "world");
  3316. auto res = cli.Get("/x");
  3317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3318. EXPECT_EQ(2, hits.load());
  3319. }
  3320. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3321. static const char *kDigestChallenge =
  3322. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3323. "algorithm=MD5";
  3324. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3325. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3326. "testrealm");
  3327. }
  3328. // Same challenge list with the schemes in the opposite order, to make sure
  3329. // the fix above didn't just special-case "Basic first".
  3330. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3331. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3332. "testrealm");
  3333. }
  3334. // A comma inside a quoted auth-param value must not be mistaken for the
  3335. // separator between two challenges (or two auth-params).
  3336. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3337. run_digest_challenge_list_test(
  3338. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3339. "algorithm=MD5"},
  3340. "test,realm");
  3341. }
  3342. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3343. // the params and leaves out the fragment.
  3344. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3345. Server svr;
  3346. std::string uri, target;
  3347. svr.Get("/a b", [&](const Request &req, Response &res) {
  3348. auto auth = req.get_header_value("Authorization");
  3349. if (auth.empty()) {
  3350. res.status = StatusCode::Unauthorized_401;
  3351. res.set_header("WWW-Authenticate",
  3352. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3353. return;
  3354. }
  3355. auto b = auth.find("uri=\"") + 5;
  3356. uri = auth.substr(b, auth.find('"', b) - b);
  3357. target = req.target;
  3358. });
  3359. auto port = svr.bind_to_any_port(HOST);
  3360. std::thread t([&]() { svr.listen_after_bind(); });
  3361. auto se = detail::scope_exit([&] {
  3362. svr.stop();
  3363. t.join();
  3364. });
  3365. svr.wait_until_ready();
  3366. Client cli(HOST, port);
  3367. cli.set_digest_auth("hello", "world");
  3368. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3370. EXPECT_EQ("/a%20b?x=1", target);
  3371. EXPECT_EQ(target, uri);
  3372. }
  3373. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3374. // make_digest_authentication_header() dereferences both unconditionally, so
  3375. // a server sending a challenge missing either one must not be treated as
  3376. // usable -- doing so used to crash the client with std::out_of_range.
  3377. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3378. Server svr;
  3379. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3380. res.status = StatusCode::Unauthorized_401;
  3381. res.set_header("WWW-Authenticate", challenge);
  3382. });
  3383. auto port = svr.bind_to_any_port(HOST);
  3384. std::thread t([&]() { svr.listen_after_bind(); });
  3385. auto se = detail::scope_exit([&] {
  3386. svr.stop();
  3387. t.join();
  3388. });
  3389. svr.wait_until_ready();
  3390. Client cli(HOST, port);
  3391. cli.set_digest_auth("hello", "world");
  3392. auto res = cli.Get("/x");
  3393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3394. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3395. }
  3396. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3397. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3398. }
  3399. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3400. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3401. }
  3402. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3403. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3404. }
  3405. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3406. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3407. // when storing the values, so the header builder has to re-escape them (and
  3408. // keep algorithm a bare token); otherwise the value breaks out of its
  3409. // quoted-string and injects extra auth-params into the client's Authorization.
  3410. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3411. std::atomic<int> hits{0};
  3412. std::string authorization;
  3413. Server svr;
  3414. svr.Get("/x", [&](const Request &req, Response &res) {
  3415. if (++hits == 1) {
  3416. res.status = StatusCode::Unauthorized_401;
  3417. // On the wire the quotes embedded in the values are backslash-escaped.
  3418. res.set_header("WWW-Authenticate",
  3419. "Digest realm=\"testrealm\", "
  3420. "nonce=\"n\\\"; injected=\\\"x\", "
  3421. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3422. } else {
  3423. authorization = req.get_header_value("Authorization");
  3424. res.set_content("ok", "text/plain");
  3425. }
  3426. });
  3427. auto port = svr.bind_to_any_port(HOST);
  3428. std::thread t([&]() { svr.listen_after_bind(); });
  3429. auto se = detail::scope_exit([&] {
  3430. svr.stop();
  3431. t.join();
  3432. });
  3433. svr.wait_until_ready();
  3434. Client cli(HOST, port);
  3435. cli.set_digest_auth("hello", "world");
  3436. auto res = cli.Get("/x");
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(2, hits.load());
  3439. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3440. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3441. // inside its quoted-string rather than starting an "injected" auth-param.
  3442. EXPECT_NE(std::string::npos,
  3443. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3444. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3445. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3446. }
  3447. #endif
  3448. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3449. auto host = "google.com";
  3450. auto another_host = "example.com";
  3451. auto wrong_ip = "0.0.0.0";
  3452. #ifdef CPPHTTPLIB_SSL_ENABLED
  3453. SSLClient cli(host);
  3454. #else
  3455. Client cli(host);
  3456. #endif
  3457. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3458. auto res = cli.Get("/");
  3459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3460. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3461. }
  3462. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3463. auto host = "google.com";
  3464. auto wrong_ip = "0.0.0.0";
  3465. #ifdef CPPHTTPLIB_SSL_ENABLED
  3466. SSLClient cli(host);
  3467. #else
  3468. Client cli(host);
  3469. #endif
  3470. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3471. auto res = cli.Get("/");
  3472. ASSERT_TRUE(!res);
  3473. EXPECT_EQ(Error::Connection, res.error());
  3474. }
  3475. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3476. // A mapped value that is not an IP literal must be resolved. "localhost"
  3477. // resolves from the hosts file, so this test needs no external DNS.
  3478. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3479. auto host = "target.invalid";
  3480. Server svr;
  3481. std::string received_host;
  3482. svr.Get("/hi", [&](const Request &req, Response &res) {
  3483. received_host = req.get_header_value("Host");
  3484. res.set_content("Hello World!", "text/plain");
  3485. });
  3486. auto port = svr.bind_to_any_port(HOST);
  3487. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3488. auto se = detail::scope_exit([&] {
  3489. svr.stop();
  3490. thread.join();
  3491. ASSERT_FALSE(svr.is_running());
  3492. });
  3493. svr.wait_until_ready();
  3494. Client cli(host, port);
  3495. cli.set_direct_hostname_addr_map({{host, HOST}});
  3496. auto res = cli.Get("/hi");
  3497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3498. EXPECT_EQ(StatusCode::OK_200, res->status);
  3499. // The mapping only redirects the connection; the identity stays host_.
  3500. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3501. }
  3502. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3503. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3504. auto host = "target.invalid";
  3505. Server svr;
  3506. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3507. res.set_content("Hello World!", "text/plain");
  3508. });
  3509. auto port = svr.bind_to_any_port("127.0.0.1");
  3510. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3511. auto se = detail::scope_exit([&] {
  3512. svr.stop();
  3513. thread.join();
  3514. ASSERT_FALSE(svr.is_running());
  3515. });
  3516. svr.wait_until_ready();
  3517. Client cli(host, port);
  3518. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3519. auto res = cli.Get("/hi");
  3520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3521. EXPECT_EQ(StatusCode::OK_200, res->status);
  3522. }
  3523. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3524. // An empty mapped value must leave host_ as the connection target. Without
  3525. // that guard the empty value would become the host argument, getaddrinfo
  3526. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3527. // loopback - silently connecting somewhere the caller never asked for.
  3528. // The server listens on loopback, so such a fallback would succeed and is
  3529. // therefore observable as a failure of this test.
  3530. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3531. Server svr;
  3532. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3533. res.set_content("Hello World!", "text/plain");
  3534. });
  3535. auto port = svr.bind_to_any_port(HOST);
  3536. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(blackhole, port);
  3544. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3545. cli.set_connection_timeout(1);
  3546. auto res = cli.Get("/hi");
  3547. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3548. }
  3549. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3550. auto host = "target.invalid";
  3551. Server svr;
  3552. std::string received_host;
  3553. svr.Get("/hi", [&](const Request &req, Response &res) {
  3554. received_host = req.get_header_value("Host");
  3555. res.set_content("Hello World!", "text/plain");
  3556. });
  3557. auto port = svr.bind_to_any_port("127.0.0.1");
  3558. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3559. auto se = detail::scope_exit([&] {
  3560. svr.stop();
  3561. thread.join();
  3562. ASSERT_FALSE(svr.is_running());
  3563. });
  3564. svr.wait_until_ready();
  3565. Client cli(host, port);
  3566. #pragma GCC diagnostic push
  3567. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3568. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3569. #pragma GCC diagnostic pop
  3570. auto res = cli.Get("/hi");
  3571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3572. EXPECT_EQ(StatusCode::OK_200, res->status);
  3573. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3574. }
  3575. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3576. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3577. Server svr;
  3578. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3579. res.set_content("Hello World!", "text/plain");
  3580. });
  3581. auto port = svr.bind_to_any_port("127.0.0.1");
  3582. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3583. auto se = detail::scope_exit([&] {
  3584. svr.stop();
  3585. thread.join();
  3586. ASSERT_FALSE(svr.is_running());
  3587. });
  3588. svr.wait_until_ready();
  3589. Client cli("127.0.0.1", port);
  3590. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3591. cli.set_connection_timeout(1);
  3592. auto res = cli.Get("/hi");
  3593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3594. EXPECT_EQ(StatusCode::OK_200, res->status);
  3595. }
  3596. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3597. auto host = "httpbingo.org";
  3598. auto path = std::string{"/absolute-redirect/3"};
  3599. #ifdef CPPHTTPLIB_SSL_ENABLED
  3600. SSLClient cli(host);
  3601. #else
  3602. Client cli(host);
  3603. #endif
  3604. cli.set_follow_location(true);
  3605. auto res = cli.Get(path);
  3606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3607. EXPECT_EQ(StatusCode::OK_200, res->status);
  3608. }
  3609. TEST(RedirectTest, Redirect_Online) {
  3610. auto host = "httpbingo.org";
  3611. auto path = std::string{"/redirect/3"};
  3612. #ifdef CPPHTTPLIB_SSL_ENABLED
  3613. SSLClient cli(host);
  3614. #else
  3615. Client cli(host);
  3616. #endif
  3617. cli.set_follow_location(true);
  3618. auto res = cli.Get(path);
  3619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3620. EXPECT_EQ(StatusCode::OK_200, res->status);
  3621. }
  3622. TEST(RelativeRedirectTest, Redirect_Online) {
  3623. auto host = "httpbingo.org";
  3624. auto path = std::string{"/relative-redirect/3"};
  3625. #ifdef CPPHTTPLIB_SSL_ENABLED
  3626. SSLClient cli(host);
  3627. #else
  3628. Client cli(host);
  3629. #endif
  3630. cli.set_follow_location(true);
  3631. auto res = cli.Get(path);
  3632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. }
  3635. TEST(TooManyRedirectTest, Redirect_Online) {
  3636. auto host = "httpbingo.org";
  3637. auto path = std::string{"/redirect/21"};
  3638. #ifdef CPPHTTPLIB_SSL_ENABLED
  3639. SSLClient cli(host);
  3640. #else
  3641. Client cli(host);
  3642. #endif
  3643. cli.set_follow_location(true);
  3644. auto res = cli.Get(path);
  3645. ASSERT_TRUE(!res);
  3646. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3647. }
  3648. #ifdef CPPHTTPLIB_SSL_ENABLED
  3649. TEST(YahooRedirectTest, Redirect_Online) {
  3650. Client cli("yahoo.com");
  3651. auto res = cli.Get("/");
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3654. cli.set_follow_location(true);
  3655. res = cli.Get("/");
  3656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3657. EXPECT_EQ(StatusCode::OK_200, res->status);
  3658. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3659. }
  3660. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3661. #define REDIR_HOST "httpbingo.org"
  3662. #define REDIR_PATH "/redirect-to"
  3663. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3664. SSLClient cli(REDIR_HOST);
  3665. cli.set_follow_location(true);
  3666. auto res =
  3667. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3669. EXPECT_EQ(StatusCode::OK_200, res->status);
  3670. }
  3671. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3672. SSLClient cli(REDIR_HOST);
  3673. cli.set_follow_location(true);
  3674. Params params;
  3675. params.emplace("url", "http://example.com");
  3676. params.emplace("status_code", "302");
  3677. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. }
  3681. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3682. SSLClient cli(REDIR_HOST);
  3683. cli.set_follow_location(true);
  3684. Params params;
  3685. params.emplace("url", "http://example.com");
  3686. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3688. EXPECT_EQ(StatusCode::OK_200, res->status);
  3689. }
  3690. TEST(UrlWithSpace, Redirect_Online) {
  3691. SSLClient cli("edge.forgecdn.net");
  3692. cli.set_follow_location(true);
  3693. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3695. EXPECT_EQ(StatusCode::OK_200, res->status);
  3696. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3697. }
  3698. #endif
  3699. #if !defined(_WIN32) && !defined(_WIN64)
  3700. TEST(ReceiveSignals, Signal) {
  3701. auto setupSignalHandlers = []() {
  3702. struct sigaction act;
  3703. sigemptyset(&act.sa_mask);
  3704. act.sa_flags = SA_SIGINFO;
  3705. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3706. switch (sig) {
  3707. case SIGINT:
  3708. default: break;
  3709. }
  3710. };
  3711. ::sigaction(SIGINT, &act, nullptr);
  3712. };
  3713. Server svr;
  3714. int port = 0;
  3715. auto thread = std::thread([&]() {
  3716. setupSignalHandlers();
  3717. port = svr.bind_to_any_port(HOST);
  3718. svr.listen_after_bind();
  3719. });
  3720. auto se = detail::scope_exit([&] {
  3721. svr.stop();
  3722. thread.join();
  3723. ASSERT_FALSE(svr.is_running());
  3724. });
  3725. svr.wait_until_ready();
  3726. ASSERT_TRUE(svr.is_running());
  3727. pthread_kill(thread.native_handle(), SIGINT);
  3728. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3729. ASSERT_TRUE(svr.is_running());
  3730. }
  3731. #endif
  3732. TEST(RedirectToDifferentPort, Redirect) {
  3733. Server svr1;
  3734. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3735. res.set_content("Hello World!", "text/plain");
  3736. });
  3737. int svr1_port = 0;
  3738. auto thread1 = std::thread([&]() {
  3739. svr1_port = svr1.bind_to_any_port(HOST);
  3740. svr1.listen_after_bind();
  3741. });
  3742. Server svr2;
  3743. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3744. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3745. });
  3746. int svr2_port = 0;
  3747. auto thread2 = std::thread([&]() {
  3748. svr2_port = svr2.bind_to_any_port(HOST);
  3749. svr2.listen_after_bind();
  3750. });
  3751. auto se = detail::scope_exit([&] {
  3752. svr2.stop();
  3753. thread2.join();
  3754. svr1.stop();
  3755. thread1.join();
  3756. ASSERT_FALSE(svr2.is_running());
  3757. ASSERT_FALSE(svr1.is_running());
  3758. });
  3759. svr1.wait_until_ready();
  3760. svr2.wait_until_ready();
  3761. Client cli("localhost", svr2_port);
  3762. cli.set_follow_location(true);
  3763. auto res = cli.Get("/2");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ(StatusCode::OK_200, res->status);
  3766. EXPECT_EQ("Hello World!", res->body);
  3767. }
  3768. // GET /redir on one server redirects to /target on another port, so the
  3769. // client follows it with a new client.
  3770. static Result
  3771. GetThroughRedirectToDifferentPort(Server::Handler target,
  3772. const std::function<void(Client &)> &setup,
  3773. const Headers &headers = Headers()) {
  3774. Server target_svr;
  3775. target_svr.Get("/target", target);
  3776. int target_port = 0;
  3777. auto target_thread = std::thread([&]() {
  3778. target_port = target_svr.bind_to_any_port(HOST);
  3779. target_svr.listen_after_bind();
  3780. });
  3781. Server origin_svr;
  3782. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3783. res.set_redirect(
  3784. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3785. });
  3786. int origin_port = 0;
  3787. auto origin_thread = std::thread([&]() {
  3788. origin_port = origin_svr.bind_to_any_port(HOST);
  3789. origin_svr.listen_after_bind();
  3790. });
  3791. auto se = detail::scope_exit([&] {
  3792. origin_svr.stop();
  3793. origin_thread.join();
  3794. target_svr.stop();
  3795. target_thread.join();
  3796. });
  3797. target_svr.wait_until_ready();
  3798. origin_svr.wait_until_ready();
  3799. Client cli("localhost", origin_port);
  3800. cli.set_follow_location(true);
  3801. setup(cli);
  3802. return cli.Get("/redir", headers);
  3803. }
  3804. static void
  3805. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3806. std::string captured_authorization;
  3807. auto result = GetThroughRedirectToDifferentPort(
  3808. [&](const Request &req, Response &res) {
  3809. captured_authorization = req.get_header_value("Authorization");
  3810. res.set_content("OK", "text/plain");
  3811. },
  3812. set_auth);
  3813. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3814. EXPECT_EQ(StatusCode::OK_200, result->status);
  3815. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3816. EXPECT_TRUE(captured_authorization.empty());
  3817. }
  3818. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3819. TestDoNotForwardCredentialsOnRedirect(
  3820. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3821. }
  3822. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3823. TestDoNotForwardCredentialsOnRedirect(
  3824. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3825. }
  3826. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3827. std::string captured_cookie;
  3828. auto result = GetThroughRedirectToDifferentPort(
  3829. [&](const Request &req, Response &res) {
  3830. captured_cookie = req.get_header_value("Cookie");
  3831. res.set_content("OK", "text/plain");
  3832. },
  3833. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3834. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3835. EXPECT_EQ(StatusCode::OK_200, result->status);
  3836. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3837. EXPECT_TRUE(captured_cookie.empty());
  3838. }
  3839. TEST(RedirectToSamePort, ForwardCookie) {
  3840. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3841. // header so that ordinary session flows keep working.
  3842. Server svr;
  3843. std::string captured_cookie;
  3844. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3845. res.set_redirect("/target", 302);
  3846. });
  3847. svr.Get("/target", [&](const Request &req, Response &res) {
  3848. captured_cookie = req.get_header_value("Cookie");
  3849. res.set_content("OK", "text/plain");
  3850. });
  3851. auto port = svr.bind_to_any_port(HOST);
  3852. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3853. auto se = detail::scope_exit([&] {
  3854. svr.stop();
  3855. thread.join();
  3856. ASSERT_FALSE(svr.is_running());
  3857. });
  3858. svr.wait_until_ready();
  3859. Client cli(HOST, port);
  3860. cli.set_follow_location(true);
  3861. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3862. auto res = cli.Get("/redir", headers);
  3863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3866. }
  3867. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3868. // The Location alone names the next target, on any origin.
  3869. Server target_svr;
  3870. std::string cross_target;
  3871. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3872. cross_target = req.target;
  3873. res.set_content("OK", "text/plain");
  3874. });
  3875. auto target_port = target_svr.bind_to_any_port(HOST);
  3876. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3877. Server origin_svr;
  3878. std::string same_target;
  3879. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3880. res.set_redirect(
  3881. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3882. });
  3883. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3884. res.set_redirect("/landing", 302);
  3885. });
  3886. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3887. same_target = req.target;
  3888. res.set_content("OK", "text/plain");
  3889. });
  3890. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3891. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3892. auto se = detail::scope_exit([&] {
  3893. origin_svr.stop();
  3894. origin_thread.join();
  3895. target_svr.stop();
  3896. target_thread.join();
  3897. });
  3898. target_svr.wait_until_ready();
  3899. origin_svr.wait_until_ready();
  3900. Client cli("localhost", origin_port);
  3901. cli.set_follow_location(true);
  3902. Request req;
  3903. req.method = "GET";
  3904. req.params = {{"api_key", "SECRET"}};
  3905. req.path = "/cross";
  3906. auto res = cli.send(req);
  3907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3908. EXPECT_EQ("/landing", cross_target);
  3909. req.path = "/same";
  3910. res = cli.send(req);
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ("/landing", same_target);
  3913. }
  3914. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3915. std::string authorization;
  3916. std::string trace_id;
  3917. auto result = GetThroughRedirectToDifferentPort(
  3918. [&](const Request &req, Response &res) {
  3919. authorization = req.get_header_value("Authorization");
  3920. trace_id = req.get_header_value("X-Trace-Id");
  3921. res.set_content("OK", "text/plain");
  3922. },
  3923. [](Client &cli) {
  3924. cli.set_default_headers(
  3925. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3926. });
  3927. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3928. EXPECT_EQ(StatusCode::OK_200, result->status);
  3929. // Like a header given with the request, a default one goes along unless it
  3930. // carries credentials (RFC 9110 15.4).
  3931. EXPECT_TRUE(authorization.empty());
  3932. EXPECT_EQ("42", trace_id);
  3933. }
  3934. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3935. auto result = GetThroughRedirectToDifferentPort(
  3936. [](const Request &, Response &res) {
  3937. res.set_content(std::string(2048, 'x'), "text/plain");
  3938. },
  3939. [](Client &cli) { cli.set_payload_max_length(1024); });
  3940. EXPECT_FALSE(result);
  3941. }
  3942. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3943. auto result = GetThroughRedirectToDifferentPort(
  3944. [](const Request &req, Response &res) {
  3945. // Answer after a second, or once the client gives up.
  3946. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3947. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3948. }
  3949. res.set_content("late", "text/plain");
  3950. },
  3951. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3952. ASSERT_FALSE(result);
  3953. EXPECT_EQ(Error::Read, result.error());
  3954. }
  3955. #ifdef CPPHTTPLIB_SSL_ENABLED
  3956. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3957. auto result = GetThroughRedirectToDifferentPort(
  3958. [](const Request &, Response &res) {
  3959. res.status = StatusCode::Unauthorized_401;
  3960. res.set_header("WWW-Authenticate",
  3961. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3962. },
  3963. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3964. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3965. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3966. }
  3967. #endif
  3968. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3969. Server svr;
  3970. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3971. // Port number that overflows int — should not crash
  3972. res.set_redirect("http://localhost:99999999999999999999/target");
  3973. });
  3974. auto port = svr.bind_to_any_port(HOST);
  3975. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3976. auto se = detail::scope_exit([&] {
  3977. svr.stop();
  3978. thread.join();
  3979. ASSERT_FALSE(svr.is_running());
  3980. });
  3981. svr.wait_until_ready();
  3982. Client cli(HOST, port);
  3983. cli.set_follow_location(true);
  3984. auto res = cli.Get("/redir");
  3985. // Should fail gracefully, not crash (no valid response due to bad port)
  3986. EXPECT_FALSE(res);
  3987. }
  3988. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3989. Server svr;
  3990. auto port = svr.bind_to_any_port(HOST);
  3991. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3992. // The server's own port followed by junk must not be followed
  3993. res.set_redirect("http://" + std::string(HOST) + ":" +
  3994. std::to_string(port) + "junk/target");
  3995. });
  3996. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3997. res.set_content("target", "text/plain");
  3998. });
  3999. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4000. auto se = detail::scope_exit([&] {
  4001. svr.stop();
  4002. thread.join();
  4003. ASSERT_FALSE(svr.is_running());
  4004. });
  4005. svr.wait_until_ready();
  4006. Client cli(HOST, port);
  4007. cli.set_follow_location(true);
  4008. auto res = cli.Get("/redir");
  4009. EXPECT_FALSE(res);
  4010. }
  4011. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4012. Server svr;
  4013. std::atomic<bool> followed{false};
  4014. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4015. res.status = StatusCode::NotModified_304;
  4016. res.set_header("Location", "/target");
  4017. });
  4018. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4019. res.status = StatusCode::UseProxy_305;
  4020. res.set_header("Location", "/target");
  4021. });
  4022. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4023. followed = true;
  4024. res.set_content("target", "text/plain");
  4025. });
  4026. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4027. auto se = detail::scope_exit([&] {
  4028. svr.stop();
  4029. th.join();
  4030. ASSERT_FALSE(svr.is_running());
  4031. });
  4032. svr.wait_until_ready();
  4033. Client cli("localhost", PORT);
  4034. cli.set_follow_location(true);
  4035. auto res = cli.Get("/304");
  4036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4037. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4038. res = cli.Get("/305");
  4039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4040. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4041. EXPECT_FALSE(followed);
  4042. }
  4043. TEST(RedirectFromPageWithContent, Redirect) {
  4044. Server svr;
  4045. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4046. res.set_content("___", "text/plain");
  4047. res.set_redirect("/2");
  4048. });
  4049. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4050. res.set_content("Hello World!", "text/plain");
  4051. });
  4052. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4053. auto se = detail::scope_exit([&] {
  4054. svr.stop();
  4055. th.join();
  4056. ASSERT_FALSE(svr.is_running());
  4057. });
  4058. svr.wait_until_ready();
  4059. {
  4060. Client cli("localhost", PORT);
  4061. cli.set_follow_location(true);
  4062. std::string body;
  4063. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4064. body.append(data, data_length);
  4065. return true;
  4066. });
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::OK_200, res->status);
  4069. EXPECT_EQ("Hello World!", body);
  4070. }
  4071. {
  4072. Client cli("localhost", PORT);
  4073. std::string body;
  4074. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4075. body.append(data, data_length);
  4076. return true;
  4077. });
  4078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4079. EXPECT_EQ(StatusCode::Found_302, res->status);
  4080. EXPECT_EQ("___", body);
  4081. }
  4082. }
  4083. // A server can close the connection after a request with "Connection: close"
  4084. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4085. // redirected request must go out on a new connection.
  4086. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4087. #ifndef _WIN32
  4088. signal(SIGPIPE, SIG_IGN);
  4089. #endif
  4090. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4091. default_socket_options(srv);
  4092. sockaddr_in addr{};
  4093. addr.sin_family = AF_INET;
  4094. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4095. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4096. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4097. ASSERT_EQ(0, ::listen(srv, 2));
  4098. auto send_text = [](socket_t sock, const std::string &text) {
  4099. ::send(sock,
  4100. #ifdef _WIN32
  4101. static_cast<const char *>(text.c_str()),
  4102. static_cast<int>(text.size()),
  4103. #else
  4104. text.c_str(), text.size(),
  4105. #endif
  4106. 0);
  4107. };
  4108. auto reused = false;
  4109. auto server_thread = std::thread([&] {
  4110. char buf[4096];
  4111. auto first = ::accept(srv, nullptr, nullptr);
  4112. if (first == INVALID_SOCKET) { return; }
  4113. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4114. ::recv(first, buf, sizeof(buf), 0);
  4115. send_text(
  4116. first,
  4117. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4118. auto next = first;
  4119. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4120. reused = true;
  4121. } else {
  4122. detail::close_socket(first);
  4123. next = ::accept(srv, nullptr, nullptr);
  4124. if (next == INVALID_SOCKET) { return; }
  4125. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4126. ::recv(next, buf, sizeof(buf), 0);
  4127. }
  4128. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4129. "Connection: close\r\n\r\nok");
  4130. detail::close_socket(next);
  4131. });
  4132. Client cli("127.0.0.1", PORT + 2);
  4133. cli.set_follow_location(true);
  4134. cli.set_read_timeout(5, 0);
  4135. auto res = cli.Get("/1");
  4136. server_thread.join();
  4137. detail::close_socket(srv);
  4138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4139. EXPECT_EQ(StatusCode::OK_200, res->status);
  4140. EXPECT_EQ("ok", res->body);
  4141. EXPECT_FALSE(reused);
  4142. }
  4143. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4144. Server svr;
  4145. auto port_str = std::to_string(PORT);
  4146. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4147. auto expected_host = "[::1]:" + port_str;
  4148. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4149. res.set_content("___", "text/plain");
  4150. // res.set_redirect("/2");
  4151. res.set_redirect(redirect_url);
  4152. });
  4153. svr.Get("/2", [&](const Request &req, Response &res) {
  4154. auto host_header = req.headers.find("Host");
  4155. ASSERT_TRUE(host_header != req.headers.end());
  4156. EXPECT_EQ(expected_host, host_header->second);
  4157. res.set_content("Hello World!", "text/plain");
  4158. });
  4159. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4160. auto se = detail::scope_exit([&] {
  4161. svr.stop();
  4162. th.join();
  4163. ASSERT_FALSE(svr.is_running());
  4164. });
  4165. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4166. // actually starts anything, so the condition !svr.is_running() will
  4167. // always remain true, and the loop never stops.
  4168. // This basically counts how many milliseconds have passed since the
  4169. // call to svr.listen(), and if after 5 seconds nothing started yet
  4170. // aborts the test.
  4171. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4172. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4173. ASSERT_LT(milliseconds, 5000U);
  4174. }
  4175. {
  4176. Client cli("::1", PORT);
  4177. cli.set_follow_location(true);
  4178. std::string body;
  4179. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4180. body.append(data, data_length);
  4181. return true;
  4182. });
  4183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4184. EXPECT_EQ(StatusCode::OK_200, res->status);
  4185. EXPECT_EQ("Hello World!", body);
  4186. }
  4187. {
  4188. Client cli("::1", PORT);
  4189. std::string body;
  4190. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4191. body.append(data, data_length);
  4192. return true;
  4193. });
  4194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4195. EXPECT_EQ(StatusCode::Found_302, res->status);
  4196. EXPECT_EQ("___", body);
  4197. }
  4198. }
  4199. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4200. Server svr;
  4201. svr.Get("/foo", [](const Request &req, Response &res) {
  4202. auto a = req.params.find("a");
  4203. if (a != req.params.end()) {
  4204. res.set_content((*a).second, "text/plain");
  4205. res.status = StatusCode::OK_200;
  4206. } else {
  4207. res.status = StatusCode::BadRequest_400;
  4208. }
  4209. });
  4210. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4211. auto se = detail::scope_exit([&] {
  4212. svr.stop();
  4213. thread.join();
  4214. ASSERT_FALSE(svr.is_running());
  4215. });
  4216. svr.wait_until_ready();
  4217. {
  4218. Client cli(HOST, PORT);
  4219. cli.set_path_encode(false);
  4220. auto res = cli.Get("/foo?a=explicitly+encoded");
  4221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4222. EXPECT_EQ(StatusCode::OK_200, res->status);
  4223. // This expects it back with a space, as the `+` won't have been
  4224. // url-encoded, and server-side the params get decoded turning `+`
  4225. // into spaces.
  4226. EXPECT_EQ("explicitly encoded", res->body);
  4227. }
  4228. }
  4229. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4230. // When path encoding is disabled the client must transmit the supplied
  4231. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4232. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4233. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4234. // than a space (0x20). Assert on the raw wire target to catch this.
  4235. Server svr;
  4236. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4237. svr.Get("/foo", [&](const Request &req, Response &res) {
  4238. EXPECT_EQ(expected_target, req.target);
  4239. res.status = StatusCode::OK_200;
  4240. });
  4241. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4242. auto se = detail::scope_exit([&] {
  4243. svr.stop();
  4244. thread.join();
  4245. ASSERT_FALSE(svr.is_running());
  4246. });
  4247. svr.wait_until_ready();
  4248. {
  4249. Client cli(HOST, PORT);
  4250. cli.set_path_encode(false);
  4251. auto res = cli.Get(expected_target.c_str());
  4252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4253. EXPECT_EQ(StatusCode::OK_200, res->status);
  4254. }
  4255. }
  4256. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4257. // `open_stream()` used to skip the path encoding that the buffered send
  4258. // path applies, so the same `path` produced different bytes in the request
  4259. // line depending on which API was used. Assert the two agree.
  4260. Server svr;
  4261. std::string target;
  4262. svr.Get(".*", [&](const Request &req, Response &res) {
  4263. target = req.target;
  4264. res.status = StatusCode::OK_200;
  4265. });
  4266. auto port = svr.bind_to_any_port(HOST);
  4267. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4268. auto se = detail::scope_exit([&] {
  4269. svr.stop();
  4270. thread.join();
  4271. ASSERT_FALSE(svr.is_running());
  4272. });
  4273. svr.wait_until_ready();
  4274. struct {
  4275. const char *path;
  4276. const char *expected;
  4277. } cases[] = {
  4278. {"/a b?x=1", "/a%20b?x=1"},
  4279. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4280. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4281. };
  4282. for (const auto &c : cases) {
  4283. Client cli(HOST, port);
  4284. target.clear();
  4285. auto res = cli.Get(c.path);
  4286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4287. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4288. auto buffered_target = target;
  4289. target.clear();
  4290. auto handle = cli.open_stream("GET", c.path);
  4291. EXPECT_TRUE(handle.is_valid())
  4292. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4293. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4294. }
  4295. }
  4296. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4297. // The `set_path_encode(false)` contract — transmit the supplied target
  4298. // verbatim — must hold for the streaming API too.
  4299. Server svr;
  4300. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4301. std::string target;
  4302. svr.Get("/foo", [&](const Request &req, Response &res) {
  4303. target = req.target;
  4304. res.status = StatusCode::OK_200;
  4305. });
  4306. auto port = svr.bind_to_any_port(HOST);
  4307. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4308. auto se = detail::scope_exit([&] {
  4309. svr.stop();
  4310. thread.join();
  4311. ASSERT_FALSE(svr.is_running());
  4312. });
  4313. svr.wait_until_ready();
  4314. {
  4315. Client cli(HOST, port);
  4316. cli.set_path_encode(false);
  4317. auto handle = cli.open_stream("GET", expected_target);
  4318. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4319. EXPECT_EQ(expected_target, target);
  4320. }
  4321. }
  4322. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4323. // With path encoding enabled a CR/LF in the target is percent-encoded
  4324. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4325. // write_request_line still backstops `set_path_encode(false)`, which is
  4326. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4327. Server svr;
  4328. // Captured before routing: the decoded path contains a newline, which a
  4329. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4330. std::string target;
  4331. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4332. target = req.target;
  4333. res.status = StatusCode::OK_200;
  4334. return Server::HandlerResponse::Handled;
  4335. });
  4336. auto port = svr.bind_to_any_port(HOST);
  4337. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4338. auto se = detail::scope_exit([&] {
  4339. svr.stop();
  4340. thread.join();
  4341. ASSERT_FALSE(svr.is_running());
  4342. });
  4343. svr.wait_until_ready();
  4344. {
  4345. Client cli(HOST, port);
  4346. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4347. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4348. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4349. }
  4350. }
  4351. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4352. // Every control character is percent-encoded, not just CR/LF, so the target
  4353. // passes the request-target check in write_request_line.
  4354. Server svr;
  4355. std::string target;
  4356. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4357. target = req.target;
  4358. res.status = StatusCode::OK_200;
  4359. return Server::HandlerResponse::Handled;
  4360. });
  4361. auto port = svr.bind_to_any_port(HOST);
  4362. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4363. auto se = detail::scope_exit([&] {
  4364. svr.stop();
  4365. thread.join();
  4366. ASSERT_FALSE(svr.is_running());
  4367. });
  4368. svr.wait_until_ready();
  4369. {
  4370. Client cli(HOST, port);
  4371. auto res = cli.Get("/a\tb\x1b\x7f");
  4372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4373. EXPECT_EQ("/a%09b%1B%7F", target);
  4374. }
  4375. }
  4376. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4377. // Nothing may reach the wire: a raw CR/LF target would split the request
  4378. // line and inject headers.
  4379. Server svr;
  4380. // Pre-routing so that "not called" means nothing reached the server at all,
  4381. // rather than merely failing to match a handler pattern.
  4382. auto handler_called = false;
  4383. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4384. handler_called = true;
  4385. res.status = StatusCode::OK_200;
  4386. return Server::HandlerResponse::Handled;
  4387. });
  4388. auto port = svr.bind_to_any_port(HOST);
  4389. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4390. auto se = detail::scope_exit([&] {
  4391. svr.stop();
  4392. thread.join();
  4393. ASSERT_FALSE(svr.is_running());
  4394. });
  4395. svr.wait_until_ready();
  4396. {
  4397. Client cli(HOST, port);
  4398. cli.set_path_encode(false);
  4399. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4400. EXPECT_FALSE(handle.is_valid());
  4401. EXPECT_EQ(Error::Write, handle.error);
  4402. EXPECT_FALSE(handler_called);
  4403. }
  4404. }
  4405. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4406. // Which of the two branches runs is decided by whether the query component
  4407. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4408. // an empty query and must still fall back to building one from
  4409. // `req.params`, while a non-empty query must win over `req.params`.
  4410. Server svr;
  4411. std::string target;
  4412. svr.Get("/foo", [&](const Request &req, Response &res) {
  4413. target = req.target;
  4414. res.status = StatusCode::OK_200;
  4415. });
  4416. auto port = svr.bind_to_any_port(HOST);
  4417. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4418. auto se = detail::scope_exit([&] {
  4419. svr.stop();
  4420. thread.join();
  4421. ASSERT_FALSE(svr.is_running());
  4422. });
  4423. svr.wait_until_ready();
  4424. {
  4425. // Trailing `?` -> empty query component -> `req.params` is used.
  4426. Client cli(HOST, port);
  4427. Request req;
  4428. req.method = "GET";
  4429. req.path = "/foo?";
  4430. req.params.emplace("a", "1");
  4431. target.clear();
  4432. auto res = cli.send(req);
  4433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4434. EXPECT_EQ("/foo?a=1", target);
  4435. }
  4436. {
  4437. // Non-empty query in `req.path` -> `req.params` is not appended.
  4438. Client cli(HOST, port);
  4439. Request req;
  4440. req.method = "GET";
  4441. req.path = "/foo?b=2";
  4442. req.params.emplace("a", "1");
  4443. target.clear();
  4444. auto res = cli.send(req);
  4445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4446. EXPECT_EQ("/foo?b=2", target);
  4447. }
  4448. }
  4449. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4450. Server svr;
  4451. svr.Get("/", [](const Request &req, Response &) {
  4452. EXPECT_EQ("\x0A", req.get_param_value("something"));
  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. cli.set_path_encode(false);
  4464. auto res = cli.Get("/?something=%0A");
  4465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4466. EXPECT_EQ(StatusCode::OK_200, res->status);
  4467. }
  4468. }
  4469. TEST(BindServerTest, BindDualStack) {
  4470. Server svr;
  4471. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4472. res.set_content("Hello World!", "text/plain");
  4473. });
  4474. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4475. auto se = detail::scope_exit([&] {
  4476. svr.stop();
  4477. thread.join();
  4478. ASSERT_FALSE(svr.is_running());
  4479. });
  4480. svr.wait_until_ready();
  4481. {
  4482. Client cli("127.0.0.1", PORT);
  4483. auto res = cli.Get("/1");
  4484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4485. EXPECT_EQ(StatusCode::OK_200, res->status);
  4486. EXPECT_EQ("Hello World!", res->body);
  4487. }
  4488. {
  4489. Client cli("::1", PORT);
  4490. auto res = cli.Get("/1");
  4491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4492. EXPECT_EQ(StatusCode::OK_200, res->status);
  4493. EXPECT_EQ("Hello World!", res->body);
  4494. }
  4495. }
  4496. TEST(BindServerTest, BindAndListenSeparately) {
  4497. Server svr;
  4498. int port = svr.bind_to_any_port("0.0.0.0");
  4499. ASSERT_TRUE(svr.is_valid());
  4500. ASSERT_TRUE(port > 0);
  4501. svr.stop();
  4502. }
  4503. // Reports whether anything is still listening on a loopback port. A plain
  4504. // connect() is used instead of a Client request because a socket left bound by
  4505. // mistake accepts the connection into its backlog and never answers, which
  4506. // would hang the test instead of failing it.
  4507. static bool is_loopback_port_accepting(int port) {
  4508. sockaddr_in addr{};
  4509. addr.sin_family = AF_INET;
  4510. addr.sin_port = htons(static_cast<uint16_t>(port));
  4511. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4512. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4513. EXPECT_NE(sock, INVALID_SOCKET);
  4514. if (sock == INVALID_SOCKET) { return false; }
  4515. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4516. static_cast<socklen_t>(sizeof(addr)));
  4517. detail::close_socket(sock);
  4518. return ret == 0;
  4519. }
  4520. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4521. Server svr;
  4522. auto port = svr.bind_to_any_port("127.0.0.1");
  4523. ASSERT_TRUE(port > 0);
  4524. svr.stop();
  4525. // bind_to_any_port() already called listen(2), so until stop() closed the
  4526. // descriptor the port kept accepting connections into the backlog. ASSERT
  4527. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4528. // below blocks forever in the accept loop.
  4529. ASSERT_FALSE(is_loopback_port_accepting(port));
  4530. // Nothing is left to accept on, so listen_after_bind() must report failure
  4531. // instead of returning success without ever serving.
  4532. EXPECT_FALSE(svr.listen_after_bind());
  4533. // The failed listen marks the server decommissioned, so a waiter returns
  4534. // instead of spinning forever.
  4535. svr.wait_until_ready();
  4536. }
  4537. #ifdef CPPHTTPLIB_SSL_ENABLED
  4538. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4539. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4540. CLIENT_CA_CERT_DIR);
  4541. int port = svr.bind_to_any_port("0.0.0.0");
  4542. ASSERT_TRUE(svr.is_valid());
  4543. ASSERT_TRUE(port > 0);
  4544. svr.stop();
  4545. }
  4546. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4547. // or a rejected CustomRoute() registration would not stop the server binding.
  4548. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4550. CLIENT_CA_CERT_DIR);
  4551. ASSERT_TRUE(svr.is_valid());
  4552. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4553. EXPECT_FALSE(svr.is_valid());
  4554. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4555. }
  4556. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4557. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4558. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4559. int port = svr.bind_to_any_port("0.0.0.0");
  4560. ASSERT_TRUE(svr.is_valid());
  4561. ASSERT_TRUE(port > 0);
  4562. svr.stop();
  4563. }
  4564. TEST(BindServerTest, UpdateCertsPem) {
  4565. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4566. int port = svr.bind_to_any_port("0.0.0.0");
  4567. ASSERT_TRUE(svr.is_valid());
  4568. ASSERT_TRUE(port > 0);
  4569. // Read PEM files
  4570. std::string cert_pem, key_pem, ca_pem;
  4571. read_file(SERVER_CERT_FILE, cert_pem);
  4572. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4573. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4574. // Update server certificates using PEM API
  4575. ASSERT_TRUE(
  4576. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4577. ASSERT_TRUE(svr.is_valid());
  4578. svr.stop();
  4579. }
  4580. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4581. // Start server with client CA (enables client auth)
  4582. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4583. ASSERT_TRUE(svr.is_valid());
  4584. bool handler_called = false;
  4585. svr.Get("/test", [&](const Request &req, Response &res) {
  4586. handler_called = true;
  4587. // Verify client certificate is present
  4588. auto cert = req.peer_cert();
  4589. EXPECT_TRUE(static_cast<bool>(cert));
  4590. res.set_content("ok", "text/plain");
  4591. });
  4592. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4593. auto se = detail::scope_exit([&] {
  4594. svr.stop();
  4595. t.join();
  4596. ASSERT_FALSE(svr.is_running());
  4597. });
  4598. svr.wait_until_ready();
  4599. // Read PEM files
  4600. std::string cert_pem, key_pem, ca_pem;
  4601. read_file(SERVER_CERT_FILE, cert_pem);
  4602. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4603. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4604. // Update server certificates and client CA using PEM API while server running
  4605. ASSERT_TRUE(
  4606. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4607. // Connect with client certificate
  4608. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4609. cli.enable_server_certificate_verification(false);
  4610. cli.set_connection_timeout(30);
  4611. auto res = cli.Get("/test");
  4612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4613. ASSERT_EQ(StatusCode::OK_200, res->status);
  4614. ASSERT_TRUE(handler_called);
  4615. EXPECT_EQ("ok", res->body);
  4616. }
  4617. // Puts a CA that did not sign the client's certificate in the old one's place.
  4618. static bool replace_client_ca(SSLServer &svr) {
  4619. std::string cert_pem, key_pem, ca_pem;
  4620. read_file(SERVER_CERT_FILE, cert_pem);
  4621. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4622. read_file(SERVER_CERT2_FILE, ca_pem);
  4623. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4624. ca_pem.c_str());
  4625. }
  4626. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4628. ASSERT_TRUE(svr.is_valid());
  4629. svr.Get("/test", [](const Request &, Response &res) {
  4630. res.set_content("ok", "text/plain");
  4631. });
  4632. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4633. auto se = detail::scope_exit([&] {
  4634. svr.stop();
  4635. t.join();
  4636. ASSERT_FALSE(svr.is_running());
  4637. });
  4638. svr.wait_until_ready();
  4639. auto get = [] {
  4640. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4641. cli.enable_server_certificate_verification(false);
  4642. return cli.Get("/test");
  4643. };
  4644. ASSERT_TRUE(get());
  4645. ASSERT_TRUE(replace_client_ca(svr));
  4646. EXPECT_FALSE(get());
  4647. }
  4648. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4649. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4650. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4651. ASSERT_TRUE(svr.is_valid());
  4652. tls::set_verify_callback(svr.tls_context(),
  4653. [](const tls::VerifyContext &) -> bool {
  4654. throw std::runtime_error("verify");
  4655. });
  4656. svr.Get("/test", [](const Request &, Response &res) {
  4657. res.set_content("ok", "text/plain");
  4658. });
  4659. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4660. auto se = detail::scope_exit([&] {
  4661. svr.stop();
  4662. t.join();
  4663. ASSERT_FALSE(svr.is_running());
  4664. });
  4665. svr.wait_until_ready();
  4666. auto get = [] {
  4667. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4668. cli.enable_server_certificate_verification(false);
  4669. return cli.Get("/test");
  4670. };
  4671. EXPECT_FALSE(get());
  4672. // The handshake is over, so an update does not wait for it.
  4673. std::string cert_pem, key_pem;
  4674. read_file(SERVER_CERT_FILE, cert_pem);
  4675. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4676. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4677. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4678. return v.preverify_ok;
  4679. });
  4680. auto res = get();
  4681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4682. EXPECT_EQ("ok", res->body);
  4683. }
  4684. #endif
  4685. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4686. // Sends each request over a new connection with a client certificate,
  4687. // resuming the session of the one before when there is one.
  4688. class ResumingClient {
  4689. public:
  4690. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4691. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4692. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4693. SSL_FILETYPE_PEM);
  4694. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4695. // callback, not through SSL_get1_session().
  4696. SSL_CTX_set_app_data(ctx_, this);
  4697. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4698. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4699. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4700. auto self = static_cast<ResumingClient *>(
  4701. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4702. SSL_SESSION_free(self->session_);
  4703. self->session_ = session;
  4704. return 1; // Keeps the reference
  4705. });
  4706. }
  4707. ~ResumingClient() {
  4708. SSL_SESSION_free(session_);
  4709. SSL_CTX_free(ctx_);
  4710. }
  4711. // Tells whether the request was answered.
  4712. bool get() {
  4713. auto error = Error::Success;
  4714. auto sock = detail::create_client_socket(
  4715. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4716. /*connection_timeout_sec=*/5, 0,
  4717. /*read_timeout_sec=*/5, 0,
  4718. /*write_timeout_sec=*/5, 0, std::string(), error);
  4719. if (sock == INVALID_SOCKET) { return false; }
  4720. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4721. auto ssl = SSL_new(ctx_);
  4722. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4723. SSL_set_fd(ssl, static_cast<int>(sock));
  4724. if (session_) { SSL_set_session(ssl, session_); }
  4725. if (SSL_connect(ssl) != 1) { return false; }
  4726. reused_ = SSL_session_reused(ssl) == 1;
  4727. // Reading the response also takes in a TLS 1.3 session ticket.
  4728. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4729. "Connection: close\r\n\r\n";
  4730. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4731. std::string res;
  4732. char buf[256];
  4733. int n;
  4734. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4735. res.append(buf, static_cast<size_t>(n));
  4736. }
  4737. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4738. SSL_shutdown(ssl);
  4739. return res.find("200 OK") != std::string::npos;
  4740. }
  4741. // Whether the last connection resumed a session
  4742. bool reused() const { return reused_; }
  4743. private:
  4744. SSL_CTX *ctx_;
  4745. SSL_SESSION *session_ = nullptr;
  4746. bool reused_ = false;
  4747. };
  4748. // A client that resumes its session gets through, but not once the client CA
  4749. // has changed, as a resumed session does not show the certificate again.
  4750. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4752. ASSERT_TRUE(svr.is_valid());
  4753. svr.Get("/test", [](const Request &, Response &res) {
  4754. res.set_content("ok", "text/plain");
  4755. });
  4756. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4757. auto se = detail::scope_exit([&] {
  4758. svr.stop();
  4759. t.join();
  4760. ASSERT_FALSE(svr.is_running());
  4761. });
  4762. svr.wait_until_ready();
  4763. ResumingClient cli;
  4764. ASSERT_TRUE(cli.get());
  4765. ASSERT_TRUE(cli.get());
  4766. EXPECT_TRUE(cli.reused());
  4767. ASSERT_TRUE(replace_client_ca(svr));
  4768. EXPECT_FALSE(cli.get());
  4769. }
  4770. // A resumed session does not show the certificate again, so the server does
  4771. // not resume one with a verify callback to run on it.
  4772. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4774. ASSERT_TRUE(svr.is_valid());
  4775. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4776. return v.preverify_ok;
  4777. });
  4778. svr.Get("/test", [](const Request &, Response &res) {
  4779. res.set_content("ok", "text/plain");
  4780. });
  4781. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4782. auto se = detail::scope_exit([&] {
  4783. svr.stop();
  4784. t.join();
  4785. ASSERT_FALSE(svr.is_running());
  4786. });
  4787. svr.wait_until_ready();
  4788. ResumingClient cli;
  4789. ASSERT_TRUE(cli.get());
  4790. ASSERT_TRUE(cli.get());
  4791. EXPECT_FALSE(cli.reused());
  4792. }
  4793. #endif
  4794. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4795. // wolfSSL shares its session cache between contexts, so a resumed session
  4796. // could carry a client certificate checked against another server's CA, or
  4797. // against a client CA since replaced.
  4798. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4800. ASSERT_TRUE(svr.is_valid());
  4801. // Trusts a CA that did not sign the client's certificate.
  4802. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4803. ASSERT_TRUE(other.is_valid());
  4804. for (auto s : {&svr, &other}) {
  4805. s->Get("/test", [](const Request &, Response &res) {
  4806. res.set_content("ok", "text/plain");
  4807. });
  4808. }
  4809. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4810. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4811. auto se = detail::scope_exit([&] {
  4812. other.stop();
  4813. svr.stop();
  4814. t2.join();
  4815. t.join();
  4816. });
  4817. svr.wait_until_ready();
  4818. other.wait_until_ready();
  4819. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4820. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4821. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4822. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4823. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4824. ASSERT_EQ(WOLFSSL_SUCCESS,
  4825. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4826. WOLFSSL_FILETYPE_PEM));
  4827. WOLFSSL_SESSION *session = nullptr;
  4828. auto session_se = detail::scope_exit([&] {
  4829. if (session) { wolfSSL_SESSION_free(session); }
  4830. });
  4831. // A request over a new connection, resuming `session` when there is one and
  4832. // keeping the connection's own in its place. Tells whether it was answered.
  4833. auto get = [&](int port) {
  4834. auto error = Error::Success;
  4835. auto sock = detail::create_client_socket(
  4836. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4837. /*connection_timeout_sec=*/5, 0,
  4838. /*read_timeout_sec=*/5, 0,
  4839. /*write_timeout_sec=*/5, 0, std::string(), error);
  4840. if (sock == INVALID_SOCKET) { return false; }
  4841. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4842. auto ssl = wolfSSL_new(ctx);
  4843. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4844. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4845. if (session) { wolfSSL_set_session(ssl, session); }
  4846. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4847. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4848. "Connection: close\r\n\r\n";
  4849. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4850. std::string res;
  4851. char buf[256];
  4852. int n;
  4853. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4854. res.append(buf, static_cast<size_t>(n));
  4855. }
  4856. wolfSSL_shutdown(ssl);
  4857. if (session) { wolfSSL_SESSION_free(session); }
  4858. session = wolfSSL_get1_session(ssl);
  4859. return res.find("200 OK") != std::string::npos;
  4860. };
  4861. ASSERT_TRUE(get(PORT));
  4862. EXPECT_FALSE(get(PORT + 1));
  4863. ASSERT_TRUE(get(PORT));
  4864. ASSERT_TRUE(replace_client_ca(svr));
  4865. EXPECT_FALSE(get(PORT));
  4866. }
  4867. #endif
  4868. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4870. ASSERT_TRUE(svr.is_valid());
  4871. svr.Get("/test", [](const Request &, Response &res) {
  4872. res.set_content("ok", "text/plain");
  4873. });
  4874. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4875. auto se = detail::scope_exit([&] {
  4876. svr.stop();
  4877. t.join();
  4878. ASSERT_FALSE(svr.is_running());
  4879. });
  4880. svr.wait_until_ready();
  4881. // A connection that sends no ClientHello keeps its handshake in progress,
  4882. // once the server has had a moment to start it.
  4883. auto error = Error::Success;
  4884. auto sock = detail::create_client_socket(
  4885. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4886. /*connection_timeout_sec=*/5, 0,
  4887. /*read_timeout_sec=*/5, 0,
  4888. /*write_timeout_sec=*/5, 0, std::string(), error);
  4889. ASSERT_NE(INVALID_SOCKET, sock);
  4890. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4891. std::string cert_pem, key_pem;
  4892. read_file(SERVER_CERT_FILE, cert_pem);
  4893. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4894. auto update = std::async(std::launch::async, [&]() {
  4895. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4896. });
  4897. EXPECT_EQ(std::future_status::timeout,
  4898. update.wait_for(std::chrono::milliseconds(200)));
  4899. detail::close_socket(sock);
  4900. EXPECT_TRUE(update.get());
  4901. SSLClient cli(HOST, PORT);
  4902. cli.enable_server_certificate_verification(false);
  4903. auto res = cli.Get("/test");
  4904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4905. EXPECT_EQ(StatusCode::OK_200, res->status);
  4906. }
  4907. #endif
  4908. TEST(ErrorHandlerTest, ContentLength) {
  4909. Server svr;
  4910. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4911. res.status = StatusCode::OK_200;
  4912. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4913. "text/html"); // <= Content-Length still 13
  4914. });
  4915. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4916. res.set_content("Hello World!\n", "text/plain");
  4917. res.status = 524;
  4918. });
  4919. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4920. auto se = detail::scope_exit([&] {
  4921. svr.stop();
  4922. thread.join();
  4923. ASSERT_FALSE(svr.is_running());
  4924. });
  4925. svr.wait_until_ready();
  4926. {
  4927. Client cli(HOST, PORT);
  4928. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4930. EXPECT_EQ(StatusCode::OK_200, res->status);
  4931. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4932. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4933. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4934. }
  4935. }
  4936. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4937. TEST(ExceptionTest, WithoutExceptionHandler) {
  4938. Server svr;
  4939. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4940. throw std::runtime_error("exception...");
  4941. });
  4942. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4943. throw std::runtime_error("exception\r\n...");
  4944. });
  4945. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4946. auto se = detail::scope_exit([&] {
  4947. svr.stop();
  4948. listen_thread.join();
  4949. ASSERT_FALSE(svr.is_running());
  4950. });
  4951. svr.wait_until_ready();
  4952. Client cli("localhost", PORT);
  4953. {
  4954. auto res = cli.Get("/exception");
  4955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4956. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4957. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4958. }
  4959. {
  4960. auto res = cli.Get("/unknown");
  4961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4962. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4963. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4964. }
  4965. }
  4966. TEST(ExceptionTest, WithExceptionHandler) {
  4967. Server svr;
  4968. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4969. std::exception_ptr ep) {
  4970. EXPECT_FALSE(ep == nullptr);
  4971. try {
  4972. std::rethrow_exception(ep);
  4973. } catch (std::exception &e) {
  4974. EXPECT_EQ("abc", std::string(e.what()));
  4975. } catch (...) {}
  4976. res.status = StatusCode::InternalServerError_500;
  4977. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4978. "text/html"); // <= Content-Length still 13 at this point
  4979. });
  4980. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4981. res.set_content("Hello World!\n", "text/plain");
  4982. throw std::runtime_error("abc");
  4983. });
  4984. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4985. auto se = detail::scope_exit([&] {
  4986. svr.stop();
  4987. thread.join();
  4988. ASSERT_FALSE(svr.is_running());
  4989. });
  4990. svr.wait_until_ready();
  4991. for (size_t i = 0; i < 10; i++) {
  4992. Client cli(HOST, PORT);
  4993. for (size_t j = 0; j < 100; j++) {
  4994. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4996. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4997. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4998. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4999. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5000. }
  5001. cli.set_keep_alive(true);
  5002. for (size_t j = 0; j < 100; j++) {
  5003. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5005. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5006. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5007. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5008. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5009. }
  5010. }
  5011. }
  5012. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5013. Server svr;
  5014. svr.set_exception_handler(
  5015. [](const Request &, Response &res, std::exception_ptr) {
  5016. res.set_content("oops", "text/plain");
  5017. });
  5018. svr.Get("/throw", [](const Request &, Response &) {
  5019. throw std::runtime_error("throw");
  5020. });
  5021. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5022. res.status = StatusCode::Created_201;
  5023. throw std::runtime_error("created-then-throw");
  5024. });
  5025. auto port = svr.bind_to_any_port(HOST);
  5026. ASSERT_GT(port, 0);
  5027. thread t = thread([&] { svr.listen_after_bind(); });
  5028. auto se = detail::scope_exit([&] {
  5029. svr.stop();
  5030. t.join();
  5031. ASSERT_FALSE(svr.is_running());
  5032. });
  5033. svr.wait_until_ready();
  5034. Client cli(HOST, port);
  5035. for (auto path : {"/throw", "/created-then-throw"}) {
  5036. auto res = cli.Get(path);
  5037. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5038. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5039. }
  5040. }
  5041. TEST(ExceptionTest, AndErrorHandler) {
  5042. Server svr;
  5043. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5044. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5045. });
  5046. svr.set_exception_handler(
  5047. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5048. EXPECT_FALSE(ep == nullptr);
  5049. try {
  5050. std::rethrow_exception(ep);
  5051. } catch (std::exception &e) {
  5052. res.set_content(e.what(), "text/html");
  5053. } catch (...) {}
  5054. res.status = StatusCode::InternalServerError_500;
  5055. });
  5056. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5057. throw std::runtime_error("EXCEPTION");
  5058. });
  5059. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5060. res.set_content("ERROR", "text/html");
  5061. res.status = StatusCode::InternalServerError_500;
  5062. });
  5063. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5064. auto se = detail::scope_exit([&] {
  5065. svr.stop();
  5066. thread.join();
  5067. ASSERT_FALSE(svr.is_running());
  5068. });
  5069. svr.wait_until_ready();
  5070. Client cli(HOST, PORT);
  5071. {
  5072. auto res = cli.Get("/exception");
  5073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5074. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5075. EXPECT_EQ("EXCEPTION", res->body);
  5076. }
  5077. {
  5078. auto res = cli.Get("/error");
  5079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5080. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5081. EXPECT_EQ("ERROR", res->body);
  5082. }
  5083. {
  5084. auto res = cli.Get("/invalid");
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5087. EXPECT_EQ("NOT_FOUND", res->body);
  5088. }
  5089. }
  5090. #endif
  5091. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5092. // An exception from a user callback outside process_request()'s try/catch
  5093. // used to unwind into the task queue - which does not catch - and terminate
  5094. // the process. Each test below runs the server on a single worker thread: a
  5095. // guard that catches the exception but still loses the thread would otherwise
  5096. // be hidden by a spare worker serving the follow-up request. Note that a
  5097. // regression here aborts the whole test binary rather than failing one test.
  5098. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5099. Server svr;
  5100. svr.new_task_queue = [] { return new ThreadPool(1); };
  5101. std::atomic<int> reported{0};
  5102. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5103. if (err == Error::UserCallbackException) { reported++; }
  5104. });
  5105. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5106. res.set_content_provider(
  5107. 1024, "text/plain",
  5108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5109. sink.write("hello", 5);
  5110. throw std::runtime_error("from the content provider");
  5111. });
  5112. });
  5113. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5114. res.set_content("ok", "text/plain");
  5115. });
  5116. auto port = svr.bind_to_any_port(HOST);
  5117. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5118. auto se = detail::scope_exit([&] {
  5119. svr.stop();
  5120. listen_thread.join();
  5121. ASSERT_FALSE(svr.is_running());
  5122. });
  5123. svr.wait_until_ready();
  5124. {
  5125. Client cli(HOST, port);
  5126. cli.set_read_timeout(5, 0);
  5127. EXPECT_FALSE(cli.Get("/throw"));
  5128. }
  5129. EXPECT_TRUE(svr.is_running());
  5130. EXPECT_EQ(1, reported.load());
  5131. // A request on a fresh connection is still served.
  5132. {
  5133. Client cli(HOST, port);
  5134. auto res = cli.Get("/ok");
  5135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5136. EXPECT_EQ(StatusCode::OK_200, res->status);
  5137. EXPECT_EQ("ok", res->body);
  5138. }
  5139. }
  5140. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5141. Server svr;
  5142. svr.new_task_queue = [] { return new ThreadPool(1); };
  5143. std::atomic<bool> should_throw{true};
  5144. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5145. res.set_content("hi", "text/plain");
  5146. });
  5147. svr.set_post_routing_handler(
  5148. [&](const Request & /*req*/, Response & /*res*/) {
  5149. if (should_throw) {
  5150. throw std::runtime_error("from the post-routing handler");
  5151. }
  5152. });
  5153. auto port = svr.bind_to_any_port(HOST);
  5154. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5155. auto se = detail::scope_exit([&] {
  5156. svr.stop();
  5157. listen_thread.join();
  5158. ASSERT_FALSE(svr.is_running());
  5159. });
  5160. svr.wait_until_ready();
  5161. {
  5162. Client cli(HOST, port);
  5163. cli.set_read_timeout(5, 0);
  5164. EXPECT_FALSE(cli.Get("/hi"));
  5165. }
  5166. EXPECT_TRUE(svr.is_running());
  5167. should_throw = false;
  5168. {
  5169. Client cli(HOST, port);
  5170. auto res = cli.Get("/hi");
  5171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5172. EXPECT_EQ(StatusCode::OK_200, res->status);
  5173. EXPECT_EQ("hi", res->body);
  5174. }
  5175. }
  5176. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5177. // The guard reports the caught exception through the error logger, which is
  5178. // a user callback too. A logger that throws has to be contained as well, or
  5179. // the process would terminate from inside the catch.
  5180. Server svr;
  5181. svr.new_task_queue = [] { return new ThreadPool(1); };
  5182. std::atomic<int> reported{0};
  5183. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5184. if (err == Error::UserCallbackException) {
  5185. reported++;
  5186. throw std::runtime_error("from the error logger");
  5187. }
  5188. });
  5189. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5190. res.set_content_provider(
  5191. 1024, "text/plain",
  5192. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5193. sink.write("hello", 5);
  5194. throw std::runtime_error("from the content provider");
  5195. });
  5196. });
  5197. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5198. res.set_content("ok", "text/plain");
  5199. });
  5200. auto port = svr.bind_to_any_port(HOST);
  5201. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5202. auto se = detail::scope_exit([&] {
  5203. svr.stop();
  5204. listen_thread.join();
  5205. ASSERT_FALSE(svr.is_running());
  5206. });
  5207. svr.wait_until_ready();
  5208. {
  5209. Client cli(HOST, port);
  5210. cli.set_read_timeout(5, 0);
  5211. EXPECT_FALSE(cli.Get("/throw"));
  5212. }
  5213. EXPECT_TRUE(svr.is_running());
  5214. EXPECT_EQ(1, reported.load());
  5215. {
  5216. Client cli(HOST, port);
  5217. auto res = cli.Get("/ok");
  5218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5219. EXPECT_EQ(StatusCode::OK_200, res->status);
  5220. EXPECT_EQ("ok", res->body);
  5221. }
  5222. }
  5223. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5224. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5225. // so the exception unwinds through the ws::WebSocket object on its way to
  5226. // the guard. None of the HTTP cases above cross that.
  5227. Server svr;
  5228. svr.new_task_queue = [] { return new ThreadPool(1); };
  5229. std::atomic<int> reported{0};
  5230. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5231. if (err == Error::UserCallbackException) { reported++; }
  5232. });
  5233. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5234. throw std::runtime_error("from the WebSocket handler");
  5235. });
  5236. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5237. res.set_content("ok", "text/plain");
  5238. });
  5239. auto port = svr.bind_to_any_port(HOST);
  5240. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5241. auto se = detail::scope_exit([&] {
  5242. svr.stop();
  5243. listen_thread.join();
  5244. ASSERT_FALSE(svr.is_running());
  5245. });
  5246. svr.wait_until_ready();
  5247. {
  5248. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5249. "/ws");
  5250. auto res = client.connect();
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. // The server dropped the connection instead of dying.
  5253. std::string msg;
  5254. EXPECT_FALSE(client.read(msg));
  5255. client.close();
  5256. }
  5257. EXPECT_TRUE(svr.is_running());
  5258. EXPECT_EQ(1, reported.load());
  5259. {
  5260. Client cli(HOST, port);
  5261. auto res = cli.Get("/ok");
  5262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5263. EXPECT_EQ(StatusCode::OK_200, res->status);
  5264. EXPECT_EQ("ok", res->body);
  5265. }
  5266. }
  5267. #ifdef CPPHTTPLIB_SSL_ENABLED
  5268. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5269. // SSLServer::process_and_close_socket() is a separate overload with its own
  5270. // guard, so it is exercised on its own.
  5271. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5272. ASSERT_TRUE(svr.is_valid());
  5273. svr.new_task_queue = [] { return new ThreadPool(1); };
  5274. std::atomic<int> reported{0};
  5275. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5276. if (err == Error::UserCallbackException) { reported++; }
  5277. });
  5278. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5279. res.set_content_provider(
  5280. 1024, "text/plain",
  5281. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5282. sink.write("hello", 5);
  5283. throw std::runtime_error("from the content provider");
  5284. });
  5285. });
  5286. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5287. res.set_content("ok", "text/plain");
  5288. });
  5289. auto port = svr.bind_to_any_port(HOST);
  5290. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5291. auto se = detail::scope_exit([&] {
  5292. svr.stop();
  5293. listen_thread.join();
  5294. ASSERT_FALSE(svr.is_running());
  5295. });
  5296. svr.wait_until_ready();
  5297. {
  5298. SSLClient cli(HOST, port);
  5299. cli.enable_server_certificate_verification(false);
  5300. cli.set_read_timeout(5, 0);
  5301. EXPECT_FALSE(cli.Get("/throw"));
  5302. }
  5303. EXPECT_TRUE(svr.is_running());
  5304. EXPECT_EQ(1, reported.load());
  5305. {
  5306. SSLClient cli(HOST, port);
  5307. cli.enable_server_certificate_verification(false);
  5308. auto res = cli.Get("/ok");
  5309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5310. EXPECT_EQ(StatusCode::OK_200, res->status);
  5311. EXPECT_EQ("ok", res->body);
  5312. }
  5313. }
  5314. #endif
  5315. #endif
  5316. TEST(NoContentTest, ContentLength) {
  5317. Server svr;
  5318. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5319. res.status = StatusCode::NoContent_204;
  5320. });
  5321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5322. auto se = detail::scope_exit([&] {
  5323. svr.stop();
  5324. thread.join();
  5325. ASSERT_FALSE(svr.is_running());
  5326. });
  5327. svr.wait_until_ready();
  5328. {
  5329. Client cli(HOST, PORT);
  5330. auto res = cli.Get("/hi");
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5333. // RFC 9110 8.6: none in a 204 response
  5334. EXPECT_FALSE(res->has_header("Content-Length"));
  5335. }
  5336. }
  5337. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5338. Server svr;
  5339. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5340. res.set_header("Content-Length", "5");
  5341. res.set_content("hello world", "text/plain");
  5342. });
  5343. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5344. // A body that reads as the last chunk, were it taken as chunked
  5345. res.set_header("Transfer-Encoding", "chunked");
  5346. res.set_content("0\r\n\r\n", "text/plain");
  5347. });
  5348. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5349. res.set_header("Content-Length", "2");
  5350. res.set_content_provider(5, "text/plain",
  5351. [](size_t offset, size_t length, DataSink &sink) {
  5352. sink.write(&"hello"[offset], length);
  5353. return true;
  5354. });
  5355. });
  5356. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5357. res.set_header("Content-Length", "1234");
  5358. });
  5359. thread t = thread([&] { svr.listen(HOST, PORT); });
  5360. auto se = detail::scope_exit([&] {
  5361. svr.stop();
  5362. t.join();
  5363. ASSERT_FALSE(svr.is_running());
  5364. });
  5365. svr.wait_until_ready();
  5366. Client cli(HOST, PORT);
  5367. cli.set_read_timeout(1, 0);
  5368. auto expect_body = [&](const Result &res, const std::string &body) {
  5369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5370. EXPECT_EQ(body, res->body);
  5371. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5372. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5373. };
  5374. Headers identity{{"Accept-Encoding", ""}};
  5375. expect_body(cli.Get("/body", identity), "hello world");
  5376. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5377. expect_body(cli.Get("/body",
  5378. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5379. "he");
  5380. expect_body(cli.Get("/provider", identity), "hello");
  5381. expect_body(cli.Get("/empty", identity), "");
  5382. // A HEAD response may give the length of the body a GET would get.
  5383. auto res = cli.Head("/empty");
  5384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5385. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5386. }
  5387. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5388. Server svr;
  5389. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5390. res.set_content("short", "text/plain");
  5391. });
  5392. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5393. res.body += " with a footer";
  5394. res.set_header("Transfer-Encoding", "chunked");
  5395. });
  5396. thread t = thread([&] { svr.listen(HOST, PORT); });
  5397. auto se = detail::scope_exit([&] {
  5398. svr.stop();
  5399. t.join();
  5400. ASSERT_FALSE(svr.is_running());
  5401. });
  5402. svr.wait_until_ready();
  5403. Client cli(HOST, PORT);
  5404. cli.set_read_timeout(1, 0);
  5405. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5407. EXPECT_EQ("short with a footer", res->body);
  5408. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5409. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5410. }
  5411. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5412. Server svr;
  5413. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5414. res.set_header("Content-Length", "3");
  5415. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5416. sink.write("abc", 3);
  5417. sink.done();
  5418. return true;
  5419. });
  5420. });
  5421. thread t = thread([&] { svr.listen(HOST, PORT); });
  5422. auto se = detail::scope_exit([&] {
  5423. svr.stop();
  5424. t.join();
  5425. ASSERT_FALSE(svr.is_running());
  5426. });
  5427. svr.wait_until_ready();
  5428. Client cli(HOST, PORT);
  5429. cli.set_keep_alive(true);
  5430. auto res = cli.Get("/");
  5431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5432. EXPECT_EQ("abc", res->body);
  5433. EXPECT_FALSE(res->has_header("Content-Length"));
  5434. EXPECT_EQ("close", res->get_header_value("Connection"));
  5435. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5436. // No body to delimit
  5437. auto head = cli.Head("/");
  5438. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5439. EXPECT_FALSE(head->has_header("Connection"));
  5440. }
  5441. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5442. #ifdef CPPHTTPLIB_SSL_ENABLED
  5443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5444. ASSERT_TRUE(svr.is_valid());
  5445. #else
  5446. Server svr;
  5447. #endif
  5448. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5449. if (req.path == "/routing_handler") {
  5450. res.set_header("PRE_ROUTING", "on");
  5451. res.set_content("Routing Handler", "text/plain");
  5452. return httplib::Server::HandlerResponse::Handled;
  5453. }
  5454. return httplib::Server::HandlerResponse::Unhandled;
  5455. });
  5456. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5457. res.set_content("Error", "text/html");
  5458. });
  5459. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5460. if (req.path == "/routing_handler") {
  5461. res.set_header("POST_ROUTING", "on");
  5462. }
  5463. });
  5464. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5465. res.set_content("Hello World!\n", "text/plain");
  5466. });
  5467. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5468. auto se = detail::scope_exit([&] {
  5469. svr.stop();
  5470. thread.join();
  5471. ASSERT_FALSE(svr.is_running());
  5472. });
  5473. svr.wait_until_ready();
  5474. {
  5475. #ifdef CPPHTTPLIB_SSL_ENABLED
  5476. SSLClient cli(HOST, PORT);
  5477. cli.enable_server_certificate_verification(false);
  5478. #else
  5479. Client cli(HOST, PORT);
  5480. #endif
  5481. auto res = cli.Get("/routing_handler");
  5482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5483. EXPECT_EQ(StatusCode::OK_200, res->status);
  5484. EXPECT_EQ("Routing Handler", res->body);
  5485. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5486. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5487. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5488. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5489. }
  5490. {
  5491. #ifdef CPPHTTPLIB_SSL_ENABLED
  5492. SSLClient cli(HOST, PORT);
  5493. cli.enable_server_certificate_verification(false);
  5494. #else
  5495. Client cli(HOST, PORT);
  5496. #endif
  5497. auto res = cli.Get("/hi");
  5498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5499. EXPECT_EQ(StatusCode::OK_200, res->status);
  5500. EXPECT_EQ("Hello World!\n", res->body);
  5501. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5502. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5503. }
  5504. {
  5505. #ifdef CPPHTTPLIB_SSL_ENABLED
  5506. SSLClient cli(HOST, PORT);
  5507. cli.enable_server_certificate_verification(false);
  5508. #else
  5509. Client cli(HOST, PORT);
  5510. #endif
  5511. auto res = cli.Get("/aaa");
  5512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5513. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5514. EXPECT_EQ("Error", res->body);
  5515. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5516. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5517. }
  5518. }
  5519. TEST(RequestHandlerTest, PreRequestHandler) {
  5520. auto route_path = "/user/:user";
  5521. Server svr;
  5522. svr.Get("/hi", [](const Request &, Response &res) {
  5523. res.set_content("hi", "text/plain");
  5524. });
  5525. svr.Get(route_path, [](const Request &req, Response &res) {
  5526. res.set_content(req.path_params.at("user"), "text/plain");
  5527. });
  5528. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5529. if (req.matched_route == route_path) {
  5530. auto user = req.path_params.at("user");
  5531. if (user != "john") {
  5532. res.status = StatusCode::Forbidden_403;
  5533. res.set_content("error", "text/html");
  5534. return Server::HandlerResponse::Handled;
  5535. }
  5536. }
  5537. return Server::HandlerResponse::Unhandled;
  5538. });
  5539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5540. auto se = detail::scope_exit([&] {
  5541. svr.stop();
  5542. thread.join();
  5543. ASSERT_FALSE(svr.is_running());
  5544. });
  5545. svr.wait_until_ready();
  5546. Client cli(HOST, PORT);
  5547. {
  5548. auto res = cli.Get("/hi");
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. EXPECT_EQ(StatusCode::OK_200, res->status);
  5551. EXPECT_EQ("hi", res->body);
  5552. }
  5553. {
  5554. auto res = cli.Get("/user/john");
  5555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5556. EXPECT_EQ(StatusCode::OK_200, res->status);
  5557. EXPECT_EQ("john", res->body);
  5558. }
  5559. {
  5560. auto res = cli.Get("/user/invalid-user");
  5561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5562. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5563. EXPECT_EQ("error", res->body);
  5564. }
  5565. }
  5566. // The pre-request handler must run before the request body is read, so a
  5567. // rejected request never forces the server to buffer a (potentially large)
  5568. // body. Here the posted body is larger than the payload limit: if the body
  5569. // were read first the server would answer 413, but because the pre-request
  5570. // handler runs first it answers 403 and the body is never read.
  5571. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5572. Server svr;
  5573. svr.set_payload_max_length(8);
  5574. auto handler_ran = false;
  5575. svr.Post("/reject", [&](const Request &req, Response &res) {
  5576. handler_ran = true;
  5577. res.set_content(req.body, "text/plain");
  5578. });
  5579. svr.Post("/accept", [](const Request &req, Response &res) {
  5580. res.set_content(req.body, "text/plain");
  5581. });
  5582. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5583. if (req.matched_route == "/reject") {
  5584. res.status = StatusCode::Forbidden_403;
  5585. res.set_content("denied", "text/plain");
  5586. return Server::HandlerResponse::Handled;
  5587. }
  5588. return Server::HandlerResponse::Unhandled;
  5589. });
  5590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5591. auto se = detail::scope_exit([&] {
  5592. svr.stop();
  5593. thread.join();
  5594. ASSERT_FALSE(svr.is_running());
  5595. });
  5596. svr.wait_until_ready();
  5597. Client cli(HOST, PORT);
  5598. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5599. // rejects with 403 before the body is read, so 413 is never reached.
  5600. {
  5601. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5603. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5604. EXPECT_EQ("denied", res->body);
  5605. EXPECT_FALSE(handler_ran);
  5606. }
  5607. // An approved route still reads the body and enforces the payload limit.
  5608. {
  5609. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5611. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5612. }
  5613. }
  5614. TEST(UserDataTest, BasicOperations) {
  5615. httplib::UserData ud;
  5616. // Initially empty
  5617. EXPECT_FALSE(ud.has("key"));
  5618. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5619. // set and get
  5620. ud.set("key", 42);
  5621. EXPECT_TRUE(ud.has("key"));
  5622. auto *p = ud.get<int>("key");
  5623. ASSERT_NE(nullptr, p);
  5624. EXPECT_EQ(42, *p);
  5625. // Type mismatch → nullptr
  5626. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5627. // Overwrite with different type
  5628. ud.set("key", std::string("hello"));
  5629. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5630. auto *s = ud.get<std::string>("key");
  5631. ASSERT_NE(nullptr, s);
  5632. EXPECT_EQ("hello", *s);
  5633. // erase
  5634. ud.erase("key");
  5635. EXPECT_FALSE(ud.has("key"));
  5636. // clear
  5637. ud.set("a", 1);
  5638. ud.set("b", 2);
  5639. ud.clear();
  5640. EXPECT_FALSE(ud.has("a"));
  5641. EXPECT_FALSE(ud.has("b"));
  5642. }
  5643. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5644. struct AuthCtx {
  5645. std::string user_id;
  5646. };
  5647. Server svr;
  5648. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5649. res.user_data.set("auth", AuthCtx{"alice"});
  5650. return Server::HandlerResponse::Unhandled;
  5651. });
  5652. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5653. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5654. ASSERT_NE(nullptr, ctx);
  5655. res.set_content("Hello " + ctx->user_id, "text/plain");
  5656. });
  5657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5658. auto se = detail::scope_exit([&] {
  5659. svr.stop();
  5660. thread.join();
  5661. ASSERT_FALSE(svr.is_running());
  5662. });
  5663. svr.wait_until_ready();
  5664. Client cli(HOST, PORT);
  5665. auto res = cli.Get("/me");
  5666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5667. EXPECT_EQ(StatusCode::OK_200, res->status);
  5668. EXPECT_EQ("Hello alice", res->body);
  5669. }
  5670. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5671. struct RoleCtx {
  5672. std::string role;
  5673. };
  5674. Server svr;
  5675. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5676. res.user_data.set("role", RoleCtx{"admin"});
  5677. return Server::HandlerResponse::Unhandled;
  5678. });
  5679. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5680. auto *ctx = res.user_data.get<RoleCtx>("role");
  5681. ASSERT_NE(nullptr, ctx);
  5682. res.set_content(ctx->role, "text/plain");
  5683. });
  5684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5685. auto se = detail::scope_exit([&] {
  5686. svr.stop();
  5687. thread.join();
  5688. ASSERT_FALSE(svr.is_running());
  5689. });
  5690. svr.wait_until_ready();
  5691. Client cli(HOST, PORT);
  5692. auto res = cli.Get("/role");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. EXPECT_EQ(StatusCode::OK_200, res->status);
  5695. EXPECT_EQ("admin", res->body);
  5696. }
  5697. TEST(InvalidFormatTest, StatusCode) {
  5698. Server svr;
  5699. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5700. res.set_content("Hello World!\n", "text/plain");
  5701. res.status = 9999; // Status should be a three-digit code...
  5702. });
  5703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5704. auto se = detail::scope_exit([&] {
  5705. svr.stop();
  5706. thread.join();
  5707. ASSERT_FALSE(svr.is_running());
  5708. });
  5709. svr.wait_until_ready();
  5710. {
  5711. Client cli(HOST, PORT);
  5712. auto res = cli.Get("/hi");
  5713. ASSERT_FALSE(res);
  5714. }
  5715. }
  5716. TEST(URLFragmentTest, WithFragment) {
  5717. Server svr;
  5718. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5719. EXPECT_TRUE(req.target == "/hi");
  5720. });
  5721. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5722. auto se = detail::scope_exit([&] {
  5723. svr.stop();
  5724. thread.join();
  5725. ASSERT_FALSE(svr.is_running());
  5726. });
  5727. svr.wait_until_ready();
  5728. {
  5729. Client cli(HOST, PORT);
  5730. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5731. EXPECT_TRUE(res);
  5732. EXPECT_EQ(StatusCode::OK_200, res->status);
  5733. res = cli.Get("/hi%23key1=val1=key2=val2");
  5734. EXPECT_TRUE(res);
  5735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5736. }
  5737. }
  5738. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5739. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5740. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5741. Server svr;
  5742. std::vector<std::string> targets;
  5743. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5744. targets.push_back(req.target);
  5745. });
  5746. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5747. auto se = detail::scope_exit([&] {
  5748. svr.stop();
  5749. thread.join();
  5750. ASSERT_FALSE(svr.is_running());
  5751. });
  5752. svr.wait_until_ready();
  5753. Client cli(HOST, PORT);
  5754. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5755. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5756. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5757. // A '?' after the '#' belongs to the fragment, not to the query.
  5758. Request req;
  5759. req.method = "GET";
  5760. req.path = "/hi#f?x=1";
  5761. req.params.emplace("a", "1");
  5762. Response res;
  5763. auto error = Error::Success;
  5764. EXPECT_TRUE(cli.send(req, res, error));
  5765. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5766. "/hi?a=1"}),
  5767. targets);
  5768. }
  5769. TEST(HeaderWriter, SetHeaderWriter) {
  5770. Server svr;
  5771. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5772. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5773. return detail::write_headers(strm, hdrs);
  5774. });
  5775. svr.Get("/hi", [](const Request &req, Response &res) {
  5776. auto it = req.headers.find("CustomClientHeader");
  5777. EXPECT_TRUE(it != req.headers.end());
  5778. EXPECT_EQ(it->second, "CustomClientValue");
  5779. res.set_content("Hello World!\n", "text/plain");
  5780. });
  5781. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5782. auto se = detail::scope_exit([&] {
  5783. svr.stop();
  5784. thread.join();
  5785. ASSERT_FALSE(svr.is_running());
  5786. });
  5787. svr.wait_until_ready();
  5788. {
  5789. Client cli(HOST, PORT);
  5790. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5791. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5792. return detail::write_headers(strm, hdrs);
  5793. });
  5794. auto res = cli.Get("/hi");
  5795. EXPECT_TRUE(res);
  5796. EXPECT_EQ(StatusCode::OK_200, res->status);
  5797. auto it = res->headers.find("CustomServerHeader");
  5798. EXPECT_TRUE(it != res->headers.end());
  5799. EXPECT_EQ(it->second, "CustomServerValue");
  5800. }
  5801. }
  5802. class ServerTest : public ::testing::Test {
  5803. protected:
  5804. ServerTest()
  5805. : cli_(HOST, PORT)
  5806. #ifdef CPPHTTPLIB_SSL_ENABLED
  5807. ,
  5808. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5809. #endif
  5810. {
  5811. #ifdef CPPHTTPLIB_SSL_ENABLED
  5812. cli_.enable_server_certificate_verification(false);
  5813. #endif
  5814. // Allow LARGE_DATA (100MB) responses
  5815. cli_.set_payload_max_length(200 * 1024 * 1024);
  5816. }
  5817. virtual void SetUp() {
  5818. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5819. svr_.set_payload_max_length(200 * 1024 * 1024);
  5820. svr_.set_mount_point("/", "./www");
  5821. svr_.set_mount_point("/mount", "./www2");
  5822. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5823. svr_.Get("/hi",
  5824. [&](const Request & /*req*/, Response &res) {
  5825. res.set_content("Hello World!", "text/plain");
  5826. })
  5827. .Get("/file_content",
  5828. [&](const Request & /*req*/, Response &res) {
  5829. res.set_file_content("./www/dir/test.html");
  5830. })
  5831. .Get("/file_content_with_content_type",
  5832. [&](const Request & /*req*/, Response &res) {
  5833. res.set_file_content("./www/file", "text/plain");
  5834. })
  5835. .Get("/invalid_file_content",
  5836. [&](const Request & /*req*/, Response &res) {
  5837. res.set_file_content("./www/dir/invalid_file_path");
  5838. })
  5839. .Get("/http_response_splitting",
  5840. [&](const Request & /*req*/, Response &res) {
  5841. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5842. EXPECT_EQ(0U, res.headers.size());
  5843. EXPECT_FALSE(res.has_header("a"));
  5844. res.set_header("a", "1\nSet-Cookie: a=1");
  5845. EXPECT_EQ(0U, res.headers.size());
  5846. EXPECT_FALSE(res.has_header("a"));
  5847. res.set_header("a", "1\rSet-Cookie: a=1");
  5848. EXPECT_EQ(0U, res.headers.size());
  5849. EXPECT_FALSE(res.has_header("a"));
  5850. res.set_header("a\r\nb", "0");
  5851. EXPECT_EQ(0U, res.headers.size());
  5852. EXPECT_FALSE(res.has_header("a"));
  5853. res.set_header("a\rb", "0");
  5854. EXPECT_EQ(0U, res.headers.size());
  5855. EXPECT_FALSE(res.has_header("a"));
  5856. res.set_header("a\nb", "0");
  5857. EXPECT_EQ(0U, res.headers.size());
  5858. EXPECT_FALSE(res.has_header("a"));
  5859. res.set_redirect("1\r\nSet-Cookie: a=1");
  5860. EXPECT_EQ(0U, res.headers.size());
  5861. EXPECT_FALSE(res.has_header("Location"));
  5862. })
  5863. .Get("/slow",
  5864. [&](const Request & /*req*/, Response &res) {
  5865. std::this_thread::sleep_for(std::chrono::seconds(4));
  5866. res.set_content("slow", "text/plain");
  5867. })
  5868. #if 0
  5869. .Post("/slowpost",
  5870. [&](const Request & /*req*/, Response &res) {
  5871. std::this_thread::sleep_for(std::chrono::seconds(2));
  5872. res.set_content("slow", "text/plain");
  5873. })
  5874. #endif
  5875. .Get("/remote_addr",
  5876. [&](const Request &req, Response &res) {
  5877. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5878. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5879. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5880. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5881. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5882. #endif
  5883. res.set_content(req.remote_addr, "text/plain");
  5884. })
  5885. .Get("/local_addr",
  5886. [&](const Request &req, Response &res) {
  5887. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5888. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5889. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5890. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5891. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5892. #endif
  5893. auto local_addr = req.local_addr;
  5894. auto local_port = std::to_string(req.local_port);
  5895. res.set_content(local_addr.append(":").append(local_port),
  5896. "text/plain");
  5897. })
  5898. .Get("/endwith%",
  5899. [&](const Request & /*req*/, Response &res) {
  5900. res.set_content("Hello World!", "text/plain");
  5901. })
  5902. .Get("/a\\+\\+b",
  5903. [&](const Request &req, Response &res) {
  5904. ASSERT_TRUE(req.has_param("a +b"));
  5905. auto val = req.get_param_value("a +b");
  5906. res.set_content(val, "text/plain");
  5907. })
  5908. .Get("/", [&](const Request & /*req*/,
  5909. Response &res) { res.set_redirect("/hi"); })
  5910. .Post("/1",
  5911. [](const Request & /*req*/, Response &res) {
  5912. res.set_redirect("/2", StatusCode::SeeOther_303);
  5913. })
  5914. .Get("/2",
  5915. [](const Request & /*req*/, Response &res) {
  5916. res.set_content("redirected.", "text/plain");
  5917. res.status = StatusCode::OK_200;
  5918. })
  5919. .Post("/person",
  5920. [&](const Request &req, Response &res) {
  5921. if (req.has_param("name") && req.has_param("note")) {
  5922. persons_[req.get_param_value("name")] =
  5923. req.get_param_value("note");
  5924. } else {
  5925. res.status = StatusCode::BadRequest_400;
  5926. }
  5927. })
  5928. .Put("/person",
  5929. [&](const Request &req, Response &res) {
  5930. if (req.has_param("name") && req.has_param("note")) {
  5931. persons_[req.get_param_value("name")] =
  5932. req.get_param_value("note");
  5933. } else {
  5934. res.status = StatusCode::BadRequest_400;
  5935. }
  5936. })
  5937. .Get("/person/(.*)",
  5938. [&](const Request &req, Response &res) {
  5939. string name = req.matches[1];
  5940. if (persons_.find(name) != persons_.end()) {
  5941. auto note = persons_[name];
  5942. res.set_content(note, "text/plain");
  5943. } else {
  5944. res.status = StatusCode::NotFound_404;
  5945. }
  5946. })
  5947. .Delete("/person",
  5948. [&](const Request &req, Response &res) {
  5949. if (req.has_param("name")) {
  5950. string name = req.get_param_value("name");
  5951. if (persons_.find(name) != persons_.end()) {
  5952. persons_.erase(name);
  5953. res.set_content("DELETED", "text/plain");
  5954. } else {
  5955. res.status = StatusCode::NotFound_404;
  5956. }
  5957. } else {
  5958. res.status = StatusCode::BadRequest_400;
  5959. }
  5960. })
  5961. .Post("/x-www-form-urlencoded-json",
  5962. [&](const Request &req, Response &res) {
  5963. auto json = req.get_param_value("json");
  5964. ASSERT_EQ(JSON_DATA, json);
  5965. res.set_content(json, "appliation/json");
  5966. res.status = StatusCode::OK_200;
  5967. })
  5968. .Get("/streamed-chunked",
  5969. [&](const Request & /*req*/, Response &res) {
  5970. res.set_chunked_content_provider(
  5971. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5972. sink.os << "123";
  5973. sink.os << "456";
  5974. sink.os << "789";
  5975. sink.done();
  5976. return true;
  5977. });
  5978. })
  5979. .Get("/streamed-chunked-with-prohibited-trailer",
  5980. [&](const Request & /*req*/, Response &res) {
  5981. auto i = new int(0);
  5982. // Declare both a prohibited trailer (Content-Length) and an
  5983. // allowed one
  5984. res.set_header("Trailer", "Content-Length, X-Allowed");
  5985. res.set_chunked_content_provider(
  5986. "text/plain",
  5987. [i](size_t /*offset*/, DataSink &sink) {
  5988. switch (*i) {
  5989. case 0: sink.os << "123"; break;
  5990. case 1: sink.os << "456"; break;
  5991. case 2: sink.os << "789"; break;
  5992. case 3: {
  5993. sink.done_with_trailer(
  5994. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5995. } break;
  5996. }
  5997. (*i)++;
  5998. return true;
  5999. },
  6000. [i](bool success) {
  6001. EXPECT_TRUE(success);
  6002. delete i;
  6003. });
  6004. })
  6005. .Get("/streamed-chunked2",
  6006. [&](const Request & /*req*/, Response &res) {
  6007. auto i = new int(0);
  6008. res.set_chunked_content_provider(
  6009. "text/plain",
  6010. [i](size_t /*offset*/, DataSink &sink) {
  6011. switch (*i) {
  6012. case 0: sink.os << "123"; break;
  6013. case 1: sink.os << "456"; break;
  6014. case 2: sink.os << "789"; break;
  6015. case 3: sink.done(); break;
  6016. }
  6017. (*i)++;
  6018. return true;
  6019. },
  6020. [i](bool success) {
  6021. EXPECT_TRUE(success);
  6022. delete i;
  6023. });
  6024. })
  6025. .Get("/streamed-chunked-with-trailer",
  6026. [&](const Request & /*req*/, Response &res) {
  6027. auto i = new int(0);
  6028. res.set_header("Trailer", "Dummy1, Dummy2");
  6029. res.set_chunked_content_provider(
  6030. "text/plain",
  6031. [i](size_t /*offset*/, DataSink &sink) {
  6032. switch (*i) {
  6033. case 0: sink.os << "123"; break;
  6034. case 1: sink.os << "456"; break;
  6035. case 2: sink.os << "789"; break;
  6036. case 3: {
  6037. sink.done_with_trailer(
  6038. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6039. } break;
  6040. }
  6041. (*i)++;
  6042. return true;
  6043. },
  6044. [i](bool success) {
  6045. EXPECT_TRUE(success);
  6046. delete i;
  6047. });
  6048. })
  6049. .Get("/streamed",
  6050. [&](const Request & /*req*/, Response &res) {
  6051. res.set_content_provider(
  6052. 6, "text/plain",
  6053. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6054. sink.os << (offset < 3 ? "a" : "b");
  6055. return true;
  6056. });
  6057. })
  6058. .Get("/streamed-without-length",
  6059. [&](const Request & /*req*/, Response &res) {
  6060. auto data = new std::string("abcdefg");
  6061. res.set_content_provider(
  6062. "text/plain",
  6063. [data](size_t offset, DataSink &sink) {
  6064. if (offset < data->size()) {
  6065. sink.os << data->substr(offset);
  6066. }
  6067. sink.done();
  6068. return true;
  6069. },
  6070. [data](bool success) {
  6071. EXPECT_TRUE(success);
  6072. delete data;
  6073. });
  6074. })
  6075. .Get("/streamed-with-range",
  6076. [&](const Request &req, Response &res) {
  6077. auto data = new std::string("abcdefg");
  6078. // An explicit status keeps the server from picking the 206 it
  6079. // would otherwise choose for a ranged request, so the response
  6080. // is not a partial representation.
  6081. auto status = req.get_param_value("status");
  6082. if (status == "200") {
  6083. res.status = StatusCode::OK_200;
  6084. } else if (status == "403") {
  6085. res.status = StatusCode::Forbidden_403;
  6086. }
  6087. res.set_content_provider(
  6088. data->size(), "text/plain",
  6089. [data](size_t offset, size_t length, DataSink &sink) {
  6090. size_t DATA_CHUNK_SIZE = 4;
  6091. const auto &d = *data;
  6092. auto out_len =
  6093. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6094. auto ret =
  6095. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6096. EXPECT_TRUE(ret);
  6097. return true;
  6098. },
  6099. [data, &req](bool success) {
  6100. EXPECT_EQ(success, !req.has_param("error"));
  6101. delete data;
  6102. });
  6103. })
  6104. .Get("/streamed-cancel",
  6105. [&](const Request & /*req*/, Response &res) {
  6106. res.set_content_provider(
  6107. size_t(-1), "text/plain",
  6108. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6109. sink.os << "data_chunk";
  6110. return true;
  6111. });
  6112. })
  6113. .Get("/regex-with-delimiter",
  6114. [&](const Request &req, Response & /*res*/) {
  6115. ASSERT_TRUE(req.has_param("key"));
  6116. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6117. })
  6118. .Get("/with-range",
  6119. [&](const Request & /*req*/, Response &res) {
  6120. res.set_content("abcdefg", "text/plain");
  6121. })
  6122. .Get("/test-start-time",
  6123. [&](const Request &req, Response & /*res*/) {
  6124. EXPECT_NE(req.start_time_,
  6125. std::chrono::steady_clock::time_point::min());
  6126. })
  6127. .Get("/with-range-customized-response",
  6128. [&](const Request & /*req*/, Response &res) {
  6129. res.status = StatusCode::BadRequest_400;
  6130. res.set_content(JSON_DATA, "application/json");
  6131. })
  6132. .Post("/chunked",
  6133. [&](const Request &req, Response & /*res*/) {
  6134. EXPECT_EQ(req.body, "dechunked post body");
  6135. })
  6136. .Post("/large-chunked",
  6137. [&](const Request &req, Response & /*res*/) {
  6138. std::string expected(6 * 30 * 1024u, 'a');
  6139. EXPECT_EQ(req.body, expected);
  6140. })
  6141. .Post("/multipart",
  6142. [&](const Request &req, Response & /*res*/) {
  6143. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6144. req.form.get_field_count("text2") +
  6145. req.form.get_field_count("file3") +
  6146. req.form.get_field_count("file4"));
  6147. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6148. req.form.get_file_count("file2"));
  6149. ASSERT_TRUE(!req.form.has_file("???"));
  6150. ASSERT_TRUE(!req.form.has_field("???"));
  6151. ASSERT_TRUE(req.body.empty());
  6152. {
  6153. const auto &text = req.form.get_field("text1");
  6154. EXPECT_EQ("text default", text);
  6155. }
  6156. {
  6157. const auto &text = req.form.get_field("text2");
  6158. EXPECT_EQ("aωb", text);
  6159. }
  6160. {
  6161. const auto &file = req.form.get_file("file1");
  6162. EXPECT_EQ("hello.txt", file.filename);
  6163. EXPECT_EQ("text/plain", file.content_type);
  6164. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6165. }
  6166. {
  6167. const auto &file = req.form.get_file("file2");
  6168. EXPECT_EQ("world.json", file.filename);
  6169. EXPECT_EQ("application/json", file.content_type);
  6170. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6171. }
  6172. {
  6173. const auto &text = req.form.get_field("file3");
  6174. EXPECT_EQ(0u, text.size());
  6175. }
  6176. {
  6177. const auto &text = req.form.get_field("file4");
  6178. EXPECT_EQ(0u, text.size());
  6179. }
  6180. })
  6181. .Post("/multipart/multi_file_values",
  6182. [&](const Request &req, Response & /*res*/) {
  6183. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6184. req.form.get_field_count("multi_text1"));
  6185. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6186. ASSERT_TRUE(!req.form.has_file("???"));
  6187. ASSERT_TRUE(!req.form.has_field("???"));
  6188. ASSERT_TRUE(req.body.empty());
  6189. {
  6190. const auto &text = req.form.get_field("text");
  6191. EXPECT_EQ("default text", text);
  6192. }
  6193. {
  6194. const auto &text1_values = req.form.get_fields("multi_text1");
  6195. EXPECT_EQ(2u, text1_values.size());
  6196. EXPECT_EQ("aaaaa", text1_values[0]);
  6197. EXPECT_EQ("bbbbb", text1_values[1]);
  6198. }
  6199. {
  6200. const auto &file1_values = req.form.get_files("multi_file1");
  6201. EXPECT_EQ(2u, file1_values.size());
  6202. auto file1 = file1_values[0];
  6203. EXPECT_EQ(file1.filename, "hello.txt");
  6204. EXPECT_EQ(file1.content_type, "text/plain");
  6205. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6206. auto file2 = file1_values[1];
  6207. EXPECT_EQ(file2.filename, "world.json");
  6208. EXPECT_EQ(file2.content_type, "application/json");
  6209. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6210. }
  6211. })
  6212. .Post("/empty",
  6213. [&](const Request &req, Response &res) {
  6214. EXPECT_EQ(req.body, "");
  6215. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6216. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6217. res.set_content("empty", "text/plain");
  6218. })
  6219. .Post("/empty-no-content-type",
  6220. [&](const Request &req, Response &res) {
  6221. EXPECT_EQ(req.body, "");
  6222. EXPECT_FALSE(req.has_header("Content-Type"));
  6223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6224. res.set_content("empty-no-content-type", "text/plain");
  6225. })
  6226. .Post("/path-only",
  6227. [&](const Request &req, Response &res) {
  6228. EXPECT_EQ(req.body, "");
  6229. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6230. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6231. res.set_content("path-only", "text/plain");
  6232. })
  6233. .Post("/path-headers-only",
  6234. [&](const Request &req, Response &res) {
  6235. EXPECT_EQ(req.body, "");
  6236. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6237. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6238. EXPECT_EQ("world", req.get_header_value("hello"));
  6239. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6240. res.set_content("path-headers-only", "text/plain");
  6241. })
  6242. .Post("/post-large",
  6243. [&](const Request &req, Response &res) {
  6244. EXPECT_EQ(req.body, LARGE_DATA);
  6245. res.set_content(req.body, "text/plain");
  6246. })
  6247. .Post("/post-loopback",
  6248. [&](const Request &, Response &res,
  6249. ContentReader const &content_reader) {
  6250. std::string body;
  6251. content_reader([&](const char *data, size_t data_length) {
  6252. body.append(data, data_length);
  6253. return true;
  6254. });
  6255. res.set_content(body, "text/plain");
  6256. })
  6257. .Put("/put-loopback",
  6258. [&](const Request &, Response &res,
  6259. ContentReader const &content_reader) {
  6260. std::string body;
  6261. content_reader([&](const char *data, size_t data_length) {
  6262. body.append(data, data_length);
  6263. return true;
  6264. });
  6265. res.set_content(body, "text/plain");
  6266. })
  6267. .Patch("/patch-loopback",
  6268. [&](const Request &, Response &res,
  6269. ContentReader const &content_reader) {
  6270. std::string body;
  6271. content_reader([&](const char *data, size_t data_length) {
  6272. body.append(data, data_length);
  6273. return true;
  6274. });
  6275. res.set_content(body, "text/plain");
  6276. })
  6277. .Put("/empty-no-content-type",
  6278. [&](const Request &req, Response &res) {
  6279. EXPECT_EQ(req.body, "");
  6280. EXPECT_FALSE(req.has_header("Content-Type"));
  6281. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6282. res.set_content("empty-no-content-type", "text/plain");
  6283. })
  6284. .Put("/put",
  6285. [&](const Request &req, Response &res) {
  6286. EXPECT_EQ(req.body, "PUT");
  6287. res.set_content(req.body, "text/plain");
  6288. })
  6289. .Put("/put-large",
  6290. [&](const Request &req, Response &res) {
  6291. EXPECT_EQ(req.body, LARGE_DATA);
  6292. res.set_content(req.body, "text/plain");
  6293. })
  6294. .Patch("/patch",
  6295. [&](const Request &req, Response &res) {
  6296. EXPECT_EQ(req.body, "PATCH");
  6297. res.set_content(req.body, "text/plain");
  6298. })
  6299. .Delete("/delete",
  6300. [&](const Request & /*req*/, Response &res) {
  6301. res.set_content("DELETE", "text/plain");
  6302. })
  6303. .Delete("/delete-body",
  6304. [&](const Request &req, Response &res) {
  6305. EXPECT_EQ(req.body, "content");
  6306. res.set_content(req.body, "text/plain");
  6307. })
  6308. .Options(R"(\*)",
  6309. [&](const Request & /*req*/, Response &res) {
  6310. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6311. })
  6312. .CustomRoute("PROPFIND", "/dav/:id",
  6313. [&](const Request &req, Response &res) {
  6314. res.set_header("x-body-size",
  6315. std::to_string(req.body.size()));
  6316. res.set_header("x-matched-route", req.matched_route);
  6317. res.set_header("x-dav-id", req.path_params.at("id"));
  6318. res.status = StatusCode::MultiStatus_207;
  6319. res.set_content(req.body, "application/xml");
  6320. })
  6321. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6322. [&](const Request &req, Response &res) {
  6323. res.set_header("x-dav-match", req.matches[1]);
  6324. res.status = StatusCode::MultiStatus_207;
  6325. })
  6326. .CustomRoute("MKCOL", "/dav-mkcol",
  6327. [&](const Request &req, Response &res) {
  6328. EXPECT_TRUE(req.body.empty());
  6329. res.status = StatusCode::Created_201;
  6330. })
  6331. .CustomRoute(
  6332. "REPORT", "/dav-report",
  6333. [&](const Request & /*req*/, Response &res,
  6334. const ContentReader &content_reader) {
  6335. std::string body;
  6336. content_reader([&](const char *data, size_t data_length) {
  6337. body.append(data, data_length);
  6338. return true;
  6339. });
  6340. res.set_header("x-body-size", std::to_string(body.size()));
  6341. res.status = StatusCode::MultiStatus_207;
  6342. res.set_content(body, "application/xml");
  6343. })
  6344. .Get("/request-target",
  6345. [&](const Request &req, Response & /*res*/) {
  6346. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6347. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6348. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6349. })
  6350. .Get("/long-query-value",
  6351. [&](const Request &req, Response & /*res*/) {
  6352. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6353. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6354. })
  6355. .Get("/too-long-query-value",
  6356. [&](const Request &req, Response & /*res*/) {
  6357. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6358. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6359. })
  6360. .Get("/array-param",
  6361. [&](const Request &req, Response & /*res*/) {
  6362. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6363. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6364. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6365. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6366. })
  6367. .Get("/array-param-values",
  6368. [&](const Request &req, Response & /*res*/) {
  6369. auto values = req.get_param_values("array");
  6370. EXPECT_EQ(3u, values.size());
  6371. EXPECT_EQ("value1", values[0]);
  6372. EXPECT_EQ("value2", values[1]);
  6373. EXPECT_EQ("value3", values[2]);
  6374. auto empty = req.get_param_values("nonexistent");
  6375. EXPECT_TRUE(empty.empty());
  6376. })
  6377. .Post("/validate-no-multiple-headers",
  6378. [&](const Request &req, Response & /*res*/) {
  6379. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6380. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6381. })
  6382. .Post("/content_receiver",
  6383. [&](const Request &req, Response &res,
  6384. const ContentReader &content_reader) {
  6385. if (req.is_multipart_form_data()) {
  6386. std::vector<FormData> items;
  6387. content_reader(
  6388. [&](const FormData &file) {
  6389. items.push_back(file);
  6390. return true;
  6391. },
  6392. [&](const char *data, size_t data_length) {
  6393. items.back().content.append(data, data_length);
  6394. return true;
  6395. });
  6396. EXPECT_EQ(5u, items.size());
  6397. {
  6398. const auto &file = get_file_value(items, "text1");
  6399. EXPECT_TRUE(file.filename.empty());
  6400. EXPECT_EQ("text default", file.content);
  6401. }
  6402. {
  6403. const auto &file = get_file_value(items, "text2");
  6404. EXPECT_TRUE(file.filename.empty());
  6405. EXPECT_EQ("aωb", file.content);
  6406. }
  6407. {
  6408. const auto &file = get_file_value(items, "file1");
  6409. EXPECT_EQ("hello.txt", file.filename);
  6410. EXPECT_EQ("text/plain", file.content_type);
  6411. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6412. }
  6413. {
  6414. const auto &file = get_file_value(items, "file2");
  6415. EXPECT_EQ("world.json", file.filename);
  6416. EXPECT_EQ("application/json", file.content_type);
  6417. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6418. }
  6419. {
  6420. const auto &file = get_file_value(items, "file3");
  6421. EXPECT_TRUE(file.filename.empty());
  6422. EXPECT_EQ("application/octet-stream", file.content_type);
  6423. EXPECT_EQ(0u, file.content.size());
  6424. }
  6425. } else {
  6426. std::string body;
  6427. content_reader([&](const char *data, size_t data_length) {
  6428. EXPECT_EQ(7U, data_length);
  6429. body.append(data, data_length);
  6430. return true;
  6431. });
  6432. EXPECT_EQ(body, "content");
  6433. res.set_content(body, "text/plain");
  6434. }
  6435. })
  6436. .Put("/content_receiver",
  6437. [&](const Request & /*req*/, Response &res,
  6438. const ContentReader &content_reader) {
  6439. std::string body;
  6440. content_reader([&](const char *data, size_t data_length) {
  6441. body.append(data, data_length);
  6442. return true;
  6443. });
  6444. EXPECT_EQ(body, "content");
  6445. res.set_content(body, "text/plain");
  6446. })
  6447. .Patch("/content_receiver",
  6448. [&](const Request & /*req*/, Response &res,
  6449. const ContentReader &content_reader) {
  6450. std::string body;
  6451. content_reader([&](const char *data, size_t data_length) {
  6452. body.append(data, data_length);
  6453. return true;
  6454. });
  6455. EXPECT_EQ(body, "content");
  6456. res.set_content(body, "text/plain");
  6457. })
  6458. .Post("/query-string-and-body",
  6459. [&](const Request &req, Response & /*res*/) {
  6460. ASSERT_TRUE(req.has_param("key"));
  6461. EXPECT_EQ(req.get_param_value("key"), "value");
  6462. EXPECT_EQ(req.body, "content");
  6463. })
  6464. .Get("/last-request",
  6465. [&](const Request &req, Response & /*res*/) {
  6466. EXPECT_EQ("close", req.get_header_value("Connection"));
  6467. })
  6468. .Get(R"(/redirect/(\d+))",
  6469. [&](const Request &req, Response &res) {
  6470. auto num = std::stoi(req.matches[1]) + 1;
  6471. std::string url = "/redirect/" + std::to_string(num);
  6472. res.set_redirect(url);
  6473. })
  6474. .Post("/binary",
  6475. [&](const Request &req, Response &res) {
  6476. EXPECT_EQ(4U, req.body.size());
  6477. EXPECT_EQ("application/octet-stream",
  6478. req.get_header_value("Content-Type"));
  6479. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6480. res.set_content(req.body, "application/octet-stream");
  6481. })
  6482. .Put("/binary",
  6483. [&](const Request &req, Response &res) {
  6484. EXPECT_EQ(4U, req.body.size());
  6485. EXPECT_EQ("application/octet-stream",
  6486. req.get_header_value("Content-Type"));
  6487. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6488. res.set_content(req.body, "application/octet-stream");
  6489. })
  6490. .Patch("/binary",
  6491. [&](const Request &req, Response &res) {
  6492. EXPECT_EQ(4U, req.body.size());
  6493. EXPECT_EQ("application/octet-stream",
  6494. req.get_header_value("Content-Type"));
  6495. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6496. res.set_content(req.body, "application/octet-stream");
  6497. })
  6498. .Delete("/binary",
  6499. [&](const Request &req, Response &res) {
  6500. EXPECT_EQ(4U, req.body.size());
  6501. EXPECT_EQ("application/octet-stream",
  6502. req.get_header_value("Content-Type"));
  6503. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6504. res.set_content(req.body, "application/octet-stream");
  6505. })
  6506. .Get("/issue1772",
  6507. [&](const Request & /*req*/, Response &res) {
  6508. res.status = 401;
  6509. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6510. })
  6511. .Delete("/issue609",
  6512. [](const httplib::Request &, httplib::Response &res,
  6513. const httplib::ContentReader &) {
  6514. res.set_content("ok", "text/plain");
  6515. })
  6516. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6517. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6518. .Get("/compress",
  6519. [&](const Request & /*req*/, Response &res) {
  6520. res.set_content(
  6521. "12345678901234567890123456789012345678901234567890123456789"
  6522. "01234567890123456789012345678901234567890",
  6523. "text/plain");
  6524. })
  6525. .Get("/compress-with-charset",
  6526. [&](const Request & /*req*/, Response &res) {
  6527. res.set_content(
  6528. "12345678901234567890123456789012345678901234567890123456789"
  6529. "01234567890123456789012345678901234567890",
  6530. "application/json; charset=utf-8");
  6531. })
  6532. .Get("/nocompress",
  6533. [&](const Request & /*req*/, Response &res) {
  6534. res.set_content(
  6535. "12345678901234567890123456789012345678901234567890123456789"
  6536. "01234567890123456789012345678901234567890",
  6537. "application/octet-stream");
  6538. })
  6539. .Post("/compress-multipart",
  6540. [&](const Request &req, Response & /*res*/) {
  6541. EXPECT_EQ(2u, req.form.fields.size());
  6542. ASSERT_TRUE(!req.form.has_field("???"));
  6543. {
  6544. const auto &text = req.form.get_field("key1");
  6545. EXPECT_EQ("test", text);
  6546. }
  6547. {
  6548. const auto &text = req.form.get_field("key2");
  6549. EXPECT_EQ("--abcdefg123", text);
  6550. }
  6551. })
  6552. #endif
  6553. ;
  6554. persons_["john"] = "programmer";
  6555. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6556. svr_.wait_until_ready();
  6557. }
  6558. virtual void TearDown() {
  6559. svr_.stop();
  6560. if (!request_threads_.empty()) {
  6561. std::this_thread::sleep_for(std::chrono::seconds(1));
  6562. for (auto &t : request_threads_) {
  6563. t.join();
  6564. }
  6565. }
  6566. t_.join();
  6567. }
  6568. map<string, string> persons_;
  6569. #ifdef CPPHTTPLIB_SSL_ENABLED
  6570. SSLClient cli_;
  6571. SSLServer svr_;
  6572. #else
  6573. Client cli_;
  6574. Server svr_;
  6575. #endif
  6576. thread t_;
  6577. std::vector<thread> request_threads_;
  6578. };
  6579. TEST_F(ServerTest, GetMethod200) {
  6580. auto res = cli_.Get("/hi");
  6581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6582. EXPECT_EQ("HTTP/1.1", res->version);
  6583. EXPECT_EQ(StatusCode::OK_200, res->status);
  6584. EXPECT_EQ("OK", res->reason);
  6585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6586. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6587. EXPECT_EQ("Hello World!", res->body);
  6588. }
  6589. TEST_F(ServerTest, GetEmptyFile) {
  6590. auto res = cli_.Get("/empty_file");
  6591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6592. EXPECT_EQ(StatusCode::OK_200, res->status);
  6593. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6594. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6595. EXPECT_EQ("", res->body);
  6596. }
  6597. TEST_F(ServerTest, GetFileContent) {
  6598. auto res = cli_.Get("/file_content");
  6599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6600. EXPECT_EQ(StatusCode::OK_200, res->status);
  6601. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6602. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6603. EXPECT_EQ("test.html", res->body);
  6604. }
  6605. TEST_F(ServerTest, GetFileContentWithRange) {
  6606. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6608. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6609. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6610. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6611. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6612. EXPECT_EQ("est", res->body);
  6613. }
  6614. TEST_F(ServerTest, GetFileContentWithContentType) {
  6615. auto res = cli_.Get("/file_content_with_content_type");
  6616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6617. EXPECT_EQ(StatusCode::OK_200, res->status);
  6618. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6619. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6620. EXPECT_EQ("file\n", res->body);
  6621. }
  6622. TEST_F(ServerTest, GetInvalidFileContent) {
  6623. auto res = cli_.Get("/invalid_file_content");
  6624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6625. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6626. }
  6627. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6628. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6630. EXPECT_EQ("HTTP/1.1", res->version);
  6631. EXPECT_EQ(StatusCode::OK_200, res->status);
  6632. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6633. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6634. EXPECT_EQ("Hello World!", res->body);
  6635. }
  6636. TEST_F(ServerTest, GetMethod302) {
  6637. auto res = cli_.Get("/");
  6638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6639. EXPECT_EQ(StatusCode::Found_302, res->status);
  6640. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6641. }
  6642. TEST_F(ServerTest, GetMethod302Redirect) {
  6643. cli_.set_follow_location(true);
  6644. auto res = cli_.Get("/");
  6645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6646. EXPECT_EQ(StatusCode::OK_200, res->status);
  6647. EXPECT_EQ("Hello World!", res->body);
  6648. EXPECT_EQ("/hi", res->location);
  6649. }
  6650. TEST_F(ServerTest, GetMethod404) {
  6651. auto res = cli_.Get("/invalid");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6654. }
  6655. TEST_F(ServerTest, HeadMethod200) {
  6656. auto res = cli_.Head("/hi");
  6657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6658. EXPECT_EQ(StatusCode::OK_200, res->status);
  6659. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6660. EXPECT_TRUE(res->body.empty());
  6661. }
  6662. TEST_F(ServerTest, HeadMethod200Static) {
  6663. auto res = cli_.Head("/mount/dir/index.html");
  6664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6665. EXPECT_EQ(StatusCode::OK_200, res->status);
  6666. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6667. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6668. EXPECT_TRUE(res->body.empty());
  6669. }
  6670. TEST_F(ServerTest, HeadMethod404) {
  6671. auto res = cli_.Head("/invalid");
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6674. EXPECT_TRUE(res->body.empty());
  6675. }
  6676. TEST_F(ServerTest, GetMethodPersonJohn) {
  6677. auto res = cli_.Get("/person/john");
  6678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6679. EXPECT_EQ(StatusCode::OK_200, res->status);
  6680. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6681. EXPECT_EQ("programmer", res->body);
  6682. }
  6683. TEST_F(ServerTest, PostMethod1) {
  6684. auto res = cli_.Get("/person/john1");
  6685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6686. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6687. res = cli_.Post("/person", "name=john1&note=coder",
  6688. "application/x-www-form-urlencoded");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. ASSERT_EQ(StatusCode::OK_200, res->status);
  6691. res = cli_.Get("/person/john1");
  6692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6693. ASSERT_EQ(StatusCode::OK_200, res->status);
  6694. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6695. ASSERT_EQ("coder", res->body);
  6696. }
  6697. TEST_F(ServerTest, PostMethod2) {
  6698. auto res = cli_.Get("/person/john2");
  6699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6700. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6701. Params params;
  6702. params.emplace("name", "john2");
  6703. params.emplace("note", "coder");
  6704. res = cli_.Post("/person", params);
  6705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6706. ASSERT_EQ(StatusCode::OK_200, res->status);
  6707. res = cli_.Get("/person/john2");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. ASSERT_EQ(StatusCode::OK_200, res->status);
  6710. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6711. ASSERT_EQ("coder", res->body);
  6712. }
  6713. TEST_F(ServerTest, PutMethod3) {
  6714. auto res = cli_.Get("/person/john3");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6717. Params params;
  6718. params.emplace("name", "john3");
  6719. params.emplace("note", "coder");
  6720. res = cli_.Put("/person", params);
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. ASSERT_EQ(StatusCode::OK_200, res->status);
  6723. res = cli_.Get("/person/john3");
  6724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6725. ASSERT_EQ(StatusCode::OK_200, res->status);
  6726. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6727. ASSERT_EQ("coder", res->body);
  6728. }
  6729. TEST_F(ServerTest, DeleteMethod1) {
  6730. auto res = cli_.Get("/person/john4");
  6731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6732. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6733. Params params;
  6734. params.emplace("name", "john4");
  6735. params.emplace("note", "coder");
  6736. res = cli_.Post("/person", params);
  6737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6738. ASSERT_EQ(StatusCode::OK_200, res->status);
  6739. res = cli_.Get("/person/john4");
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. ASSERT_EQ(StatusCode::OK_200, res->status);
  6742. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6743. ASSERT_EQ("coder", res->body);
  6744. Params delete_params;
  6745. delete_params.emplace("name", "john4");
  6746. res = cli_.Delete("/person", delete_params);
  6747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6748. ASSERT_EQ(StatusCode::OK_200, res->status);
  6749. ASSERT_EQ("DELETED", res->body);
  6750. res = cli_.Get("/person/john4");
  6751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6752. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6753. }
  6754. TEST_F(ServerTest, DeleteMethod2) {
  6755. auto res = cli_.Get("/person/john5");
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6758. Params params;
  6759. params.emplace("name", "john5");
  6760. params.emplace("note", "developer");
  6761. res = cli_.Post("/person", params);
  6762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6763. ASSERT_EQ(StatusCode::OK_200, res->status);
  6764. res = cli_.Get("/person/john5");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. ASSERT_EQ(StatusCode::OK_200, res->status);
  6767. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6768. ASSERT_EQ("developer", res->body);
  6769. Params delete_params;
  6770. delete_params.emplace("name", "john5");
  6771. Headers headers;
  6772. headers.emplace("Custom-Header", "test-value");
  6773. res = cli_.Delete("/person", headers, delete_params);
  6774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6775. ASSERT_EQ(StatusCode::OK_200, res->status);
  6776. ASSERT_EQ("DELETED", res->body);
  6777. res = cli_.Get("/person/john5");
  6778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6779. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6780. }
  6781. TEST_F(ServerTest, DeleteMethod3) {
  6782. auto res = cli_.Get("/person/john6");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6785. Params params;
  6786. params.emplace("name", "john6");
  6787. params.emplace("note", "tester");
  6788. res = cli_.Post("/person", params);
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. ASSERT_EQ(StatusCode::OK_200, res->status);
  6791. res = cli_.Get("/person/john6");
  6792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6793. ASSERT_EQ(StatusCode::OK_200, res->status);
  6794. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6795. ASSERT_EQ("tester", res->body);
  6796. Params delete_params;
  6797. delete_params.emplace("name", "john6");
  6798. Headers headers;
  6799. headers.emplace("Custom-Header", "test-value");
  6800. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6802. ASSERT_EQ(StatusCode::OK_200, res->status);
  6803. ASSERT_EQ("DELETED", res->body);
  6804. res = cli_.Get("/person/john6");
  6805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6806. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6807. }
  6808. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6809. Params params;
  6810. params.emplace("json", JSON_DATA);
  6811. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. ASSERT_EQ(StatusCode::OK_200, res->status);
  6814. ASSERT_EQ(JSON_DATA, res->body);
  6815. }
  6816. TEST_F(ServerTest, PostEmptyContent) {
  6817. auto res = cli_.Post("/empty", "", "text/plain");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. ASSERT_EQ(StatusCode::OK_200, res->status);
  6820. ASSERT_EQ("empty", res->body);
  6821. }
  6822. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6823. auto res = cli_.Post("/empty-no-content-type");
  6824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6825. ASSERT_EQ(StatusCode::OK_200, res->status);
  6826. ASSERT_EQ("empty-no-content-type", res->body);
  6827. }
  6828. TEST_F(ServerTest, PostPathOnly) {
  6829. auto res = cli_.Post("/path-only");
  6830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6831. ASSERT_EQ(StatusCode::OK_200, res->status);
  6832. ASSERT_EQ("path-only", res->body);
  6833. }
  6834. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6835. auto res = cli_.Post("/path-headers-only",
  6836. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. ASSERT_EQ(StatusCode::OK_200, res->status);
  6839. ASSERT_EQ("path-headers-only", res->body);
  6840. }
  6841. TEST_F(ServerTest, PostLarge) {
  6842. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. ASSERT_EQ(StatusCode::OK_200, res->status);
  6845. EXPECT_EQ(LARGE_DATA, res->body);
  6846. }
  6847. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6848. auto res = cli_.Put("/empty-no-content-type");
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. ASSERT_EQ(StatusCode::OK_200, res->status);
  6851. ASSERT_EQ("empty-no-content-type", res->body);
  6852. }
  6853. TEST_F(ServerTest, GetMethodDir) {
  6854. auto res = cli_.Get("/dir/");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6858. auto body = R"(<html>
  6859. <head>
  6860. </head>
  6861. <body>
  6862. <a href="/dir/test.html">Test</a>
  6863. <a href="/hi">hi</a>
  6864. </body>
  6865. </html>
  6866. )";
  6867. EXPECT_EQ(body, res->body);
  6868. }
  6869. TEST_F(ServerTest, GetMethodDirTest) {
  6870. auto res = cli_.Get("/dir/test.html");
  6871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6872. EXPECT_EQ(StatusCode::OK_200, res->status);
  6873. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6874. EXPECT_EQ("test.html", res->body);
  6875. }
  6876. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6877. auto res = cli_.Get("/dir/../dir/test.html");
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6880. }
  6881. TEST_F(ServerTest, GetMethodInvalidPath) {
  6882. auto res = cli_.Get("/dir/../test.html");
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6885. }
  6886. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6887. auto res = cli_.Get("/../www/dir/test.html");
  6888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6889. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6890. }
  6891. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6892. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6895. }
  6896. TEST_F(ServerTest, GetMethodDirMountTest) {
  6897. auto res = cli_.Get("/mount/dir/test.html");
  6898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6899. EXPECT_EQ(StatusCode::OK_200, res->status);
  6900. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6901. EXPECT_EQ("test.html", res->body);
  6902. }
  6903. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6904. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6906. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6907. }
  6908. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6909. auto res = cli_.Get("/mount/dir/../test.html");
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6912. }
  6913. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6914. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6916. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6917. }
  6918. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6919. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6922. }
  6923. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6924. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6926. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6927. }
  6928. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6929. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6932. }
  6933. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6934. auto res = cli_.Get("/mount/dir");
  6935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6936. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6937. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6938. }
  6939. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6940. auto res = cli_.Get("//dir");
  6941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6942. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6943. EXPECT_FALSE(res->has_header("Location"));
  6944. }
  6945. TEST_F(ServerTest, PostMethod303) {
  6946. auto res = cli_.Post("/1", "body", "text/plain");
  6947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6948. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6949. EXPECT_EQ("/2", res->get_header_value("Location"));
  6950. }
  6951. TEST_F(ServerTest, PostMethod303Redirect) {
  6952. cli_.set_follow_location(true);
  6953. auto res = cli_.Post("/1", "body", "text/plain");
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. EXPECT_EQ("redirected.", res->body);
  6957. EXPECT_EQ("/2", res->location);
  6958. }
  6959. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6960. auto res = cli_.Get("/dir/test.abcde");
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::OK_200, res->status);
  6963. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6964. EXPECT_EQ("abcde", res->body);
  6965. }
  6966. TEST_F(ServerTest, StaticFileRange) {
  6967. auto res =
  6968. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6971. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6972. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6973. EXPECT_EQ(true, res->has_header("Content-Range"));
  6974. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6975. EXPECT_EQ(std::string("cd"), res->body);
  6976. }
  6977. TEST_F(ServerTest, StaticFileRanges) {
  6978. auto res = cli_.Get("/dir/test.abcde",
  6979. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6982. EXPECT_TRUE(
  6983. res->get_header_value("Content-Type")
  6984. .find(
  6985. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6986. 0);
  6987. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6988. }
  6989. TEST_F(ServerTest, StaticFileRangeHead) {
  6990. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6993. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6994. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6995. EXPECT_EQ(true, res->has_header("Content-Range"));
  6996. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6997. }
  6998. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6999. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7001. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7002. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7003. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7004. EXPECT_EQ(true, res->has_header("Content-Range"));
  7005. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7006. res->get_header_value("Content-Range"));
  7007. EXPECT_EQ("LAST\n", res->body);
  7008. }
  7009. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7010. auto res =
  7011. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7015. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7016. EXPECT_EQ(true, res->has_header("Content-Range"));
  7017. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7018. }
  7019. TEST_F(ServerTest, StaticFileBigFile) {
  7020. auto res = cli_.Get("/dir/1MB.txt");
  7021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7022. EXPECT_EQ(StatusCode::OK_200, res->status);
  7023. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7024. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7025. }
  7026. TEST_F(ServerTest, InvalidBaseDirMount) {
  7027. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7028. }
  7029. TEST_F(ServerTest, Binary) {
  7030. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7031. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7032. "application/octet-stream");
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. ASSERT_EQ(StatusCode::OK_200, res->status);
  7035. ASSERT_EQ(4U, res->body.size());
  7036. res = cli_.Put("/binary", binary.data(), binary.size(),
  7037. "application/octet-stream");
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. ASSERT_EQ(StatusCode::OK_200, res->status);
  7040. ASSERT_EQ(4U, res->body.size());
  7041. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7042. "application/octet-stream");
  7043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7044. ASSERT_EQ(StatusCode::OK_200, res->status);
  7045. ASSERT_EQ(4U, res->body.size());
  7046. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7047. "application/octet-stream");
  7048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7049. ASSERT_EQ(StatusCode::OK_200, res->status);
  7050. ASSERT_EQ(4U, res->body.size());
  7051. }
  7052. TEST_F(ServerTest, BinaryString) {
  7053. auto binary = std::string("\x00\x01\x02\x03", 4);
  7054. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7056. ASSERT_EQ(StatusCode::OK_200, res->status);
  7057. ASSERT_EQ(4U, res->body.size());
  7058. res = cli_.Put("/binary", binary, "application/octet-stream");
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. ASSERT_EQ(StatusCode::OK_200, res->status);
  7061. ASSERT_EQ(4U, res->body.size());
  7062. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7064. ASSERT_EQ(StatusCode::OK_200, res->status);
  7065. ASSERT_EQ(4U, res->body.size());
  7066. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. ASSERT_EQ(StatusCode::OK_200, res->status);
  7069. ASSERT_EQ(4U, res->body.size());
  7070. }
  7071. TEST_F(ServerTest, EmptyRequest) {
  7072. auto res = cli_.Get("");
  7073. ASSERT_TRUE(!res);
  7074. EXPECT_EQ(Error::Connection, res.error());
  7075. }
  7076. TEST_F(ServerTest, LongRequest) {
  7077. std::string request;
  7078. for (size_t i = 0; i < 545; i++) {
  7079. request += "/TooLongRequest";
  7080. }
  7081. request += "OK";
  7082. auto res = cli_.Get(request.c_str());
  7083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7084. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7085. }
  7086. TEST_F(ServerTest, TooLongRequest) {
  7087. std::string request;
  7088. for (size_t i = 0; i < 546; i++) {
  7089. request += "/TooLongRequest";
  7090. }
  7091. request += "_NG";
  7092. auto start = std::chrono::high_resolution_clock::now();
  7093. cli_.set_keep_alive(true);
  7094. auto res = cli_.Get(request.c_str());
  7095. auto end = std::chrono::high_resolution_clock::now();
  7096. auto elapsed =
  7097. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7098. .count();
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7101. EXPECT_LE(elapsed, 1000);
  7102. EXPECT_EQ("close", res->get_header_value("Connection"));
  7103. EXPECT_FALSE(cli_.is_socket_open());
  7104. }
  7105. TEST_F(ServerTest, AlmostTooLongRequest) {
  7106. // test for #2046 - URI length check shouldn't include other content on req
  7107. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7108. // leading /, space, HTTP/1.1)
  7109. std::string request =
  7110. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7111. auto res = cli_.Get(request.c_str());
  7112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7113. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7114. }
  7115. TEST_F(ServerTest, LongHeader) {
  7116. Request req;
  7117. req.method = "GET";
  7118. req.path = "/hi";
  7119. std::string host_and_port;
  7120. host_and_port += HOST;
  7121. host_and_port += ":";
  7122. host_and_port += std::to_string(PORT);
  7123. req.headers.emplace("Host", host_and_port.c_str());
  7124. req.headers.emplace("Accept", "*/*");
  7125. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7126. req.headers.emplace(
  7127. "Header-Name",
  7128. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7129. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7130. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7131. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7132. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7133. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7134. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7135. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7136. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7137. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7138. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7139. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7140. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7156. "@@@@@@@@@@@@@@@@");
  7157. auto res = std::make_shared<Response>();
  7158. auto error = Error::Success;
  7159. auto ret = cli_.send(req, *res, error);
  7160. ASSERT_TRUE(ret);
  7161. EXPECT_EQ(StatusCode::OK_200, res->status);
  7162. }
  7163. TEST_F(ServerTest, LongQueryValue) {
  7164. auto start = std::chrono::high_resolution_clock::now();
  7165. cli_.set_keep_alive(true);
  7166. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7167. auto end = std::chrono::high_resolution_clock::now();
  7168. auto elapsed =
  7169. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7170. .count();
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7173. EXPECT_LE(elapsed, 1000);
  7174. EXPECT_EQ("close", res->get_header_value("Connection"));
  7175. EXPECT_FALSE(cli_.is_socket_open());
  7176. }
  7177. TEST_F(ServerTest, TooLongQueryValue) {
  7178. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7179. ASSERT_FALSE(res);
  7180. EXPECT_EQ(Error::Read, res.error());
  7181. }
  7182. TEST_F(ServerTest, TooLongHeader) {
  7183. Request req;
  7184. req.method = "GET";
  7185. req.path = "/hi";
  7186. std::string host_and_port;
  7187. host_and_port += HOST;
  7188. host_and_port += ":";
  7189. host_and_port += std::to_string(PORT);
  7190. req.headers.emplace("Host", host_and_port.c_str());
  7191. req.headers.emplace("Accept", "*/*");
  7192. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7193. req.headers.emplace(
  7194. "Header-Name",
  7195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7207. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7208. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7209. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7210. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7211. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7212. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7213. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7214. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7215. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7216. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7217. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7218. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7219. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7220. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7221. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7222. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7223. "@@@@@@@@@@@@@@@@@");
  7224. auto res = std::make_shared<Response>();
  7225. auto error = Error::Success;
  7226. auto ret = cli_.send(req, *res, error);
  7227. ASSERT_TRUE(ret);
  7228. EXPECT_EQ(StatusCode::OK_200, res->status);
  7229. }
  7230. TEST_F(ServerTest, HeaderCountAtLimit) {
  7231. // Test with headers just under the 100 limit
  7232. httplib::Headers headers;
  7233. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7234. // This should keep us just under the 100 header limit
  7235. for (int i = 0; i < 95; i++) {
  7236. std::string name = "X-Test-Header-" + std::to_string(i);
  7237. std::string value = "value" + std::to_string(i);
  7238. headers.emplace(name, value);
  7239. }
  7240. // This should work fine as we're under the limit
  7241. auto res = cli_.Get("/hi", headers);
  7242. EXPECT_TRUE(res);
  7243. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7244. }
  7245. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7246. // Test with many headers to exceed the 100 limit
  7247. httplib::Headers headers;
  7248. // Add 150 headers to definitely exceed the 100 limit
  7249. for (int i = 0; i < 150; i++) {
  7250. std::string name = "X-Test-Header-" + std::to_string(i);
  7251. std::string value = "value" + std::to_string(i);
  7252. headers.emplace(name, value);
  7253. }
  7254. // This should fail due to exceeding header count limit
  7255. cli_.set_keep_alive(true);
  7256. auto res = cli_.Get("/hi", headers);
  7257. // The server should respond with 400 Bad Request
  7258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7259. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7260. EXPECT_EQ("close", res->get_header_value("Connection"));
  7261. EXPECT_FALSE(cli_.is_socket_open());
  7262. }
  7263. TEST_F(ServerTest, PercentEncoding) {
  7264. auto res = cli_.Get("/e%6edwith%");
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. EXPECT_EQ(StatusCode::OK_200, res->status);
  7267. }
  7268. TEST_F(ServerTest, PercentEncodingUnicode) {
  7269. auto res = cli_.Get("/e%u006edwith%");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. EXPECT_EQ(StatusCode::OK_200, res->status);
  7272. }
  7273. TEST_F(ServerTest, InvalidPercentEncoding) {
  7274. auto res = cli_.Get("/%endwith%");
  7275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7276. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7277. }
  7278. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7279. auto res = cli_.Get("/%uendwith%");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7282. }
  7283. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7284. auto res = cli_.Get("/hello?aaa=bbb%");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7287. }
  7288. TEST_F(ServerTest, PlusSignEncoding) {
  7289. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::OK_200, res->status);
  7292. EXPECT_EQ("a +b", res->body);
  7293. }
  7294. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7295. // This test simulates a potential DoS attack using many headers
  7296. // to verify our security fix prevents memory exhaustion
  7297. httplib::Headers attack_headers;
  7298. // Attempt to add many headers like an attacker would (200 headers to far
  7299. // exceed limit)
  7300. for (int i = 0; i < 200; i++) {
  7301. std::string name = "X-Attack-Header-" + std::to_string(i);
  7302. std::string value = "attack_payload_" + std::to_string(i);
  7303. attack_headers.emplace(name, value);
  7304. }
  7305. // Try to POST with excessive headers
  7306. cli_.set_keep_alive(true);
  7307. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7308. // Should either fail or return 400 Bad Request due to security limit
  7309. if (res) {
  7310. // If we get a response, it should be 400 Bad Request
  7311. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7312. EXPECT_EQ("close", res->get_header_value("Connection"));
  7313. }
  7314. EXPECT_FALSE(cli_.is_socket_open());
  7315. }
  7316. TEST_F(ServerTest, MultipartFormData) {
  7317. UploadFormDataItems items = {
  7318. {"text1", "text default", "", ""},
  7319. {"text2", "aωb", "", ""},
  7320. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7321. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7322. {"file3", "", "", "application/octet-stream"},
  7323. {"file4", "", "", " application/json tmp-string "}};
  7324. auto res = cli_.Post("/multipart", items);
  7325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7326. EXPECT_EQ(StatusCode::OK_200, res->status);
  7327. }
  7328. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7329. UploadFormDataItems items = {
  7330. {"text", "default text", "", ""},
  7331. {"multi_text1", "aaaaa", "", ""},
  7332. {"multi_text1", "bbbbb", "", ""},
  7333. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7334. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7335. "application/json"},
  7336. };
  7337. auto res = cli_.Post("/multipart/multi_file_values", items);
  7338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7339. EXPECT_EQ(StatusCode::OK_200, res->status);
  7340. }
  7341. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7342. auto res = cli_.Get("/hi");
  7343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7344. EXPECT_EQ(StatusCode::OK_200, res->status);
  7345. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7346. EXPECT_EQ("Hello World!", res->body);
  7347. }
  7348. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7349. Request req;
  7350. req.method = "POST";
  7351. req.path = "/chunked";
  7352. std::string host_and_port;
  7353. host_and_port += HOST;
  7354. host_and_port += ":";
  7355. host_and_port += std::to_string(PORT);
  7356. req.headers.emplace("Host", host_and_port.c_str());
  7357. req.headers.emplace("Accept", "*/*");
  7358. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7359. req.headers.emplace("Content-Type", "text/plain");
  7360. req.headers.emplace("Content-Length", "0");
  7361. req.headers.emplace(
  7362. "Transfer-Encoding",
  7363. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7364. // Client does not chunk, so make a chunked body manually.
  7365. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7366. auto res = std::make_shared<Response>();
  7367. auto error = Error::Success;
  7368. auto ret = cli_.send(req, *res, error);
  7369. ASSERT_TRUE(ret);
  7370. EXPECT_EQ(StatusCode::OK_200, res->status);
  7371. }
  7372. template <typename ClientT>
  7373. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7374. int expected_status) {
  7375. Request req;
  7376. req.method = "POST";
  7377. req.path = "/chunked";
  7378. std::string host_and_port;
  7379. host_and_port += HOST;
  7380. host_and_port += ":";
  7381. host_and_port += std::to_string(PORT);
  7382. req.headers.emplace("Host", host_and_port.c_str());
  7383. req.headers.emplace("Content-Length", "0");
  7384. req.headers.emplace("Transfer-Encoding", "chunked");
  7385. req.body = body;
  7386. auto res = std::make_shared<Response>();
  7387. auto error = Error::Success;
  7388. ASSERT_TRUE(cli.send(req, *res, error));
  7389. EXPECT_EQ(expected_status, res->status);
  7390. }
  7391. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7392. // rather than treat them as valid lengths.
  7393. template <typename ClientT>
  7394. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7395. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7396. }
  7397. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7398. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7399. }
  7400. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7401. expect_chunked_body_rejected(
  7402. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7403. }
  7404. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7405. // chunk-size line carries no CR, LF or other control character ahead of its
  7406. // terminator. Such a line must be refused rather than read as extension text.
  7407. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7408. expect_chunked_body_rejected(
  7409. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7410. }
  7411. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7412. expect_chunked_body_rejected(
  7413. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7414. }
  7415. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7416. expect_chunked_body_rejected(
  7417. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7418. }
  7419. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7420. // The literal stays split: a hex escape consumes every hex digit that
  7421. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7422. expect_chunked_body_rejected(
  7423. cli_, "4;a\x01"
  7424. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7425. }
  7426. // The bytes around chunk data are no payload, so they cannot ride on the
  7427. // payload limit
  7428. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7429. // Small enough that the whole request is sent before the server turns it
  7430. // down, yet past the limit by the last chunks
  7431. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7432. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7433. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7434. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7435. SCOPED_TRACE(size_line.substr(0, 2));
  7436. std::string body;
  7437. for (auto c : std::string("dechunked post body")) {
  7438. body += size_line + "\r\n" + c + "\r\n";
  7439. }
  7440. body += "0\r\n\r\n";
  7441. expect_chunked_body_rejected(cli_, body.c_str());
  7442. }
  7443. }
  7444. TEST_F(ServerTest, AcceptsChunkExtension) {
  7445. expect_chunked_body_status(cli_,
  7446. "4;name=value\r\ndech\r\n"
  7447. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7448. "0;last\r\n\r\n",
  7449. StatusCode::OK_200);
  7450. }
  7451. TEST_F(ServerTest, GetStreamed2) {
  7452. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7455. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7456. EXPECT_EQ(true, res->has_header("Content-Range"));
  7457. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7458. EXPECT_EQ(std::string("ab"), res->body);
  7459. }
  7460. TEST_F(ServerTest, GetStreamed) {
  7461. auto res = cli_.Get("/streamed");
  7462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7463. EXPECT_EQ(StatusCode::OK_200, res->status);
  7464. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7465. EXPECT_EQ(std::string("aaabbb"), res->body);
  7466. }
  7467. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7468. auto res = cli_.Get("/streamed-without-length",
  7469. Headers{make_range_header({{0, -1}})});
  7470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7471. EXPECT_EQ(StatusCode::OK_200, res->status);
  7472. EXPECT_EQ(false, res->has_header("Content-Length"));
  7473. EXPECT_EQ(false, res->has_header("Content-Range"));
  7474. EXPECT_EQ(std::string("abcdefg"), res->body);
  7475. }
  7476. TEST_F(ServerTest, GetStreamedWithRange1) {
  7477. auto res =
  7478. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7480. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7481. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7482. EXPECT_EQ(true, res->has_header("Content-Range"));
  7483. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7484. EXPECT_EQ(std::string("def"), res->body);
  7485. }
  7486. TEST_F(ServerTest, GetStreamedWithRange2) {
  7487. auto res =
  7488. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7491. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7492. EXPECT_EQ(true, res->has_header("Content-Range"));
  7493. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7494. EXPECT_EQ(std::string("bcdefg"), res->body);
  7495. }
  7496. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7497. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7499. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7500. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7501. EXPECT_EQ(true, res->has_header("Content-Range"));
  7502. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7503. EXPECT_EQ(std::string("efg"), res->body);
  7504. }
  7505. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7506. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7507. // the entire representation.
  7508. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7509. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7511. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7512. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7513. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7514. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7515. }
  7516. }
  7517. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7518. auto res =
  7519. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7521. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7522. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7523. EXPECT_EQ(false, res->has_header("Content-Range"));
  7524. EXPECT_EQ(0U, res->body.size());
  7525. }
  7526. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7527. // Only a 206 is served as a partial representation. Under any other status
  7528. // `apply_ranges()` reported the full content length, so the body must match
  7529. // that header, and the content provider must never be asked for an offset
  7530. // outside the representation.
  7531. auto check = [&](int status, const char *range) {
  7532. auto path =
  7533. std::string("/streamed-with-range?status=") + std::to_string(status);
  7534. auto ctx = path + " Range: " + range;
  7535. auto res = cli_.Get(path, Headers{{"Range", range}});
  7536. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7537. EXPECT_EQ(status, res->status) << ctx;
  7538. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7539. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7540. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7541. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7542. };
  7543. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7544. check(403, "bytes=3-5");
  7545. // The offset is far past the representation.
  7546. check(403, "bytes=100000-100200");
  7547. // `first_pos` is still -1 here, and the bounds asserts in
  7548. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7549. check(403, "bytes=-3");
  7550. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7551. // multipart branch would have written one that is empty.
  7552. check(403, "bytes=1-2, 4-5");
  7553. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7554. // covers the whole representation.
  7555. check(200, "bytes=3-5");
  7556. check(200, "bytes=1-2, 4-5");
  7557. }
  7558. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7559. auto res =
  7560. cli_.Get("/streamed-with-range",
  7561. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7562. "92233720368547758079223372036854775807"}});
  7563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7564. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7565. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7566. EXPECT_EQ(false, res->has_header("Content-Range"));
  7567. EXPECT_EQ(0U, res->body.size());
  7568. }
  7569. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7570. auto res = cli_.Get(
  7571. "/with-range",
  7572. Headers{{"Range",
  7573. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7574. {"Accept-Encoding", ""}});
  7575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7576. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7577. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7578. EXPECT_EQ(true, res->has_header("Content-Range"));
  7579. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7580. EXPECT_EQ(std::string("abcdefg"), res->body);
  7581. }
  7582. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7583. auto res = cli_.Get("/with-range", Headers{
  7584. {"Range", "bytes=0-"},
  7585. {"Accept-Encoding", ""},
  7586. });
  7587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7588. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7589. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7590. EXPECT_EQ(true, res->has_header("Content-Range"));
  7591. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7592. EXPECT_EQ(std::string("abcdefg"), res->body);
  7593. }
  7594. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7595. auto res = cli_.Get("/streamed-with-range",
  7596. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7599. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7600. EXPECT_EQ(false, res->has_header("Content-Range"));
  7601. EXPECT_EQ(267U, res->body.size());
  7602. // Check that both range contents are present
  7603. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7604. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7605. // Check that Content-Range headers are present for both ranges
  7606. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7607. std::string::npos);
  7608. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7609. std::string::npos);
  7610. }
  7611. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7612. Ranges ranges;
  7613. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7614. ranges.emplace_back(0, -1);
  7615. }
  7616. auto res = cli_.Get("/streamed-with-range?error",
  7617. Headers{{make_range_header(ranges)}});
  7618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7619. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7620. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7621. EXPECT_EQ(false, res->has_header("Content-Range"));
  7622. EXPECT_EQ(0U, res->body.size());
  7623. }
  7624. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7625. auto res = cli_.Get("/streamed-with-range",
  7626. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7628. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7629. EXPECT_EQ(5U, res->body.size());
  7630. // Check that overlapping ranges are coalesced into a single range
  7631. EXPECT_EQ("bcdef", res->body);
  7632. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7633. // Should be single range, not multipart
  7634. EXPECT_TRUE(res->has_header("Content-Range"));
  7635. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7636. }
  7637. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7638. auto res = cli_.Get("/streamed-with-range",
  7639. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7641. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7642. EXPECT_EQ(268U, res->body.size());
  7643. // Check that both range contents are present
  7644. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7645. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7646. // Check that Content-Range headers are present for both ranges
  7647. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7648. std::string::npos);
  7649. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7650. std::string::npos);
  7651. }
  7652. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7653. auto res = cli_.Get("/streamed-with-range",
  7654. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7657. EXPECT_EQ(269U, res->body.size());
  7658. // Check that both duplicate range contents are present
  7659. size_t first_abc = res->body.find("abc\r\n");
  7660. EXPECT_TRUE(first_abc != std::string::npos);
  7661. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7662. EXPECT_TRUE(second_abc != std::string::npos);
  7663. // Check that Content-Range headers are present for both ranges
  7664. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7665. EXPECT_TRUE(first_range != std::string::npos);
  7666. size_t second_range =
  7667. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7668. EXPECT_TRUE(second_range != std::string::npos);
  7669. }
  7670. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7671. auto res =
  7672. cli_.Get("/streamed-with-range?error",
  7673. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7675. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7676. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7677. EXPECT_EQ(false, res->has_header("Content-Range"));
  7678. EXPECT_EQ(0U, res->body.size());
  7679. }
  7680. TEST_F(ServerTest, GetStreamedEndless) {
  7681. uint64_t offset = 0;
  7682. auto res = cli_.Get("/streamed-cancel",
  7683. [&](const char * /*data*/, uint64_t data_length) {
  7684. if (offset < 100) {
  7685. offset += data_length;
  7686. return true;
  7687. }
  7688. return false;
  7689. });
  7690. ASSERT_TRUE(!res);
  7691. EXPECT_EQ(Error::Canceled, res.error());
  7692. }
  7693. TEST_F(ServerTest, ClientStop) {
  7694. std::atomic_size_t count{4};
  7695. std::vector<std::thread> threads;
  7696. for (auto i = count.load(); i != 0; --i) {
  7697. threads.emplace_back([&]() {
  7698. auto res = cli_.Get("/streamed-cancel",
  7699. [&](const char *, uint64_t) { return true; });
  7700. --count;
  7701. ASSERT_TRUE(!res);
  7702. EXPECT_TRUE(res.error() == Error::Canceled ||
  7703. res.error() == Error::Read || res.error() == Error::Write);
  7704. });
  7705. }
  7706. std::this_thread::sleep_for(std::chrono::seconds(2));
  7707. while (count != 0) {
  7708. cli_.stop();
  7709. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7710. }
  7711. for (auto &t : threads) {
  7712. t.join();
  7713. }
  7714. }
  7715. TEST_F(ServerTest, GetWithRange1) {
  7716. auto res = cli_.Get("/with-range", Headers{
  7717. make_range_header({{3, 5}}),
  7718. {"Accept-Encoding", ""},
  7719. });
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7722. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7723. EXPECT_EQ(true, res->has_header("Content-Range"));
  7724. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7725. EXPECT_EQ(std::string("def"), res->body);
  7726. }
  7727. TEST_F(ServerTest, GetWithRange2) {
  7728. auto res = cli_.Get("/with-range", Headers{
  7729. make_range_header({{1, -1}}),
  7730. {"Accept-Encoding", ""},
  7731. });
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7734. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7735. EXPECT_EQ(true, res->has_header("Content-Range"));
  7736. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7737. EXPECT_EQ(std::string("bcdefg"), res->body);
  7738. }
  7739. TEST_F(ServerTest, GetWithRange3) {
  7740. auto res = cli_.Get("/with-range", Headers{
  7741. make_range_header({{0, 0}}),
  7742. {"Accept-Encoding", ""},
  7743. });
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7746. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7747. EXPECT_EQ(true, res->has_header("Content-Range"));
  7748. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7749. EXPECT_EQ(std::string("a"), res->body);
  7750. }
  7751. TEST_F(ServerTest, GetWithRange4) {
  7752. auto res = cli_.Get("/with-range", Headers{
  7753. make_range_header({{-1, 2}}),
  7754. {"Accept-Encoding", ""},
  7755. });
  7756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7757. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7758. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7759. EXPECT_EQ(true, res->has_header("Content-Range"));
  7760. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7761. EXPECT_EQ(std::string("fg"), res->body);
  7762. }
  7763. TEST_F(ServerTest, GetWithRange5) {
  7764. auto res = cli_.Get("/with-range", Headers{
  7765. make_range_header({{0, 5}}),
  7766. {"Accept-Encoding", ""},
  7767. });
  7768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7769. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7770. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7771. EXPECT_EQ(true, res->has_header("Content-Range"));
  7772. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7773. EXPECT_EQ(std::string("abcdef"), res->body);
  7774. }
  7775. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7776. auto res =
  7777. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7779. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7780. }
  7781. TEST_F(ServerTest, GetWithRangeMultipart) {
  7782. auto res =
  7783. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7785. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7786. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7787. EXPECT_EQ(false, res->has_header("Content-Range"));
  7788. EXPECT_EQ(267U, res->body.size());
  7789. }
  7790. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7791. auto res = cli_.Get("/with-range",
  7792. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7795. }
  7796. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7797. auto res = cli_.Get("/with-range-customized-response",
  7798. Headers{{make_range_header({{1, 2}})}});
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7801. EXPECT_EQ(true, res->has_header("Content-Length"));
  7802. EXPECT_EQ(false, res->has_header("Content-Range"));
  7803. EXPECT_EQ(JSON_DATA, res->body);
  7804. }
  7805. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7806. auto res = cli_.Get("/with-range-customized-response",
  7807. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7810. EXPECT_EQ(true, res->has_header("Content-Length"));
  7811. EXPECT_EQ(false, res->has_header("Content-Range"));
  7812. EXPECT_EQ(JSON_DATA, res->body);
  7813. }
  7814. TEST_F(ServerTest, Issue1772) {
  7815. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7817. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7818. }
  7819. TEST_F(ServerTest, Issue609) {
  7820. auto res = cli_.Delete("/issue609");
  7821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7822. EXPECT_EQ(StatusCode::OK_200, res->status);
  7823. EXPECT_EQ(std::string("ok"), res->body);
  7824. }
  7825. TEST_F(ServerTest, GetStreamedChunked) {
  7826. auto res = cli_.Get("/streamed-chunked");
  7827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7828. EXPECT_EQ(StatusCode::OK_200, res->status);
  7829. EXPECT_EQ(std::string("123456789"), res->body);
  7830. }
  7831. TEST_F(ServerTest, GetStreamedChunked2) {
  7832. auto res = cli_.Get("/streamed-chunked2");
  7833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7834. EXPECT_EQ(StatusCode::OK_200, res->status);
  7835. EXPECT_EQ(std::string("123456789"), res->body);
  7836. }
  7837. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7838. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::OK_200, res->status);
  7841. EXPECT_EQ(std::string("123456789"), res->body);
  7842. EXPECT_TRUE(res->has_header("Trailer"));
  7843. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7844. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7845. // Trailers are now stored separately from headers (security fix)
  7846. EXPECT_EQ(2U, res->trailers.size());
  7847. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7848. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7849. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7850. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7851. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7852. // Verify trailers are NOT in headers (security verification)
  7853. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7854. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7855. }
  7856. TEST_F(ServerTest, LargeChunkedPost) {
  7857. Request req;
  7858. req.method = "POST";
  7859. req.path = "/large-chunked";
  7860. std::string host_and_port;
  7861. host_and_port += HOST;
  7862. host_and_port += ":";
  7863. host_and_port += std::to_string(PORT);
  7864. req.headers.emplace("Host", host_and_port.c_str());
  7865. req.headers.emplace("Accept", "*/*");
  7866. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7867. req.headers.emplace("Content-Type", "text/plain");
  7868. req.headers.emplace("Content-Length", "0");
  7869. req.headers.emplace("Transfer-Encoding", "chunked");
  7870. std::string long_string(30 * 1024u, 'a');
  7871. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7872. // Attempt to make a large enough post to exceed OS buffers, to test that
  7873. // the server handles short reads if the full chunk data isn't available.
  7874. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7875. auto res = std::make_shared<Response>();
  7876. auto error = Error::Success;
  7877. auto ret = cli_.send(req, *res, error);
  7878. ASSERT_TRUE(ret);
  7879. EXPECT_EQ(StatusCode::OK_200, res->status);
  7880. }
  7881. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7882. auto res = cli_.Get("/remote_addr");
  7883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7884. EXPECT_EQ(StatusCode::OK_200, res->status);
  7885. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7886. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7887. }
  7888. TEST_F(ServerTest, GetMethodLocalAddr) {
  7889. auto res = cli_.Get("/local_addr");
  7890. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7891. EXPECT_EQ(StatusCode::OK_200, res->status);
  7892. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7893. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7894. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7895. }
  7896. TEST_F(ServerTest, HTTPResponseSplitting) {
  7897. auto res = cli_.Get("/http_response_splitting");
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. }
  7901. TEST_F(ServerTest, SlowRequest) {
  7902. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7903. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7904. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7905. }
  7906. #if 0
  7907. TEST_F(ServerTest, SlowPost) {
  7908. char buffer[64 * 1024];
  7909. memset(buffer, 0x42, sizeof(buffer));
  7910. auto res = cli_.Post(
  7911. "/slowpost", 64 * 1024 * 1024,
  7912. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7913. auto ret = sink.write(buffer, sizeof(buffer));
  7914. EXPECT_TRUE(ret);
  7915. return true;
  7916. },
  7917. "text/plain");
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. }
  7921. TEST_F(ServerTest, SlowPostFail) {
  7922. char buffer[64 * 1024];
  7923. memset(buffer, 0x42, sizeof(buffer));
  7924. cli_.set_write_timeout(std::chrono::seconds(0));
  7925. auto res = cli_.Post(
  7926. "/slowpost", 64 * 1024 * 1024,
  7927. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7928. sink.write(buffer, sizeof(buffer));
  7929. return true;
  7930. },
  7931. "text/plain");
  7932. ASSERT_TRUE(!res);
  7933. EXPECT_EQ(Error::Write, res.error());
  7934. }
  7935. #endif
  7936. TEST_F(ServerTest, Put) {
  7937. auto res = cli_.Put("/put", "PUT", "text/plain");
  7938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7939. EXPECT_EQ(StatusCode::OK_200, res->status);
  7940. EXPECT_EQ("PUT", res->body);
  7941. }
  7942. TEST_F(ServerTest, PutWithContentProvider) {
  7943. auto res = cli_.Put(
  7944. "/put", 3,
  7945. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7946. sink.os << "PUT";
  7947. return true;
  7948. },
  7949. "text/plain");
  7950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7951. EXPECT_EQ(StatusCode::OK_200, res->status);
  7952. EXPECT_EQ("PUT", res->body);
  7953. }
  7954. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7955. auto res = cli_.Post(
  7956. "/post", 42,
  7957. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7958. return false;
  7959. },
  7960. "text/plain");
  7961. ASSERT_TRUE(!res);
  7962. EXPECT_EQ(Error::Canceled, res.error());
  7963. }
  7964. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7965. auto res = cli_.Put(
  7966. "/put",
  7967. [](size_t /*offset*/, DataSink &sink) {
  7968. sink.os << "PUT";
  7969. sink.done();
  7970. return true;
  7971. },
  7972. "text/plain");
  7973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7974. EXPECT_EQ(StatusCode::OK_200, res->status);
  7975. EXPECT_EQ("PUT", res->body);
  7976. }
  7977. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7978. auto res = cli_.Post(
  7979. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7980. "text/plain");
  7981. ASSERT_TRUE(!res);
  7982. EXPECT_EQ(Error::Canceled, res.error());
  7983. }
  7984. TEST_F(ServerTest, PostLoopBack) {
  7985. std::string body;
  7986. auto res = cli_.Post(
  7987. "/post-loopback", 9,
  7988. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7989. EXPECT_EQ(9u, length);
  7990. sink.write("123", 3);
  7991. sink.write("456", 3);
  7992. sink.write("789", 3);
  7993. return true;
  7994. },
  7995. "text/plain",
  7996. [&body](const char *data, size_t data_length) {
  7997. body.append(data, data_length);
  7998. return true;
  7999. });
  8000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8001. EXPECT_EQ(StatusCode::OK_200, res->status);
  8002. EXPECT_EQ("123456789", body);
  8003. }
  8004. TEST_F(ServerTest, PutLoopBack) {
  8005. std::string body;
  8006. auto res = cli_.Put(
  8007. "/put-loopback", 9,
  8008. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8009. EXPECT_EQ(9u, length);
  8010. sink.write("123", 3);
  8011. sink.write("456", 3);
  8012. sink.write("789", 3);
  8013. return true;
  8014. },
  8015. "text/plain",
  8016. [&body](const char *data, size_t data_length) {
  8017. body.append(data, data_length);
  8018. return true;
  8019. });
  8020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8021. EXPECT_EQ(StatusCode::OK_200, res->status);
  8022. EXPECT_EQ("123456789", body);
  8023. }
  8024. TEST_F(ServerTest, PatchLoopBack) {
  8025. std::string body;
  8026. auto res = cli_.Patch(
  8027. "/patch-loopback", 9,
  8028. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8029. EXPECT_EQ(9u, length);
  8030. sink.write("123", 3);
  8031. sink.write("456", 3);
  8032. sink.write("789", 3);
  8033. return true;
  8034. },
  8035. "text/plain",
  8036. [&body](const char *data, size_t data_length) {
  8037. body.append(data, data_length);
  8038. return true;
  8039. });
  8040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8041. EXPECT_EQ(StatusCode::OK_200, res->status);
  8042. EXPECT_EQ("123456789", body);
  8043. }
  8044. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8045. std::string body;
  8046. auto res = cli_.Post(
  8047. "/post-loopback",
  8048. [](size_t /*offset*/, DataSink &sink) {
  8049. sink.write("123", 3);
  8050. sink.write("456", 3);
  8051. sink.write("789", 3);
  8052. sink.done();
  8053. return true;
  8054. },
  8055. "text/plain",
  8056. [&body](const char *data, size_t data_length) {
  8057. body.append(data, data_length);
  8058. return true;
  8059. });
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. EXPECT_EQ("123456789", body);
  8063. }
  8064. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8065. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8066. cli_.set_compress(true);
  8067. auto res = cli_.Put(
  8068. "/put", 3,
  8069. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8070. sink.os << "PUT";
  8071. return true;
  8072. },
  8073. "text/plain");
  8074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8075. EXPECT_EQ(StatusCode::OK_200, res->status);
  8076. EXPECT_EQ("PUT", res->body);
  8077. }
  8078. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8079. cli_.set_compress(true);
  8080. auto res = cli_.Post(
  8081. "/post", 42,
  8082. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8083. return false;
  8084. },
  8085. "text/plain");
  8086. ASSERT_TRUE(!res);
  8087. EXPECT_EQ(Error::Canceled, res.error());
  8088. }
  8089. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8090. cli_.set_compress(true);
  8091. auto res = cli_.Put(
  8092. "/put",
  8093. [](size_t /*offset*/, DataSink &sink) {
  8094. sink.os << "PUT";
  8095. sink.done();
  8096. return true;
  8097. },
  8098. "text/plain");
  8099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8100. EXPECT_EQ(StatusCode::OK_200, res->status);
  8101. EXPECT_EQ("PUT", res->body);
  8102. }
  8103. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8104. cli_.set_compress(true);
  8105. auto res = cli_.Post(
  8106. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8107. "text/plain");
  8108. ASSERT_TRUE(!res);
  8109. EXPECT_EQ(Error::Canceled, res.error());
  8110. }
  8111. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8112. cli_.set_compress(true);
  8113. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8115. EXPECT_EQ(StatusCode::OK_200, res->status);
  8116. EXPECT_EQ(LARGE_DATA, res->body);
  8117. }
  8118. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8119. #ifdef CPPHTTPLIB_SSL_ENABLED
  8120. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8121. Client cli(s.c_str());
  8122. cli.enable_server_certificate_verification(false);
  8123. #else
  8124. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8125. Client cli(s.c_str());
  8126. #endif
  8127. cli.set_compress(true);
  8128. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8130. EXPECT_EQ(StatusCode::OK_200, res->status);
  8131. EXPECT_EQ(LARGE_DATA, res->body);
  8132. // The compressed size should be less than a 10th of the original. May vary
  8133. // depending on the zlib library.
  8134. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8135. static_cast<uint64_t>(10 * 1024 * 1024));
  8136. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8137. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8138. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8139. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8140. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8141. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8142. #endif
  8143. }
  8144. TEST_F(ServerTest, PutContentWithDeflate) {
  8145. cli_.set_compress(false);
  8146. Headers headers;
  8147. headers.emplace("Content-Encoding", "deflate");
  8148. // PUT in deflate format:
  8149. auto res = cli_.Put("/put", headers,
  8150. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8152. EXPECT_EQ(StatusCode::OK_200, res->status);
  8153. EXPECT_EQ("PUT", res->body);
  8154. }
  8155. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8156. Headers headers;
  8157. headers.emplace("Accept-Encoding", "gzip, deflate");
  8158. auto res = cli_.Get("/streamed-chunked", headers);
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::OK_200, res->status);
  8161. EXPECT_EQ(std::string("123456789"), res->body);
  8162. }
  8163. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8164. Headers headers;
  8165. headers.emplace("Accept-Encoding", "gzip, deflate");
  8166. auto res = cli_.Get("/streamed-chunked2", headers);
  8167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8168. EXPECT_EQ(StatusCode::OK_200, res->status);
  8169. EXPECT_EQ(std::string("123456789"), res->body);
  8170. }
  8171. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8172. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8174. EXPECT_EQ(StatusCode::OK_200, res->status);
  8175. }
  8176. TEST(GzipDecompressor, ChunkedDecompression) {
  8177. std::string data;
  8178. for (size_t i = 0; i < 32 * 1024; ++i) {
  8179. data.push_back(static_cast<char>('a' + i % 26));
  8180. }
  8181. std::string compressed_data;
  8182. {
  8183. httplib::detail::gzip_compressor compressor;
  8184. bool result = compressor.compress(
  8185. data.data(), data.size(),
  8186. /*last=*/true,
  8187. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8188. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8189. compressed_data_size);
  8190. return true;
  8191. });
  8192. ASSERT_TRUE(result);
  8193. }
  8194. std::string decompressed_data;
  8195. {
  8196. httplib::detail::gzip_decompressor decompressor;
  8197. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8198. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8199. size_t chunk_size = 130;
  8200. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8201. chunk_begin += chunk_size) {
  8202. size_t current_chunk_size =
  8203. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8204. bool result = decompressor.decompress(
  8205. compressed_data.data() + chunk_begin, current_chunk_size,
  8206. [&](const char *decompressed_data_chunk,
  8207. size_t decompressed_data_chunk_size) {
  8208. decompressed_data.insert(decompressed_data.size(),
  8209. decompressed_data_chunk,
  8210. decompressed_data_chunk_size);
  8211. return true;
  8212. });
  8213. ASSERT_TRUE(result);
  8214. }
  8215. }
  8216. ASSERT_EQ(data, decompressed_data);
  8217. }
  8218. TEST(GzipDecompressor, DeflateDecompression) {
  8219. std::string original_text = "Raw deflate without gzip";
  8220. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8221. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8222. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8223. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8224. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8225. std::string decompressed_data;
  8226. {
  8227. httplib::detail::gzip_decompressor decompressor;
  8228. bool result = decompressor.decompress(
  8229. compressed_data.data(), compressed_data.size(),
  8230. [&](const char *decompressed_data_chunk,
  8231. size_t decompressed_data_chunk_size) {
  8232. decompressed_data.insert(decompressed_data.size(),
  8233. decompressed_data_chunk,
  8234. decompressed_data_chunk_size);
  8235. return true;
  8236. });
  8237. ASSERT_TRUE(result);
  8238. }
  8239. ASSERT_EQ(original_text, decompressed_data);
  8240. }
  8241. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8242. std::string original_text = "Raw deflate without gzip";
  8243. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8244. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8245. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8246. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8247. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8248. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8249. std::string decompressed_data;
  8250. {
  8251. httplib::detail::gzip_decompressor decompressor;
  8252. bool result = decompressor.decompress(
  8253. compressed_data.data(), compressed_data.size(),
  8254. [&](const char *decompressed_data_chunk,
  8255. size_t decompressed_data_chunk_size) {
  8256. decompressed_data.insert(decompressed_data.size(),
  8257. decompressed_data_chunk,
  8258. decompressed_data_chunk_size);
  8259. return true;
  8260. });
  8261. ASSERT_TRUE(result);
  8262. }
  8263. ASSERT_EQ(original_text, decompressed_data);
  8264. }
  8265. #endif
  8266. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8267. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8268. Headers headers;
  8269. headers.emplace("Accept-Encoding", "br");
  8270. auto res = cli_.Get("/streamed-chunked", headers);
  8271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8272. EXPECT_EQ(StatusCode::OK_200, res->status);
  8273. EXPECT_EQ(std::string("123456789"), res->body);
  8274. }
  8275. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8276. Headers headers;
  8277. headers.emplace("Accept-Encoding", "br");
  8278. auto res = cli_.Get("/streamed-chunked2", headers);
  8279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8280. EXPECT_EQ(StatusCode::OK_200, res->status);
  8281. EXPECT_EQ(std::string("123456789"), res->body);
  8282. }
  8283. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8284. cli_.set_compress(true);
  8285. auto res = cli_.Put(
  8286. "/put", 3,
  8287. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8288. sink.os << "PUT";
  8289. return true;
  8290. },
  8291. "text/plain");
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::OK_200, res->status);
  8294. EXPECT_EQ("PUT", res->body);
  8295. }
  8296. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8297. cli_.set_compress(true);
  8298. auto res = cli_.Put(
  8299. "/put",
  8300. [](size_t /*offset*/, DataSink &sink) {
  8301. sink.os << "PUT";
  8302. sink.done();
  8303. return true;
  8304. },
  8305. "text/plain");
  8306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8307. EXPECT_EQ(StatusCode::OK_200, res->status);
  8308. EXPECT_EQ("PUT", res->body);
  8309. }
  8310. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8311. cli_.set_compress(true);
  8312. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ(StatusCode::OK_200, res->status);
  8315. EXPECT_EQ(LARGE_DATA, res->body);
  8316. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8317. }
  8318. #endif
  8319. TEST_F(ServerTest, Patch) {
  8320. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8322. EXPECT_EQ(StatusCode::OK_200, res->status);
  8323. EXPECT_EQ("PATCH", res->body);
  8324. }
  8325. TEST_F(ServerTest, Delete) {
  8326. auto res = cli_.Delete("/delete");
  8327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8328. EXPECT_EQ(StatusCode::OK_200, res->status);
  8329. EXPECT_EQ("DELETE", res->body);
  8330. }
  8331. TEST_F(ServerTest, DeleteContentReceiver) {
  8332. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8334. EXPECT_EQ(StatusCode::OK_200, res->status);
  8335. EXPECT_EQ("content", res->body);
  8336. }
  8337. TEST_F(ServerTest, Options) {
  8338. auto res = cli_.Options("*");
  8339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8340. EXPECT_EQ(StatusCode::OK_200, res->status);
  8341. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8342. EXPECT_TRUE(res->body.empty());
  8343. }
  8344. TEST_F(ServerTest, URL) {
  8345. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8347. EXPECT_EQ(StatusCode::OK_200, res->status);
  8348. }
  8349. TEST_F(ServerTest, ArrayParam) {
  8350. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8352. EXPECT_EQ(StatusCode::OK_200, res->status);
  8353. }
  8354. TEST_F(ServerTest, ArrayParamValues) {
  8355. auto res =
  8356. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ(StatusCode::OK_200, res->status);
  8359. }
  8360. TEST_F(ServerTest, NoMultipleHeaders) {
  8361. Headers headers = {{"Content-Length", "5"}};
  8362. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8363. "text/plain");
  8364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8365. EXPECT_EQ(StatusCode::OK_200, res->status);
  8366. }
  8367. TEST_F(ServerTest, PostContentReceiver) {
  8368. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. ASSERT_EQ(StatusCode::OK_200, res->status);
  8371. ASSERT_EQ("content", res->body);
  8372. }
  8373. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8374. UploadFormDataItems items = {
  8375. {"text1", "text default", "", ""},
  8376. {"text2", "aωb", "", ""},
  8377. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8378. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8379. {"file3", "", "", "application/octet-stream"},
  8380. };
  8381. auto res = cli_.Post("/content_receiver", items);
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ(StatusCode::OK_200, res->status);
  8384. }
  8385. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8386. UploadFormDataItems items = {
  8387. {"text1", "text default", "", ""},
  8388. {"text2", "aωb", "", ""},
  8389. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8390. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8391. {"file3", "", "", "application/octet-stream"},
  8392. };
  8393. auto boundary = std::string("+++++");
  8394. std::string body;
  8395. for (const auto &item : items) {
  8396. body += "--" + boundary + "\r\n";
  8397. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8398. if (!item.filename.empty()) {
  8399. body += "; filename=\"" + item.filename + "\"";
  8400. }
  8401. body += "\r\n";
  8402. if (!item.content_type.empty()) {
  8403. body += "Content-Type: " + item.content_type + "\r\n";
  8404. }
  8405. body += "\r\n";
  8406. body += item.content + "\r\n";
  8407. }
  8408. body += "--" + boundary + "--\r\n";
  8409. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8410. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. }
  8414. TEST(MultipartFormDataTest, FieldEscaping) {
  8415. Server svr;
  8416. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8417. const ContentReader &content_reader) {
  8418. ASSERT_TRUE(req.is_multipart_form_data());
  8419. std::vector<FormData> received;
  8420. content_reader(
  8421. [&](const FormData &file) {
  8422. received.push_back(file);
  8423. return true;
  8424. },
  8425. [&](const char *data, size_t data_length) {
  8426. received.back().content.append(data, data_length);
  8427. return true;
  8428. });
  8429. // '"', CR and LF in names and filenames are escaped following the
  8430. // WHATWG HTML standard, so each part still parses as a single part
  8431. // with no injected headers. Content types get CR/LF escaped too,
  8432. // while '"' (legal there, e.g. quoted charset) is preserved.
  8433. ASSERT_EQ(4U, received.size());
  8434. EXPECT_EQ("na%22me", received[0].name);
  8435. EXPECT_EQ("quoted name", received[0].content);
  8436. EXPECT_EQ("file", received[1].name);
  8437. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8438. received[1].filename);
  8439. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8440. EXPECT_EQ("injected", received[1].content);
  8441. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8442. EXPECT_EQ("my%22file.txt", received[2].filename);
  8443. EXPECT_EQ("cr lf name", received[2].content);
  8444. EXPECT_EQ("typed", received[3].name);
  8445. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8446. received[3].content_type);
  8447. EXPECT_EQ("typed content", received[3].content);
  8448. });
  8449. auto port = svr.bind_to_any_port("localhost");
  8450. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8451. auto se = detail::scope_exit([&] {
  8452. svr.stop();
  8453. t.join();
  8454. ASSERT_FALSE(svr.is_running());
  8455. });
  8456. svr.wait_until_ready();
  8457. Client cli("localhost", port);
  8458. UploadFormDataItems items = {
  8459. {"na\"me", "quoted name", "", ""},
  8460. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8461. "application/octet-stream"},
  8462. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8463. {"typed", "typed content", "",
  8464. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8465. };
  8466. auto res = cli.Post("/post", items);
  8467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8468. EXPECT_EQ(StatusCode::OK_200, res->status);
  8469. }
  8470. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8471. const UploadFormDataItems items = {
  8472. {"name1", "Content 1", "", ""},
  8473. {"name2", "Content 2", "file2.txt", "text/plain"},
  8474. };
  8475. Server svr;
  8476. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8477. const ContentReader &content_reader) {
  8478. ASSERT_TRUE(req.is_multipart_form_data());
  8479. std::vector<FormData> received;
  8480. content_reader(
  8481. [&](const FormData &file) {
  8482. received.push_back(file);
  8483. return true;
  8484. },
  8485. [&](const char *data, size_t data_length) {
  8486. received.back().content.append(data, data_length);
  8487. return true;
  8488. });
  8489. ASSERT_EQ(2U, received.size());
  8490. EXPECT_EQ("name1", received[0].name);
  8491. EXPECT_EQ("Content 1", received[0].content);
  8492. EXPECT_EQ("name2", received[1].name);
  8493. EXPECT_EQ("Content 2", received[1].content);
  8494. EXPECT_EQ("file2.txt", received[1].filename);
  8495. EXPECT_EQ("text/plain", received[1].content_type);
  8496. });
  8497. auto port = svr.bind_to_any_port("localhost");
  8498. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8499. auto se = detail::scope_exit([&] {
  8500. svr.stop();
  8501. t.join();
  8502. ASSERT_FALSE(svr.is_running());
  8503. });
  8504. svr.wait_until_ready();
  8505. Client cli("localhost", port);
  8506. // Whole-body serialization with a generated boundary
  8507. {
  8508. MultipartFormDataWriter writer;
  8509. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8510. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8511. writer.content_type());
  8512. auto body = writer.serialize(items);
  8513. EXPECT_EQ(body.size(), writer.content_length(items));
  8514. auto res = cli.Post("/post", body, writer.content_type());
  8515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8516. EXPECT_EQ(StatusCode::OK_200, res->status);
  8517. }
  8518. // Per-part framing with a custom boundary via a content provider
  8519. {
  8520. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8521. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8522. MultipartFormDataWriter writer("custom-boundary_123");
  8523. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8524. std::string body;
  8525. for (const auto &item : items) {
  8526. body += writer.item_begin(item);
  8527. body += item.content;
  8528. body += MultipartFormDataWriter::item_end();
  8529. }
  8530. body += writer.finish();
  8531. EXPECT_EQ(body.size(), writer.content_length(items));
  8532. auto res = cli.Post(
  8533. "/post", body.size(),
  8534. [&](size_t offset, size_t length, DataSink &sink) {
  8535. sink.write(body.data() + offset, length);
  8536. return true;
  8537. },
  8538. writer.content_type());
  8539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8540. EXPECT_EQ(StatusCode::OK_200, res->status);
  8541. }
  8542. }
  8543. TEST_F(ServerTest, PostContentReceiverGzip) {
  8544. cli_.set_compress(true);
  8545. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8547. ASSERT_EQ(StatusCode::OK_200, res->status);
  8548. ASSERT_EQ("content", res->body);
  8549. }
  8550. TEST_F(ServerTest, PutContentReceiver) {
  8551. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8553. ASSERT_EQ(StatusCode::OK_200, res->status);
  8554. ASSERT_EQ("content", res->body);
  8555. }
  8556. TEST_F(ServerTest, PatchContentReceiver) {
  8557. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8559. ASSERT_EQ(StatusCode::OK_200, res->status);
  8560. ASSERT_EQ("content", res->body);
  8561. }
  8562. template <typename ClientType>
  8563. void TestWithHeadersAndContentReceiver(
  8564. ClientType &cli,
  8565. std::function<Result(ClientType &, const std::string &, const Headers &,
  8566. const std::string &, const std::string &,
  8567. ContentReceiver, DownloadProgress)>
  8568. request_func) {
  8569. Headers headers;
  8570. headers.emplace("X-Custom-Header", "test-value");
  8571. std::string received_body;
  8572. auto res = request_func(
  8573. cli, "/content_receiver", headers, "content", "application/json",
  8574. [&](const char *data, size_t data_length) {
  8575. received_body.append(data, data_length);
  8576. return true;
  8577. },
  8578. nullptr);
  8579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8580. EXPECT_EQ(StatusCode::OK_200, res->status);
  8581. EXPECT_EQ("content", received_body);
  8582. }
  8583. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8584. #ifdef CPPHTTPLIB_SSL_ENABLED
  8585. using ClientT = SSLClient;
  8586. #else
  8587. using ClientT = Client;
  8588. #endif
  8589. TestWithHeadersAndContentReceiver<ClientT>(
  8590. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8591. const std::string &body, const std::string &content_type,
  8592. ContentReceiver receiver, DownloadProgress progress) {
  8593. return cli.Post(path, headers, body, content_type, receiver, progress);
  8594. });
  8595. }
  8596. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8597. #ifdef CPPHTTPLIB_SSL_ENABLED
  8598. using ClientT = SSLClient;
  8599. #else
  8600. using ClientT = Client;
  8601. #endif
  8602. TestWithHeadersAndContentReceiver<ClientT>(
  8603. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8604. const std::string &body, const std::string &content_type,
  8605. ContentReceiver receiver, DownloadProgress progress) {
  8606. return cli.Put(path, headers, body, content_type, receiver, progress);
  8607. });
  8608. }
  8609. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8610. #ifdef CPPHTTPLIB_SSL_ENABLED
  8611. using ClientT = SSLClient;
  8612. #else
  8613. using ClientT = Client;
  8614. #endif
  8615. TestWithHeadersAndContentReceiver<ClientT>(
  8616. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8617. const std::string &body, const std::string &content_type,
  8618. ContentReceiver receiver, DownloadProgress progress) {
  8619. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8620. });
  8621. }
  8622. template <typename ClientType>
  8623. void TestWithHeadersAndContentReceiverWithProgress(
  8624. ClientType &cli,
  8625. std::function<Result(ClientType &, const std::string &, const Headers &,
  8626. const std::string &, const std::string &,
  8627. ContentReceiver, DownloadProgress)>
  8628. request_func) {
  8629. Headers headers;
  8630. headers.emplace("X-Test-Header", "progress-test");
  8631. std::string received_body;
  8632. auto progress_called = false;
  8633. auto res = request_func(
  8634. cli, "/content_receiver", headers, "content", "text/plain",
  8635. [&](const char *data, size_t data_length) {
  8636. received_body.append(data, data_length);
  8637. return true;
  8638. },
  8639. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8640. progress_called = true;
  8641. return true;
  8642. });
  8643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8644. EXPECT_EQ(StatusCode::OK_200, res->status);
  8645. EXPECT_EQ("content", received_body);
  8646. EXPECT_TRUE(progress_called);
  8647. }
  8648. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8649. #ifdef CPPHTTPLIB_SSL_ENABLED
  8650. using ClientT = SSLClient;
  8651. #else
  8652. using ClientT = Client;
  8653. #endif
  8654. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8655. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8656. const std::string &body, const std::string &content_type,
  8657. ContentReceiver receiver, DownloadProgress progress) {
  8658. return cli.Post(path, headers, body, content_type, receiver, progress);
  8659. });
  8660. }
  8661. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8662. #ifdef CPPHTTPLIB_SSL_ENABLED
  8663. using ClientT = SSLClient;
  8664. #else
  8665. using ClientT = Client;
  8666. #endif
  8667. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8668. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8669. const std::string &body, const std::string &content_type,
  8670. ContentReceiver receiver, DownloadProgress progress) {
  8671. return cli.Put(path, headers, body, content_type, receiver, progress);
  8672. });
  8673. }
  8674. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8675. #ifdef CPPHTTPLIB_SSL_ENABLED
  8676. using ClientT = SSLClient;
  8677. #else
  8678. using ClientT = Client;
  8679. #endif
  8680. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8681. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8682. const std::string &body, const std::string &content_type,
  8683. ContentReceiver receiver, DownloadProgress progress) {
  8684. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8685. });
  8686. }
  8687. template <typename ClientType>
  8688. void TestWithHeadersAndContentReceiverError(
  8689. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8690. const Headers &, const std::string &,
  8691. const std::string &, ContentReceiver)>
  8692. request_func) {
  8693. Headers headers;
  8694. headers.emplace("X-Error-Test", "true");
  8695. std::string received_body;
  8696. auto receiver_failed = false;
  8697. auto res =
  8698. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8699. [&](const char *data, size_t data_length) {
  8700. received_body.append(data, data_length);
  8701. receiver_failed = true;
  8702. return false;
  8703. });
  8704. ASSERT_FALSE(res);
  8705. EXPECT_TRUE(receiver_failed);
  8706. }
  8707. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8708. #ifdef CPPHTTPLIB_SSL_ENABLED
  8709. using ClientT = SSLClient;
  8710. #else
  8711. using ClientT = Client;
  8712. #endif
  8713. TestWithHeadersAndContentReceiverError<ClientT>(
  8714. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8715. const std::string &body, const std::string &content_type,
  8716. ContentReceiver receiver) {
  8717. return cli.Post(path, headers, body, content_type, receiver);
  8718. });
  8719. }
  8720. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8721. #ifdef CPPHTTPLIB_SSL_ENABLED
  8722. using ClientT = SSLClient;
  8723. #else
  8724. using ClientT = Client;
  8725. #endif
  8726. TestWithHeadersAndContentReceiverError<ClientT>(
  8727. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8728. const std::string &body, const std::string &content_type,
  8729. ContentReceiver receiver) {
  8730. return cli.Put(path, headers, body, content_type, receiver);
  8731. });
  8732. }
  8733. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8734. #ifdef CPPHTTPLIB_SSL_ENABLED
  8735. using ClientT = SSLClient;
  8736. #else
  8737. using ClientT = Client;
  8738. #endif
  8739. TestWithHeadersAndContentReceiverError<ClientT>(
  8740. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8741. const std::string &body, const std::string &content_type,
  8742. ContentReceiver receiver) {
  8743. return cli.Patch(path, headers, body, content_type, receiver);
  8744. });
  8745. }
  8746. TEST_F(ServerTest, PostQueryStringAndBody) {
  8747. auto res =
  8748. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8750. ASSERT_EQ(StatusCode::OK_200, res->status);
  8751. }
  8752. TEST_F(ServerTest, HTTP2Magic) {
  8753. Request req;
  8754. req.method = "PRI";
  8755. req.path = "*";
  8756. req.body = "SM";
  8757. auto res = std::make_shared<Response>();
  8758. auto error = Error::Success;
  8759. auto ret = cli_.send(req, *res, error);
  8760. ASSERT_TRUE(ret);
  8761. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8762. }
  8763. TEST_F(ServerTest, KeepAlive) {
  8764. auto res = cli_.Get("/hi");
  8765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8766. EXPECT_EQ(StatusCode::OK_200, res->status);
  8767. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8768. EXPECT_EQ("Hello World!", res->body);
  8769. res = cli_.Get("/hi");
  8770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8771. EXPECT_EQ(StatusCode::OK_200, res->status);
  8772. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8773. EXPECT_EQ("Hello World!", res->body);
  8774. res = cli_.Get("/hi");
  8775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8776. EXPECT_EQ(StatusCode::OK_200, res->status);
  8777. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8778. EXPECT_EQ("Hello World!", res->body);
  8779. res = cli_.Get("/not-exist");
  8780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8781. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8782. res = cli_.Post("/empty", "", "text/plain");
  8783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8784. EXPECT_EQ(StatusCode::OK_200, res->status);
  8785. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8786. EXPECT_EQ("empty", res->body);
  8787. EXPECT_EQ("close", res->get_header_value("Connection"));
  8788. res = cli_.Post(
  8789. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8790. "text/plain");
  8791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8792. EXPECT_EQ(StatusCode::OK_200, res->status);
  8793. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8794. EXPECT_EQ("empty", res->body);
  8795. cli_.set_keep_alive(false);
  8796. res = cli_.Get("/last-request");
  8797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8798. EXPECT_EQ(StatusCode::OK_200, res->status);
  8799. EXPECT_EQ("close", res->get_header_value("Connection"));
  8800. }
  8801. TEST_F(ServerTest, TooManyRedirect) {
  8802. cli_.set_follow_location(true);
  8803. auto res = cli_.Get("/redirect/0");
  8804. ASSERT_TRUE(!res);
  8805. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8806. }
  8807. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8808. Request req;
  8809. req.method = "FOOBAR";
  8810. req.path = "/hi";
  8811. cli_.set_keep_alive(true);
  8812. auto res = cli_.send(req);
  8813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8814. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8815. EXPECT_EQ("close", res->get_header_value("Connection"));
  8816. EXPECT_FALSE(cli_.is_socket_open());
  8817. }
  8818. TEST_F(ServerTest, CustomRouteReadsBody) {
  8819. const std::string xml =
  8820. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8821. Request req;
  8822. req.method = "PROPFIND";
  8823. req.path = "/dav/dir";
  8824. req.set_header("Depth", "1");
  8825. req.body = xml;
  8826. auto res = cli_.send(req);
  8827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8828. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8829. EXPECT_EQ(xml, res->body);
  8830. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8831. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8832. }
  8833. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8834. Request req;
  8835. req.method = "PROPFIND";
  8836. req.path = "/dav/42";
  8837. auto res = cli_.send(req);
  8838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8839. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8840. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8841. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8842. }
  8843. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8844. Request req;
  8845. req.method = "PROPFIND";
  8846. req.path = "/dav-re/123";
  8847. auto res = cli_.send(req);
  8848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8849. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8850. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8851. }
  8852. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8853. Request req;
  8854. req.method = "MKCOL";
  8855. req.path = "/dav-mkcol";
  8856. auto res = cli_.send(req);
  8857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8858. EXPECT_EQ(StatusCode::Created_201, res->status);
  8859. }
  8860. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8861. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8862. Request req;
  8863. req.method = "REPORT";
  8864. req.path = "/dav-report";
  8865. req.body = xml;
  8866. auto res = cli_.send(req);
  8867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8868. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8869. EXPECT_EQ(xml, res->body);
  8870. }
  8871. // A content reader route must fire even when the request carries no body,
  8872. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8873. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8874. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8875. Request req;
  8876. req.method = "REPORT";
  8877. req.path = "/dav-report";
  8878. auto res = cli_.send(req);
  8879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8880. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8881. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8882. }
  8883. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8884. Request req;
  8885. req.method = "PROPFIND";
  8886. req.path = "/not-dav";
  8887. auto res = cli_.send(req);
  8888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8889. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8890. }
  8891. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8892. Request req;
  8893. req.method = "UNLOCK";
  8894. req.path = "/dav/dir";
  8895. cli_.set_keep_alive(true);
  8896. auto res = cli_.send(req);
  8897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8898. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8899. EXPECT_EQ("close", res->get_header_value("Connection"));
  8900. EXPECT_FALSE(cli_.is_socket_open());
  8901. }
  8902. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8903. // The mount point serves this path, but only for GET and HEAD.
  8904. auto get_res = cli_.Get("/dir/index.html");
  8905. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8906. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8907. Request req;
  8908. req.method = "PROPFIND";
  8909. req.path = "/dir/index.html";
  8910. auto res = cli_.send(req);
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8913. }
  8914. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8915. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8916. cli_.set_keep_alive(true);
  8917. for (auto i = 0; i < 2; i++) {
  8918. Request req;
  8919. req.method = "PROPFIND";
  8920. req.path = "/dav/dir";
  8921. req.body = xml;
  8922. auto res = cli_.send(req);
  8923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8924. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8925. EXPECT_EQ(xml, res->body);
  8926. EXPECT_TRUE(cli_.is_socket_open());
  8927. }
  8928. // A built-in method must still be served on the same connection.
  8929. cli_.set_keep_alive(false);
  8930. auto res = cli_.Get("/hi");
  8931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8932. EXPECT_EQ(StatusCode::OK_200, res->status);
  8933. EXPECT_EQ("close", res->get_header_value("Connection"));
  8934. }
  8935. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8936. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8937. Request req;
  8938. req.method = "PROPFIND";
  8939. req.path = "/dav/dir";
  8940. req.set_header("Expect", "100-continue");
  8941. req.body = xml;
  8942. auto res = cli_.send(req);
  8943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8944. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8945. EXPECT_EQ(xml, res->body);
  8946. }
  8947. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8948. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8949. TEST_F(ServerTest, Gzip) {
  8950. Headers headers;
  8951. headers.emplace("Accept-Encoding", "gzip, deflate");
  8952. auto res = cli_.Get("/compress", headers);
  8953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8954. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8956. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8957. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8958. "7890123456789012345678901234567890",
  8959. res->body);
  8960. EXPECT_EQ(StatusCode::OK_200, res->status);
  8961. }
  8962. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8963. Headers headers;
  8964. headers.emplace("Accept-Encoding", "gzip, deflate");
  8965. auto res = cli_.Get("/compress-with-charset", headers);
  8966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8967. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8968. EXPECT_EQ("application/json; charset=utf-8",
  8969. res->get_header_value("Content-Type"));
  8970. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8971. "7890123456789012345678901234567890",
  8972. res->body);
  8973. EXPECT_EQ(StatusCode::OK_200, res->status);
  8974. }
  8975. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8976. Headers headers;
  8977. headers.emplace("Accept-Encoding", "");
  8978. auto res = cli_.Get("/compress", headers);
  8979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8980. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8982. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8983. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8984. "7890123456789012345678901234567890",
  8985. res->body);
  8986. EXPECT_EQ(StatusCode::OK_200, res->status);
  8987. }
  8988. TEST_F(ServerTest, GzipWithContentReceiver) {
  8989. Headers headers;
  8990. headers.emplace("Accept-Encoding", "gzip, deflate");
  8991. std::string body;
  8992. auto res =
  8993. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8994. EXPECT_EQ(100U, data_length);
  8995. body.append(data, data_length);
  8996. return true;
  8997. });
  8998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8999. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9000. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9001. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9002. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9003. "7890123456789012345678901234567890",
  9004. body);
  9005. EXPECT_EQ(StatusCode::OK_200, res->status);
  9006. }
  9007. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9008. Headers headers;
  9009. headers.emplace("Accept-Encoding", "gzip, deflate");
  9010. cli_.set_decompress(false);
  9011. auto res = cli_.Get("/compress", headers);
  9012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9013. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9015. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9016. EXPECT_EQ(33U, res->body.size());
  9017. EXPECT_EQ(StatusCode::OK_200, res->status);
  9018. }
  9019. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9020. Headers headers;
  9021. headers.emplace("Accept-Encoding", "");
  9022. std::string body;
  9023. auto res =
  9024. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9025. EXPECT_EQ(100U, data_length);
  9026. body.append(data, data_length);
  9027. return true;
  9028. });
  9029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9030. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9031. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9032. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9033. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9034. "7890123456789012345678901234567890",
  9035. body);
  9036. EXPECT_EQ(StatusCode::OK_200, res->status);
  9037. }
  9038. TEST_F(ServerTest, NoGzip) {
  9039. Headers headers;
  9040. headers.emplace("Accept-Encoding", "gzip, deflate");
  9041. auto res = cli_.Get("/nocompress", headers);
  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. res->body);
  9049. EXPECT_EQ(StatusCode::OK_200, res->status);
  9050. }
  9051. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9052. Headers headers;
  9053. headers.emplace("Accept-Encoding", "gzip, deflate");
  9054. std::string body;
  9055. auto res = cli_.Get("/nocompress", headers,
  9056. [&](const char *data, size_t data_length) {
  9057. EXPECT_EQ(100U, data_length);
  9058. body.append(data, data_length);
  9059. return true;
  9060. });
  9061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9062. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9063. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9064. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9065. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9066. "7890123456789012345678901234567890",
  9067. body);
  9068. EXPECT_EQ(StatusCode::OK_200, res->status);
  9069. }
  9070. TEST_F(ServerTest, MultipartFormDataGzip) {
  9071. UploadFormDataItems items = {
  9072. {"key1", "test", "", ""},
  9073. {"key2", "--abcdefg123", "", ""},
  9074. };
  9075. cli_.set_compress(true);
  9076. auto res = cli_.Post("/compress-multipart", items);
  9077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9078. EXPECT_EQ(StatusCode::OK_200, res->status);
  9079. }
  9080. #endif
  9081. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9082. // Static file compression is opt-in, so these run their own server rather than
  9083. // flipping it on for the shared ServerTest fixture, which would silently
  9084. // rewrite what every other static file test is asserting.
  9085. class StaticFileCompressionTest : public ::testing::Test {
  9086. protected:
  9087. void TearDown() override {
  9088. if (t_.joinable()) {
  9089. svr_.stop();
  9090. t_.join();
  9091. }
  9092. }
  9093. int start(const std::function<void(Server &)> &configure = nullptr) {
  9094. // Serves the same tree as a directory of build-time compressed assets
  9095. // would be served: the mount point names the coding the files are already
  9096. // stored in. Registered before "/" so it is the one that matches.
  9097. svr_.set_mount_point("/pre-encoded", "./www",
  9098. {{"Content-Encoding", "gzip"}});
  9099. svr_.set_mount_point("/", "./www");
  9100. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9101. res.set_file_content("./www/dir/index.html", "text/html");
  9102. });
  9103. svr_.Get("/pre-encoded-file-content",
  9104. [](const Request & /*req*/, Response &res) {
  9105. res.set_header("Content-Encoding", "gzip");
  9106. res.set_file_content("./www/dir/index.html", "text/html");
  9107. });
  9108. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9109. res.set_content_provider(
  9110. 6, "text/plain",
  9111. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9112. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9113. return true;
  9114. });
  9115. });
  9116. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9117. res.set_content_provider(
  9118. 1000, "text/plain",
  9119. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9120. if (offset < 100) {
  9121. std::string data(100, 'A');
  9122. sink.write(data.data(), data.size());
  9123. return true;
  9124. }
  9125. std::this_thread::sleep_for(std::chrono::seconds(2));
  9126. std::string data(900, 'B');
  9127. sink.write(data.data(), data.size());
  9128. return true;
  9129. });
  9130. });
  9131. if (configure) { configure(svr_); }
  9132. auto port = svr_.bind_to_any_port(HOST);
  9133. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9134. svr_.wait_until_ready();
  9135. return port;
  9136. }
  9137. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9138. // Every file under ./www except 1MB.txt is smaller than the default
  9139. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9140. // it out of the way.
  9141. static void enable_without_floor(Server &svr) {
  9142. svr.set_static_file_compression(true);
  9143. svr.set_static_file_compression_min_length(0);
  9144. }
  9145. Server svr_;
  9146. std::thread t_;
  9147. };
  9148. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9149. auto port = start();
  9150. Client cli(HOST, port);
  9151. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9153. EXPECT_EQ(StatusCode::OK_200, res->status);
  9154. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9155. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9156. EXPECT_EQ(1048576U, res->body.size());
  9157. }
  9158. TEST_F(StaticFileCompressionTest, MountPoint) {
  9159. auto port = start(enable);
  9160. Client cli(HOST, port);
  9161. cli.set_decompress(false);
  9162. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9164. EXPECT_EQ(StatusCode::OK_200, res->status);
  9165. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9166. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9167. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9168. // The response stays self-delimiting: a length, not a chunked body.
  9169. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9170. EXPECT_EQ(std::to_string(res->body.size()),
  9171. res->get_header_value("Content-Length"));
  9172. EXPECT_LT(res->body.size(), 1048576U);
  9173. EXPECT_FALSE(res->body.empty());
  9174. }
  9175. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9176. auto port = start(enable);
  9177. Client cli(HOST, port);
  9178. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9180. EXPECT_EQ(StatusCode::OK_200, res->status);
  9181. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9182. EXPECT_EQ(1048576U, res->body.size());
  9183. }
  9184. TEST_F(StaticFileCompressionTest, FileContent) {
  9185. auto port = start(enable_without_floor);
  9186. Client cli(HOST, port);
  9187. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9189. EXPECT_EQ(StatusCode::OK_200, res->status);
  9190. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9191. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9192. EXPECT_EQ(104U, res->body.size());
  9193. }
  9194. // A handler that serves an already-encoded file names the coding itself. The
  9195. // file-backed path decided its coding from Accept-Encoding and the content
  9196. // type alone, so it compressed the stored bytes a second time and appended a
  9197. // second Content-Encoding field line.
  9198. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9199. auto port = start(enable_without_floor);
  9200. Client cli(HOST, port);
  9201. cli.set_decompress(false);
  9202. auto res = cli.Get("/pre-encoded-file-content",
  9203. Headers{{"Accept-Encoding", "gzip"}});
  9204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9205. EXPECT_EQ(StatusCode::OK_200, res->status);
  9206. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9207. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9208. // Vary belongs to a coding the server chose, and it chose none here.
  9209. EXPECT_FALSE(res->has_header("Vary"));
  9210. // The file travels exactly as it is stored on disk.
  9211. EXPECT_EQ(104U, res->body.size());
  9212. }
  9213. // The 1MB file clears the default floor, so this one runs the configuration a
  9214. // deployment would actually have.
  9215. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9216. auto port = start(enable);
  9217. Client cli(HOST, port);
  9218. cli.set_decompress(false);
  9219. auto res =
  9220. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9222. EXPECT_EQ(StatusCode::OK_200, res->status);
  9223. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9224. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9225. EXPECT_FALSE(res->has_header("Vary"));
  9226. EXPECT_EQ(1048576U, res->body.size());
  9227. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9228. }
  9229. TEST_F(StaticFileCompressionTest, Head) {
  9230. auto port = start(enable);
  9231. Client cli(HOST, port);
  9232. cli.set_decompress(false);
  9233. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9234. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9235. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9237. EXPECT_EQ(StatusCode::OK_200, res->status);
  9238. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9239. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9240. // HEAD still reports the size a GET would return.
  9241. EXPECT_EQ(get->get_header_value("Content-Length"),
  9242. res->get_header_value("Content-Length"));
  9243. EXPECT_TRUE(res->body.empty());
  9244. }
  9245. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9246. auto port = start(enable);
  9247. Client cli(HOST, port);
  9248. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9249. {"Accept-Encoding", "gzip"}});
  9250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9251. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9252. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9253. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9254. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9255. EXPECT_EQ("cd", res->body);
  9256. }
  9257. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9258. auto port = start(enable);
  9259. Client cli(HOST, port);
  9260. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9262. EXPECT_EQ(StatusCode::OK_200, res->status);
  9263. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9264. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9265. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9266. }
  9267. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9268. auto port = start(enable);
  9269. Client cli(HOST, port);
  9270. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9272. EXPECT_EQ(StatusCode::OK_200, res->status);
  9273. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9274. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9275. EXPECT_TRUE(res->body.empty());
  9276. }
  9277. TEST_F(StaticFileCompressionTest, MinLength) {
  9278. auto port = start(enable);
  9279. Client cli(HOST, port);
  9280. // 104 bytes, well under the default floor. Compressing it would add the
  9281. // gzip header and trailer to a body that already fits in one packet.
  9282. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9284. EXPECT_EQ(StatusCode::OK_200, res->status);
  9285. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9286. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9287. }
  9288. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9289. auto port = start([](Server &svr) {
  9290. svr.set_static_file_compression(true);
  9291. svr.set_static_file_compression_min_length(1);
  9292. });
  9293. Client cli(HOST, port);
  9294. cli.set_decompress(false);
  9295. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9297. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9298. // A 9-byte file comes back larger than it went in, because gzip's header and
  9299. // trailer outweigh anything deflate can save. That is the end of the range
  9300. // the floor exists to keep out.
  9301. EXPECT_GT(res->body.size(), 9U);
  9302. }
  9303. TEST_F(StaticFileCompressionTest, MaxLength) {
  9304. auto port = start([](Server &svr) {
  9305. svr.set_static_file_compression(true);
  9306. svr.set_static_file_compression_min_length(0);
  9307. svr.set_static_file_compression_max_length(1024);
  9308. });
  9309. Client cli(HOST, port);
  9310. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9311. // defines `small` as a macro on Windows.
  9312. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9313. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9314. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9315. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9316. // Under it: compressed.
  9317. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9318. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9319. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9320. }
  9321. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9322. auto port = start(enable_without_floor);
  9323. Client cli(HOST, port);
  9324. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9325. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9326. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9327. auto identity_etag = identity->get_header_value("ETag");
  9328. ASSERT_FALSE(identity_etag.empty());
  9329. auto gzipped =
  9330. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9331. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9332. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9333. auto gzip_etag = gzipped->get_header_value("ETag");
  9334. ASSERT_FALSE(gzip_etag.empty());
  9335. // Two representations, two validators.
  9336. EXPECT_NE(identity_etag, gzip_etag);
  9337. // Each one revalidates against the request that would produce it...
  9338. auto fresh =
  9339. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9340. {"If-None-Match", gzip_etag}});
  9341. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9342. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9343. auto fresh_identity =
  9344. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9345. {"If-None-Match", identity_etag}});
  9346. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9347. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9348. // ...and not against the other representation.
  9349. auto crossed =
  9350. cli.Get("/dir/index.html",
  9351. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9352. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9353. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9354. }
  9355. // The opt-in covers responses the server reads off disk itself. A caller's own
  9356. // known-length provider keeps its Content-Length and, more importantly, keeps
  9357. // delivering incrementally: routing it through a compressor would hold every
  9358. // write back until zlib's window filled.
  9359. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9360. auto port = start(enable);
  9361. Client cli(HOST, port);
  9362. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9364. EXPECT_EQ(StatusCode::OK_200, res->status);
  9365. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9366. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9367. EXPECT_EQ("aaabbb", res->body);
  9368. }
  9369. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9370. auto port = start(enable);
  9371. Client cli(HOST, port);
  9372. cli.set_read_timeout(1, 0);
  9373. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9374. Headers{{"Accept-Encoding", "gzip"}});
  9375. ASSERT_TRUE(handle.is_valid());
  9376. // The provider writes 100 bytes and then stalls for longer than the read
  9377. // timeout. Those first bytes have to arrive anyway: run the response through
  9378. // a compressor and zlib holds them until its window fills, so the read would
  9379. // come back empty instead.
  9380. char buf[256];
  9381. auto n = handle.read(buf, sizeof(buf));
  9382. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9383. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9384. }
  9385. #endif
  9386. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9387. TEST_F(ServerTest, Brotli) {
  9388. Headers headers;
  9389. headers.emplace("Accept-Encoding", "br");
  9390. auto res = cli_.Get("/compress", headers);
  9391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9392. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9393. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9394. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9395. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9396. "7890123456789012345678901234567890",
  9397. res->body);
  9398. EXPECT_EQ(StatusCode::OK_200, res->status);
  9399. }
  9400. #endif
  9401. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9402. TEST_F(ServerTest, Zstd) {
  9403. Headers headers;
  9404. headers.emplace("Accept-Encoding", "zstd");
  9405. auto res = cli_.Get("/compress", headers);
  9406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9407. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9408. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9409. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9410. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9411. "7890123456789012345678901234567890",
  9412. res->body);
  9413. EXPECT_EQ(StatusCode::OK_200, res->status);
  9414. }
  9415. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9416. Headers headers;
  9417. headers.emplace("Accept-Encoding", "");
  9418. auto res = cli_.Get("/compress", headers);
  9419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9420. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9421. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9422. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9423. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9424. "7890123456789012345678901234567890",
  9425. res->body);
  9426. EXPECT_EQ(StatusCode::OK_200, res->status);
  9427. }
  9428. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9429. Headers headers;
  9430. headers.emplace("Accept-Encoding", "zstd");
  9431. std::string body;
  9432. auto res =
  9433. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9434. EXPECT_EQ(100U, data_length);
  9435. body.append(data, data_length);
  9436. return true;
  9437. });
  9438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9439. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9440. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9441. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9442. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9443. "7890123456789012345678901234567890",
  9444. body);
  9445. EXPECT_EQ(StatusCode::OK_200, res->status);
  9446. }
  9447. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9448. Headers headers;
  9449. headers.emplace("Accept-Encoding", "zstd");
  9450. cli_.set_decompress(false);
  9451. auto res = cli_.Get("/compress", headers);
  9452. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9453. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9454. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9455. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9457. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9458. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9459. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9460. EXPECT_EQ(StatusCode::OK_200, res->status);
  9461. ASSERT_EQ(26U, res->body.size());
  9462. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9463. 0);
  9464. }
  9465. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9466. Headers headers;
  9467. headers.emplace("Accept-Encoding", "");
  9468. std::string body;
  9469. auto res =
  9470. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9471. EXPECT_EQ(100U, data_length);
  9472. body.append(data, data_length);
  9473. return true;
  9474. });
  9475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9476. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9478. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9479. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9480. "7890123456789012345678901234567890",
  9481. body);
  9482. EXPECT_EQ(StatusCode::OK_200, res->status);
  9483. }
  9484. TEST_F(ServerTest, NoZstd) {
  9485. Headers headers;
  9486. headers.emplace("Accept-Encoding", "zstd");
  9487. auto res = cli_.Get("/nocompress", headers);
  9488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9489. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9490. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9491. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9492. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9493. "7890123456789012345678901234567890",
  9494. res->body);
  9495. EXPECT_EQ(StatusCode::OK_200, res->status);
  9496. }
  9497. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9498. Headers headers;
  9499. headers.emplace("Accept-Encoding", "zstd");
  9500. std::string body;
  9501. auto res = cli_.Get("/nocompress", headers,
  9502. [&](const char *data, size_t data_length) {
  9503. EXPECT_EQ(100U, data_length);
  9504. body.append(data, data_length);
  9505. return true;
  9506. });
  9507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9508. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9509. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9510. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9511. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9512. "7890123456789012345678901234567890",
  9513. body);
  9514. EXPECT_EQ(StatusCode::OK_200, res->status);
  9515. }
  9516. // TODO: How to enable zstd ??
  9517. TEST_F(ServerTest, MultipartFormDataZstd) {
  9518. UploadFormDataItems items = {
  9519. {"key1", "test", "", ""},
  9520. {"key2", "--abcdefg123", "", ""},
  9521. };
  9522. Headers headers;
  9523. headers.emplace("Accept-Encoding", "zstd");
  9524. cli_.set_compress(true);
  9525. auto res = cli_.Post("/compress-multipart", headers, items);
  9526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9527. EXPECT_EQ(StatusCode::OK_200, res->status);
  9528. }
  9529. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9530. Headers headers;
  9531. headers.emplace("Accept-Encoding", "zstd");
  9532. cli_.set_compress(true);
  9533. auto res = cli_.Put(
  9534. "/put", headers, 3,
  9535. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9536. sink.os << "PUT";
  9537. return true;
  9538. },
  9539. "text/plain");
  9540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9541. EXPECT_EQ(StatusCode::OK_200, res->status);
  9542. EXPECT_EQ("PUT", res->body);
  9543. }
  9544. // Pre-compression logging tests
  9545. TEST_F(ServerTest, PreCompressionLogging) {
  9546. // Test data for compression (matches the actual /compress endpoint content)
  9547. const std::string test_content =
  9548. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9549. "3456789012345678901234567890";
  9550. // Variables to capture logging data
  9551. std::string pre_compression_body;
  9552. std::string pre_compression_content_type;
  9553. std::string pre_compression_content_encoding;
  9554. std::string post_compression_body;
  9555. std::string post_compression_content_type;
  9556. std::string post_compression_content_encoding;
  9557. // Set up pre-compression logger
  9558. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9559. const Response &res) {
  9560. pre_compression_body = res.body;
  9561. pre_compression_content_type = res.get_header_value("Content-Type");
  9562. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9563. });
  9564. // Set up post-compression logger
  9565. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9566. post_compression_body = res.body;
  9567. post_compression_content_type = res.get_header_value("Content-Type");
  9568. post_compression_content_encoding =
  9569. res.get_header_value("Content-Encoding");
  9570. });
  9571. // Test with gzip compression
  9572. Headers headers;
  9573. headers.emplace("Accept-Encoding", "gzip");
  9574. auto res = cli_.Get("/compress", headers);
  9575. // Verify response was compressed
  9576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9577. EXPECT_EQ(StatusCode::OK_200, res->status);
  9578. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9579. // Verify pre-compression logger captured uncompressed content
  9580. EXPECT_EQ(test_content, pre_compression_body);
  9581. EXPECT_EQ("text/plain", pre_compression_content_type);
  9582. EXPECT_TRUE(pre_compression_content_encoding
  9583. .empty()); // No encoding header before compression
  9584. // Verify post-compression logger captured compressed content
  9585. EXPECT_NE(test_content,
  9586. post_compression_body); // Should be different after compression
  9587. EXPECT_EQ("text/plain", post_compression_content_type);
  9588. EXPECT_EQ("gzip", post_compression_content_encoding);
  9589. // Verify compressed content is smaller
  9590. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9591. }
  9592. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9593. const std::string test_content =
  9594. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9595. "3456789012345678901234567890";
  9596. std::string pre_compression_body;
  9597. std::string post_compression_body;
  9598. svr_.set_pre_compression_logger(
  9599. [&](const Request & /*req*/, const Response &res) {
  9600. pre_compression_body = res.body;
  9601. });
  9602. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9603. post_compression_body = res.body;
  9604. });
  9605. Headers headers;
  9606. headers.emplace("Accept-Encoding", "br");
  9607. auto res = cli_.Get("/compress", headers);
  9608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9609. EXPECT_EQ(StatusCode::OK_200, res->status);
  9610. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9611. // Verify pre-compression content is uncompressed
  9612. EXPECT_EQ(test_content, pre_compression_body);
  9613. // Verify post-compression content is compressed
  9614. EXPECT_NE(test_content, post_compression_body);
  9615. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9616. }
  9617. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9618. const std::string test_content =
  9619. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9620. "3456789012345678901234567890";
  9621. std::string pre_compression_body;
  9622. std::string post_compression_body;
  9623. svr_.set_pre_compression_logger(
  9624. [&](const Request & /*req*/, const Response &res) {
  9625. pre_compression_body = res.body;
  9626. });
  9627. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9628. post_compression_body = res.body;
  9629. });
  9630. // Request without compression (use /nocompress endpoint)
  9631. Headers headers;
  9632. auto res = cli_.Get("/nocompress", headers);
  9633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9634. EXPECT_EQ(StatusCode::OK_200, res->status);
  9635. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9636. // Pre-compression logger should not be called when no compression is applied
  9637. EXPECT_TRUE(
  9638. pre_compression_body.empty()); // Pre-compression logger not called
  9639. EXPECT_EQ(
  9640. test_content,
  9641. post_compression_body); // Post-compression logger captures final content
  9642. }
  9643. TEST_F(ServerTest, LoggerSeesContentLength) {
  9644. size_t logged_content_length = 0;
  9645. std::string logged_content_length_header;
  9646. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9647. logged_content_length = res.content_length_;
  9648. logged_content_length_header = res.get_header_value("Content-Length");
  9649. });
  9650. auto res = cli_.Get("/nocompress");
  9651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9652. EXPECT_EQ(StatusCode::OK_200, res->status);
  9653. EXPECT_EQ(res->body.size(), logged_content_length);
  9654. EXPECT_EQ(std::to_string(logged_content_length),
  9655. logged_content_length_header);
  9656. }
  9657. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9658. const std::string test_content =
  9659. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9660. "3456789012345678901234567890";
  9661. std::string pre_compression_body;
  9662. bool pre_logger_called = false;
  9663. // Set only pre-compression logger
  9664. svr_.set_pre_compression_logger(
  9665. [&](const Request & /*req*/, const Response &res) {
  9666. pre_compression_body = res.body;
  9667. pre_logger_called = true;
  9668. });
  9669. Headers headers;
  9670. headers.emplace("Accept-Encoding", "gzip");
  9671. auto res = cli_.Get("/compress", headers);
  9672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9673. EXPECT_EQ(StatusCode::OK_200, res->status);
  9674. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9675. // Verify pre-compression logger was called
  9676. EXPECT_TRUE(pre_logger_called);
  9677. EXPECT_EQ(test_content, pre_compression_body);
  9678. }
  9679. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9680. {
  9681. // Test with Expect: 100-continue header - success case
  9682. // Server returns 100 Continue, client sends body, server returns 200 OK
  9683. Request req;
  9684. req.method = "POST";
  9685. req.path = "/post-large";
  9686. req.set_header("Expect", "100-continue");
  9687. req.body = LARGE_DATA;
  9688. Response res;
  9689. auto error = Error::Success;
  9690. cli_.set_keep_alive(true);
  9691. auto ret = cli_.send(req, res, error);
  9692. EXPECT_TRUE(ret);
  9693. EXPECT_EQ(StatusCode::OK_200, res.status);
  9694. EXPECT_EQ(LARGE_DATA, res.body);
  9695. }
  9696. {
  9697. // Test with Expect: 100-continue header - error case
  9698. // Client should not send the body when server returns an error
  9699. Request req;
  9700. req.method = "POST";
  9701. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9702. req.set_header("Expect", "100-continue");
  9703. req.body = LARGE_DATA;
  9704. Response res;
  9705. auto error = Error::Success;
  9706. auto start = std::chrono::high_resolution_clock::now();
  9707. cli_.set_keep_alive(true);
  9708. auto ret = cli_.send(req, res, error);
  9709. auto end = std::chrono::high_resolution_clock::now();
  9710. auto elapsed =
  9711. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9712. .count();
  9713. // With Expect: 100-continue, request completes successfully but with error
  9714. EXPECT_TRUE(ret);
  9715. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9716. EXPECT_EQ("close", res.get_header_value("Connection"));
  9717. EXPECT_FALSE(cli_.is_socket_open());
  9718. EXPECT_LE(elapsed, 2000);
  9719. }
  9720. {
  9721. // Send an extra GET request to ensure error recovery without hanging
  9722. Request req;
  9723. req.method = "GET";
  9724. req.path = "/hi";
  9725. auto start = std::chrono::high_resolution_clock::now();
  9726. auto res = cli_.send(req);
  9727. auto end = std::chrono::high_resolution_clock::now();
  9728. auto elapsed =
  9729. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9730. .count();
  9731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9732. EXPECT_EQ(StatusCode::OK_200, res->status);
  9733. EXPECT_EQ("Hello World!", res->body);
  9734. EXPECT_LE(elapsed, 500);
  9735. }
  9736. }
  9737. TEST(ZstdDecompressor, ChunkedDecompression) {
  9738. std::string data;
  9739. for (size_t i = 0; i < 32 * 1024; ++i) {
  9740. data.push_back(static_cast<char>('a' + i % 26));
  9741. }
  9742. std::string compressed_data;
  9743. {
  9744. httplib::detail::zstd_compressor compressor;
  9745. bool result = compressor.compress(
  9746. data.data(), data.size(),
  9747. /*last=*/true,
  9748. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9749. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9750. compressed_data_size);
  9751. return true;
  9752. });
  9753. ASSERT_TRUE(result);
  9754. }
  9755. std::string decompressed_data;
  9756. {
  9757. httplib::detail::zstd_decompressor decompressor;
  9758. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9759. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9760. size_t chunk_size = 130;
  9761. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9762. chunk_begin += chunk_size) {
  9763. size_t current_chunk_size =
  9764. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9765. bool result = decompressor.decompress(
  9766. compressed_data.data() + chunk_begin, current_chunk_size,
  9767. [&](const char *decompressed_data_chunk,
  9768. size_t decompressed_data_chunk_size) {
  9769. decompressed_data.insert(decompressed_data.size(),
  9770. decompressed_data_chunk,
  9771. decompressed_data_chunk_size);
  9772. return true;
  9773. });
  9774. ASSERT_TRUE(result);
  9775. }
  9776. }
  9777. ASSERT_EQ(data, decompressed_data);
  9778. }
  9779. TEST(ZstdDecompressor, Decompress) {
  9780. std::string original_text = "Compressed with ZSTD";
  9781. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9782. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9783. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9784. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9785. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9786. std::string decompressed_data;
  9787. {
  9788. httplib::detail::zstd_decompressor decompressor;
  9789. bool result = decompressor.decompress(
  9790. compressed_data.data(), compressed_data.size(),
  9791. [&](const char *decompressed_data_chunk,
  9792. size_t decompressed_data_chunk_size) {
  9793. decompressed_data.insert(decompressed_data.size(),
  9794. decompressed_data_chunk,
  9795. decompressed_data_chunk_size);
  9796. return true;
  9797. });
  9798. ASSERT_TRUE(result);
  9799. }
  9800. ASSERT_EQ(original_text, decompressed_data);
  9801. }
  9802. #endif
  9803. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9804. // separate chunks so that the server sees each part in its own read(). Used to
  9805. // place a read boundary at a specific offset of a request body.
  9806. static bool send_request_in_parts(time_t read_timeout_sec,
  9807. const std::vector<std::string> &parts,
  9808. std::string *resp = nullptr,
  9809. int port = PORT) {
  9810. auto error = Error::Success;
  9811. auto client_sock = detail::create_client_socket(
  9812. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9813. /*connection_timeout_sec=*/5, 0,
  9814. /*read_timeout_sec=*/5, 0,
  9815. /*write_timeout_sec=*/5, 0, std::string(), error);
  9816. if (client_sock == INVALID_SOCKET) { return false; }
  9817. auto ret = detail::process_client_socket(
  9818. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9819. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9820. for (size_t i = 0; i < parts.size(); i++) {
  9821. const auto &part = parts[i];
  9822. if (part.size() !=
  9823. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9824. return false;
  9825. }
  9826. if (i + 1 < parts.size()) {
  9827. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9828. }
  9829. }
  9830. char buf[512];
  9831. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9832. while (line_reader.getline()) {
  9833. if (resp) { *resp += line_reader.ptr(); }
  9834. }
  9835. return true;
  9836. });
  9837. detail::close_socket(client_sock);
  9838. return ret;
  9839. }
  9840. // Sends a raw request to a server listening at HOST:PORT.
  9841. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9842. std::string *resp = nullptr, int port = PORT) {
  9843. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9844. }
  9845. #ifdef CPPHTTPLIB_SSL_ENABLED
  9846. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9848. ASSERT_TRUE(svr.is_valid());
  9849. svr.set_read_timeout(1, 0);
  9850. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9851. auto se = detail::scope_exit([&] {
  9852. svr.stop();
  9853. t.join();
  9854. ASSERT_FALSE(svr.is_running());
  9855. });
  9856. svr.wait_until_ready();
  9857. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9858. // keeps each wait well within the read timeout. The server gives up a
  9859. // second in, so the bytes sent after that fail.
  9860. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9861. parts.resize(26, std::string(1, '\0'));
  9862. EXPECT_FALSE(send_request_in_parts(5, parts));
  9863. }
  9864. #endif
  9865. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9866. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9867. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9868. const std::vector<std::string> &parts,
  9869. std::string *resp = nullptr,
  9870. int port = PORT) {
  9871. auto error = Error::Success;
  9872. auto sock = detail::create_client_socket(
  9873. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9874. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9875. /*write_timeout_sec=*/5, 0, std::string(), error);
  9876. if (sock == INVALID_SOCKET) { return false; }
  9877. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9878. auto ctx = SSL_CTX_new(TLS_client_method());
  9879. auto ssl = SSL_new(ctx);
  9880. auto ssl_se = detail::scope_exit([&] {
  9881. SSL_free(ssl);
  9882. SSL_CTX_free(ctx);
  9883. });
  9884. SSL_set_fd(ssl, static_cast<int>(sock));
  9885. if (SSL_connect(ssl) != 1) { return false; }
  9886. for (size_t i = 0; i < parts.size(); i++) {
  9887. const auto &part = parts[i];
  9888. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9889. static_cast<int>(part.size())) {
  9890. return false;
  9891. }
  9892. if (i + 1 < parts.size()) {
  9893. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9894. }
  9895. }
  9896. char buf[512];
  9897. int n;
  9898. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9899. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9900. }
  9901. return true;
  9902. }
  9903. #endif
  9904. // The request line, then a header value a byte at a time.
  9905. static std::vector<std::string> slow_request_head_parts() {
  9906. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9907. parts.resize(26, "a");
  9908. parts.emplace_back("\r\n\r\n");
  9909. return parts;
  9910. }
  9911. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9912. // within the one-second read timeout. The server gives up a second in, before
  9913. // the head is complete.
  9914. static void
  9915. expect_slow_request_head_dropped(Server &svr,
  9916. const std::function<std::string()> &send) {
  9917. std::atomic<bool> handled(false);
  9918. svr.Get("/", [&](const Request &, Response &res) {
  9919. handled = true;
  9920. res.set_content("ok", "text/plain");
  9921. });
  9922. svr.set_read_timeout(1, 0);
  9923. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9924. auto se = detail::scope_exit([&] {
  9925. svr.stop();
  9926. t.join();
  9927. ASSERT_FALSE(svr.is_running());
  9928. });
  9929. svr.wait_until_ready();
  9930. auto resp = send();
  9931. EXPECT_FALSE(handled);
  9932. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9933. }
  9934. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9935. Server svr;
  9936. expect_slow_request_head_dropped(svr, [] {
  9937. std::string resp;
  9938. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9939. return resp;
  9940. });
  9941. }
  9942. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9943. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9945. ASSERT_TRUE(svr.is_valid());
  9946. expect_slow_request_head_dropped(svr, [] {
  9947. std::string resp;
  9948. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9949. return resp;
  9950. });
  9951. }
  9952. #endif
  9953. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9954. Server svr;
  9955. std::string header_value;
  9956. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9957. header_value = req.get_header_value("foo");
  9958. res.set_content("ok", "text/plain");
  9959. });
  9960. thread t = thread([&] { svr.listen(HOST, PORT); });
  9961. auto se = detail::scope_exit([&] {
  9962. svr.stop();
  9963. t.join();
  9964. ASSERT_FALSE(svr.is_running());
  9965. });
  9966. svr.wait_until_ready();
  9967. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9968. // like characters are not treated the same - use vertical tab and escape.
  9969. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9970. "foo: \t \v bar \x1B\t \r\n"
  9971. "Connection: close\r\n"
  9972. "\r\n";
  9973. std::string res;
  9974. ASSERT_TRUE(send_request(5, req, &res));
  9975. EXPECT_EQ(header_value, "");
  9976. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9977. }
  9978. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9979. Server svr;
  9980. std::string received;
  9981. svr.Get("/order", [&](const Request &req, Response &res) {
  9982. received = entries_to_string(req.headers);
  9983. res.set_content("ok", "text/plain");
  9984. });
  9985. auto port = svr.bind_to_any_port(HOST);
  9986. thread t = thread([&] { svr.listen_after_bind(); });
  9987. auto se = detail::scope_exit([&] {
  9988. svr.stop();
  9989. t.join();
  9990. ASSERT_FALSE(svr.is_running());
  9991. });
  9992. svr.wait_until_ready();
  9993. const std::string req = "GET /order HTTP/1.1\r\n"
  9994. "Host: localhost\r\n"
  9995. "X-First: 1\r\n"
  9996. "X-Dup: a\r\n"
  9997. "X-Second: 2\r\n"
  9998. "X-Dup: b\r\n"
  9999. "Connection: close\r\n"
  10000. "\r\n";
  10001. std::string res;
  10002. ASSERT_TRUE(send_request(5, req, &res, port));
  10003. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10004. EXPECT_EQ(
  10005. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10006. received);
  10007. }
  10008. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10009. Server svr;
  10010. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10011. res.set_header("Set-Cookie", "first=1");
  10012. res.set_header("X-Between", "y");
  10013. res.set_header("Set-Cookie", "second=2");
  10014. res.set_content("ok", "text/plain");
  10015. });
  10016. auto port = svr.bind_to_any_port(HOST);
  10017. thread t = thread([&] { svr.listen_after_bind(); });
  10018. auto se = detail::scope_exit([&] {
  10019. svr.stop();
  10020. t.join();
  10021. ASSERT_FALSE(svr.is_running());
  10022. });
  10023. svr.wait_until_ready();
  10024. Client cli(HOST, port);
  10025. auto res = cli.Get("/cookies");
  10026. ASSERT_TRUE(res);
  10027. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10028. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10029. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10030. }
  10031. // A stream may send a byte at a time with a small extension on each chunk,
  10032. // however long it runs
  10033. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10034. Server svr;
  10035. svr.Post("/count", [](const Request &req, Response &res) {
  10036. res.set_content(std::to_string(req.body.size()), "text/plain");
  10037. });
  10038. auto port = svr.bind_to_any_port(HOST);
  10039. ASSERT_LT(0, port);
  10040. thread t = thread([&] { svr.listen_after_bind(); });
  10041. auto se = detail::scope_exit([&] {
  10042. svr.stop();
  10043. t.join();
  10044. ASSERT_FALSE(svr.is_running());
  10045. });
  10046. svr.wait_until_ready();
  10047. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10048. "\r\nTransfer-Encoding: chunked\r\n"
  10049. "Connection: close\r\n\r\n";
  10050. for (auto i = 0; i < 4096; i++) {
  10051. req += "1;a=b\r\nx\r\n";
  10052. }
  10053. req += "0\r\n\r\n";
  10054. std::string res;
  10055. ASSERT_TRUE(send_request(5, req, &res, port));
  10056. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10057. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10058. }
  10059. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10060. Server svr;
  10061. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10062. auto i = new int(0);
  10063. res.set_header("Trailer", "X-Safe, X-Reflected");
  10064. res.set_chunked_content_provider(
  10065. "text/plain",
  10066. [i](size_t /*offset*/, DataSink &sink) {
  10067. if (*i == 0) {
  10068. sink.os << "body";
  10069. } else {
  10070. Headers trailer;
  10071. // A valid trailer that must survive.
  10072. trailer.emplace("X-Safe", "safe");
  10073. // Attacker-controlled value carrying CR/LF (response splitting).
  10074. trailer.emplace("X-Reflected",
  10075. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10076. // Attacker-controlled name carrying CR/LF.
  10077. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10078. sink.done_with_trailer(trailer);
  10079. }
  10080. (*i)++;
  10081. return true;
  10082. },
  10083. [i](bool /*success*/) { delete i; });
  10084. });
  10085. thread t = thread([&] { svr.listen(HOST, PORT); });
  10086. auto se = detail::scope_exit([&] {
  10087. svr.stop();
  10088. t.join();
  10089. ASSERT_FALSE(svr.is_running());
  10090. });
  10091. svr.wait_until_ready();
  10092. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10093. "Host: " + HOST +
  10094. "\r\n"
  10095. "Connection: close\r\n"
  10096. "\r\n";
  10097. std::string res;
  10098. ASSERT_TRUE(send_request(5, req, &res));
  10099. // The injected fields must not appear anywhere in the raw response.
  10100. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10101. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10102. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10103. // Invalid trailers are dropped entirely, matching set_header().
  10104. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10105. // The valid trailer still passes through.
  10106. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10107. }
  10108. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10109. // A custom header writer gets only the fields the default one writes
  10110. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10111. std::string s;
  10112. for (const auto &h : hdrs) {
  10113. s += h.first + ": " + h.second + "\r\n";
  10114. }
  10115. s += "\r\n";
  10116. return strm.write(s.data(), s.size());
  10117. };
  10118. for (auto custom_writer : {false, true}) {
  10119. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10120. Server svr;
  10121. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10122. svr.set_post_routing_handler([](const Request &, Response &res) {
  10123. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10124. });
  10125. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10126. // res.headers is a public field an application can populate directly,
  10127. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10128. // A valid header that must survive.
  10129. res.headers.emplace("X-Safe", "safe");
  10130. // Attacker-controlled value carrying CR/LF (response splitting).
  10131. res.headers.emplace("X-Reflected",
  10132. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10133. // Attacker-controlled name carrying CR/LF.
  10134. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10135. res.set_content("body", "text/plain");
  10136. });
  10137. thread t = thread([&] { svr.listen(HOST, PORT); });
  10138. auto se = detail::scope_exit([&] {
  10139. svr.stop();
  10140. t.join();
  10141. ASSERT_FALSE(svr.is_running());
  10142. });
  10143. svr.wait_until_ready();
  10144. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10145. "Host: " + HOST +
  10146. "\r\n"
  10147. "Connection: close\r\n"
  10148. "\r\n";
  10149. std::string res;
  10150. ASSERT_TRUE(send_request(5, req, &res));
  10151. // The injected fields must not appear anywhere in the raw response.
  10152. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10153. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10154. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10155. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10156. // Invalid headers are dropped entirely, matching set_header().
  10157. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10158. // The valid header still passes through.
  10159. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10160. }
  10161. }
  10162. // Forward declaration: in split builds split.py strips `inline` and moves the
  10163. // definition into httplib.cc, so detail::write_request_line is not visible from
  10164. // the public httplib.h. Re-declaring it here lets the tests link against the
  10165. // symbol in both header-only and split builds.
  10166. namespace httplib {
  10167. namespace detail {
  10168. ssize_t write_request_line(Stream &strm, const std::string &method,
  10169. const std::string &path);
  10170. } // namespace detail
  10171. } // namespace httplib
  10172. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10173. // A well-formed target is written verbatim.
  10174. {
  10175. detail::BufferStream strm;
  10176. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10177. EXPECT_GT(n, 0);
  10178. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10179. }
  10180. // A target carrying CR/LF, SP or other control octets must be rejected
  10181. // before anything reaches the wire, otherwise it splits the request line and
  10182. // injects a header or a whole request.
  10183. const std::string evil_targets[] = {
  10184. "/a\r\nInjected: pwned",
  10185. "/a\rInjected",
  10186. "/a\nInjected",
  10187. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10188. "/a b",
  10189. "/a\tb",
  10190. "/a\x7f",
  10191. };
  10192. for (const auto &evil : evil_targets) {
  10193. detail::BufferStream strm;
  10194. auto n = detail::write_request_line(strm, "GET", evil);
  10195. EXPECT_LT(n, 0);
  10196. EXPECT_TRUE(strm.get_buffer().empty());
  10197. }
  10198. }
  10199. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10200. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10201. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10202. // target reaches write_request. The client must fail cleanly with
  10203. // Error::Write instead of putting a request-line-less, header-injecting
  10204. // request on the wire.
  10205. Server svr;
  10206. svr.Get("/a", [](const Request &, Response &res) {
  10207. res.set_content("ok", "text/plain");
  10208. });
  10209. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10210. auto se = detail::scope_exit([&] {
  10211. svr.stop();
  10212. thread.join();
  10213. ASSERT_FALSE(svr.is_running());
  10214. });
  10215. svr.wait_until_ready();
  10216. {
  10217. Client cli(HOST, PORT);
  10218. cli.set_path_encode(false);
  10219. // The request is rejected before anything is written, so the connection
  10220. // stays silent and the subsequent response read would otherwise block for
  10221. // the full default read timeout. Shorten it -- the assertion is on the
  10222. // error, not the timeout.
  10223. cli.set_read_timeout(1, 0);
  10224. auto res = cli.Get("/a\r\nInjected: pwned");
  10225. EXPECT_FALSE(res);
  10226. EXPECT_EQ(Error::Write, res.error());
  10227. }
  10228. }
  10229. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10230. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10231. // including extension methods.
  10232. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10233. for (const auto &method : good_methods) {
  10234. detail::BufferStream strm;
  10235. auto n = detail::write_request_line(strm, method, "/");
  10236. EXPECT_GT(n, 0);
  10237. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10238. }
  10239. // A method carrying CR/LF would split the request line and smuggle a whole
  10240. // request ahead of the real one. A space or an empty method corrupts the
  10241. // request line. All must be rejected before anything reaches the wire.
  10242. const std::string evil_methods[] = {
  10243. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10244. "GET\r\nInjected: pwned",
  10245. "GET\r",
  10246. "GET\n",
  10247. "GE T",
  10248. "",
  10249. };
  10250. for (const auto &evil : evil_methods) {
  10251. detail::BufferStream strm;
  10252. auto n = detail::write_request_line(strm, evil, "/");
  10253. EXPECT_LT(n, 0);
  10254. EXPECT_TRUE(strm.get_buffer().empty());
  10255. }
  10256. }
  10257. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10258. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10259. // through Client::send must fail with Error::Write and no request, neither
  10260. // the smuggled one nor the real one, may reach the server.
  10261. Server svr;
  10262. std::atomic<int> request_count(0);
  10263. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10264. request_count++;
  10265. res.status = StatusCode::OK_200;
  10266. return Server::HandlerResponse::Handled;
  10267. });
  10268. auto port = svr.bind_to_any_port(HOST);
  10269. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10270. auto se = detail::scope_exit([&] {
  10271. svr.stop();
  10272. thread.join();
  10273. ASSERT_FALSE(svr.is_running());
  10274. });
  10275. svr.wait_until_ready();
  10276. {
  10277. Client cli(HOST, port);
  10278. const std::string evil_methods[] = {
  10279. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10280. "GE T",
  10281. "",
  10282. };
  10283. for (const auto &evil : evil_methods) {
  10284. Request req;
  10285. req.method = evil;
  10286. req.path = "/";
  10287. auto res = cli.send(req);
  10288. EXPECT_FALSE(res);
  10289. EXPECT_EQ(Error::Write, res.error());
  10290. }
  10291. auto handle =
  10292. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10293. EXPECT_FALSE(handle.is_valid());
  10294. EXPECT_EQ(Error::Write, handle.error);
  10295. // A valid request on the same client still goes through.
  10296. auto res = cli.Get("/");
  10297. ASSERT_TRUE(res);
  10298. EXPECT_EQ(StatusCode::OK_200, res->status);
  10299. }
  10300. EXPECT_EQ(1, request_count.load());
  10301. }
  10302. // Sends a raw request and verifies that there isn't a crash or exception.
  10303. static void test_raw_request(const std::string &req,
  10304. std::string *out = nullptr) {
  10305. Server svr;
  10306. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10307. res.set_content("ok", "text/plain");
  10308. });
  10309. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10310. res.set_content("ok", "text/plain");
  10311. });
  10312. svr.Get("/header_field_value_check",
  10313. [&](const Request & /*req*/, Response &res) {
  10314. res.set_content("ok", "text/plain");
  10315. });
  10316. svr.CustomRoute("PROPFIND", "/dav",
  10317. [&](const Request & /*req*/, Response &res) {
  10318. res.status = StatusCode::MultiStatus_207;
  10319. });
  10320. // Server read timeout must be longer than the client read timeout for the
  10321. // bug to reproduce, probably to force the server to process a request
  10322. // without a trailing blank line.
  10323. const time_t client_read_timeout_sec = 1;
  10324. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10325. bool listen_thread_ok = false;
  10326. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10327. auto se = detail::scope_exit([&] {
  10328. svr.stop();
  10329. t.join();
  10330. ASSERT_FALSE(svr.is_running());
  10331. EXPECT_TRUE(listen_thread_ok);
  10332. });
  10333. svr.wait_until_ready();
  10334. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10335. }
  10336. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10337. // A certain header line causes an exception if the header property is parsed
  10338. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10339. test_raw_request(
  10340. "GET /hi HTTP/1.1\r\n"
  10341. " : "
  10342. " "
  10343. " ");
  10344. }
  10345. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10346. // A certain header line causes an exception if the header property *name* is
  10347. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10348. // greedy matcher and requires backtracking when there are a lot of ":"
  10349. // characters.
  10350. // This occurs with libc++ but not libstdc++.
  10351. test_raw_request(
  10352. "GET /hi HTTP/1.1\r\n"
  10353. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10354. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10355. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10356. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10357. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10358. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10359. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10360. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10361. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10362. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10363. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10364. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10365. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10366. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10367. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10368. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10369. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10370. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10371. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10372. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10373. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10374. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10375. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10376. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10377. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10378. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10379. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10380. "&&&%%%");
  10381. }
  10382. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10383. // Make sure this doesn't crash the server.
  10384. // In a previous version of the header line regex, the "\r" rendered the line
  10385. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10386. // a new position where the leading white space ended and the field value
  10387. // began.
  10388. // The crash occurs with libc++ but not libstdc++.
  10389. test_raw_request("GET /hi HTTP/1.1\r\n"
  10390. "a:" +
  10391. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10392. "\r\n"
  10393. "\r\n");
  10394. }
  10395. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10396. const char *rejected[] = {
  10397. // RFC 9112 §3: one SP between the parts, and nothing else
  10398. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10399. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10400. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10401. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10402. // A request-target has no fragment
  10403. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10404. // An HTTP/1.1 request needs a Host
  10405. "GET /hi HTTP/1.1\r\n\r\n",
  10406. };
  10407. for (auto request : rejected) {
  10408. std::string out;
  10409. test_raw_request(request, &out);
  10410. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10411. }
  10412. std::string out;
  10413. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10414. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10415. }
  10416. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10417. // RFC 9112 §6.1
  10418. const char *requests[] = {
  10419. "PUT /put_hi HTTP/1.1\r\n"
  10420. "Host: localhost\r\n"
  10421. "Content-Length: 0\r\n"
  10422. "Transfer-Encoding: chunked\r\n"
  10423. "\r\n"
  10424. "0\r\n\r\n",
  10425. "PUT /put_hi HTTP/1.0\r\n"
  10426. "Connection: keep-alive\r\n"
  10427. "Transfer-Encoding: chunked\r\n"
  10428. "\r\n"
  10429. "0\r\n\r\n",
  10430. };
  10431. for (auto request : requests) {
  10432. std::string out;
  10433. test_raw_request(request, &out);
  10434. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10435. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10436. }
  10437. }
  10438. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10439. std::string out;
  10440. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10441. "Content-Type: text/plain\r\n"
  10442. "Transfer-Encoding: chunked\r\n"
  10443. "\r\n"
  10444. "nothex\r\n",
  10445. &out);
  10446. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10447. }
  10448. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10449. std::string out;
  10450. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10451. "Content-Type: text/plain\r\n"
  10452. "Transfer-Encoding: chunked\r\n"
  10453. "\r\n"
  10454. "3\r\n"
  10455. "xyz\r\n"
  10456. "NaN\r\n",
  10457. &out);
  10458. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10459. }
  10460. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10461. std::string out;
  10462. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10463. "Content-Type: text/plain\r\n"
  10464. "Transfer-Encoding: chunked\r\n"
  10465. "\r\n"
  10466. // Length is too large for 64 bits.
  10467. "1ffffffffffffffff\r\n"
  10468. "xyz\r\n",
  10469. &out);
  10470. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10471. }
  10472. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10473. test_raw_request("GET /hi HTTP/1.1\r\n"
  10474. "Content-Type: text/plain\r\n\r");
  10475. }
  10476. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10477. std::string out;
  10478. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10479. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10480. }
  10481. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10482. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10483. std::string out;
  10484. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10485. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10486. }
  10487. }
  10488. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10489. std::string out;
  10490. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10491. "Host: localhost\r\n"
  10492. "Connection: close\r\n\r\n",
  10493. &out);
  10494. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10495. }
  10496. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10497. Server svr;
  10498. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10499. EXPECT_TRUE(!req.remote_addr.empty());
  10500. });
  10501. thread t = thread([&] { svr.listen(HOST, PORT); });
  10502. auto se = detail::scope_exit([&] {
  10503. svr.stop();
  10504. t.join();
  10505. ASSERT_FALSE(svr.is_running());
  10506. });
  10507. svr.wait_until_ready();
  10508. // Send an invalid request line to trigger Bad Request
  10509. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10510. std::string out;
  10511. ASSERT_TRUE(send_request(5, bad_req, &out));
  10512. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10513. }
  10514. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10515. // answered right away rather than blocking on a read that waits for EOF.
  10516. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10517. std::string out;
  10518. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10519. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10520. }
  10521. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10522. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10523. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10524. for (const auto *method : methods) {
  10525. Server svr;
  10526. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10527. EXPECT_FALSE(svr.is_valid()) << method;
  10528. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10529. }
  10530. }
  10531. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10532. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10533. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10534. for (const auto *method : methods) {
  10535. Server svr;
  10536. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10537. EXPECT_FALSE(svr.is_valid()) << method;
  10538. }
  10539. }
  10540. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10541. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10542. "COPY", "MOVE", "LOCK",
  10543. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10544. Server svr;
  10545. for (const auto *method : methods) {
  10546. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10547. }
  10548. EXPECT_TRUE(svr.is_valid());
  10549. }
  10550. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10551. Server svr;
  10552. svr.CustomRoute("POST", "/x",
  10553. [](const Request &, Response &, const ContentReader &) {});
  10554. EXPECT_FALSE(svr.is_valid());
  10555. }
  10556. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10557. Server svr;
  10558. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10559. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10560. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10561. EXPECT_FALSE(svr.is_valid());
  10562. }
  10563. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10564. Server svr;
  10565. auto captured = Error::Success;
  10566. svr.set_error_logger(
  10567. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10568. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10569. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10570. }
  10571. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10572. std::string out;
  10573. std::string request(
  10574. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10575. test_raw_request(request, &out);
  10576. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10577. }
  10578. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10579. std::string out;
  10580. std::string request(
  10581. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10582. test_raw_request(request, &out);
  10583. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10584. }
  10585. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10586. std::string out;
  10587. std::string request(
  10588. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10589. test_raw_request(request, &out);
  10590. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10591. }
  10592. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10593. std::string out;
  10594. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10595. "Host: localhost\r\n"
  10596. "Test: \r\n\r\n",
  10597. &out);
  10598. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10599. }
  10600. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10601. Server svr;
  10602. std::string x_custom;
  10603. std::string cookie;
  10604. std::string xff;
  10605. std::string x_unicode;
  10606. std::string x_iis;
  10607. svr.Get("/check", [&](const Request &req, Response &res) {
  10608. x_custom = req.get_header_value("X-Custom");
  10609. cookie = req.get_header_value("Cookie");
  10610. xff = req.get_header_value("X-Forwarded-For");
  10611. x_unicode = req.get_header_value("X-Unicode");
  10612. x_iis = req.get_header_value("X-IIS");
  10613. res.set_content("ok", "text/plain");
  10614. });
  10615. thread t = thread([&] { svr.listen(HOST, PORT); });
  10616. auto se = detail::scope_exit([&] {
  10617. svr.stop();
  10618. t.join();
  10619. ASSERT_FALSE(svr.is_running());
  10620. });
  10621. svr.wait_until_ready();
  10622. const std::string req = "GET /check HTTP/1.1\r\n"
  10623. "Host: localhost\r\n"
  10624. "X-Custom: a%0D%0AInjected: b\r\n"
  10625. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10626. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10627. "X-Unicode: %E3%81%82\r\n"
  10628. "X-IIS: %u00E9\r\n"
  10629. "Connection: close\r\n"
  10630. "\r\n";
  10631. std::string res;
  10632. ASSERT_TRUE(send_request(5, req, &res));
  10633. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10634. // Every value must be returned verbatim (wire form), with no decoding.
  10635. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10636. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10637. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10638. EXPECT_EQ("%E3%81%82", x_unicode);
  10639. EXPECT_EQ("%u00E9", x_iis);
  10640. }
  10641. // Applications that previously relied on automatic percent-decoding can
  10642. // reproduce the old behavior by explicitly calling decode_path_component()
  10643. // or, for RFC 3986 conformance, decode_uri_component().
  10644. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10645. Server svr;
  10646. std::string decoded;
  10647. svr.Get("/check", [&](const Request &req, Response &res) {
  10648. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10649. res.set_content("ok", "text/plain");
  10650. });
  10651. thread t = thread([&] { svr.listen(HOST, PORT); });
  10652. auto se = detail::scope_exit([&] {
  10653. svr.stop();
  10654. t.join();
  10655. ASSERT_FALSE(svr.is_running());
  10656. });
  10657. svr.wait_until_ready();
  10658. const std::string req = "GET /check HTTP/1.1\r\n"
  10659. "Host: localhost\r\n"
  10660. "X-Custom: hello%20world\r\n"
  10661. "Connection: close\r\n"
  10662. "\r\n";
  10663. std::string res;
  10664. ASSERT_TRUE(send_request(5, req, &res));
  10665. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10666. EXPECT_EQ("hello world", decoded);
  10667. }
  10668. // Regression test for #2033. Browsers send Referer values that include
  10669. // percent-encoded characters such as %0A inside the URL. Decoding the
  10670. // header value would either trip the post-decode CR/LF/NUL guard (the
  10671. // original bug, returning 400) or, after that guard was relaxed, silently
  10672. // store a literal LF — both unacceptable. The wire form must round-trip.
  10673. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10674. Server svr;
  10675. std::string referer;
  10676. svr.Get("/check", [&](const Request &req, Response &res) {
  10677. referer = req.get_header_value("Referer");
  10678. res.set_content("ok", "text/plain");
  10679. });
  10680. thread t = thread([&] { svr.listen(HOST, PORT); });
  10681. auto se = detail::scope_exit([&] {
  10682. svr.stop();
  10683. t.join();
  10684. ASSERT_FALSE(svr.is_running());
  10685. });
  10686. svr.wait_until_ready();
  10687. const std::string req = "GET /check HTTP/1.1\r\n"
  10688. "Host: localhost\r\n"
  10689. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10690. "Connection: close\r\n"
  10691. "\r\n";
  10692. std::string res;
  10693. ASSERT_TRUE(send_request(5, req, &res));
  10694. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10695. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10696. }
  10697. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10698. Server svr;
  10699. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10700. res.set_header("Cache-Control", "no-cache");
  10701. res.set_chunked_content_provider(
  10702. "text/event-stream", [](size_t offset, DataSink &sink) {
  10703. std::string s = "data:";
  10704. s += std::to_string(offset);
  10705. s += "\n\n";
  10706. auto ret = sink.write(s.data(), s.size());
  10707. EXPECT_TRUE(ret);
  10708. std::this_thread::sleep_for(std::chrono::seconds(1));
  10709. return true;
  10710. });
  10711. });
  10712. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10713. svr.wait_until_ready();
  10714. Client client(HOST, PORT);
  10715. const Headers headers = {{"Accept", "text/event-stream"}};
  10716. auto get_thread = std::thread([&client, &headers]() {
  10717. auto res = client.Get(
  10718. "/events", headers,
  10719. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10720. });
  10721. auto se = detail::scope_exit([&] {
  10722. svr.stop();
  10723. get_thread.join();
  10724. listen_thread.join();
  10725. ASSERT_FALSE(svr.is_running());
  10726. });
  10727. // Give GET time to get a few messages.
  10728. std::this_thread::sleep_for(std::chrono::seconds(2));
  10729. }
  10730. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10731. httplib::Server svr;
  10732. svr.Post("/hi",
  10733. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10734. res.status = StatusCode::OK_200;
  10735. });
  10736. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10737. svr.wait_until_ready();
  10738. Client cli(HOST, PORT);
  10739. auto res = cli.Post("/hi", "data", "text/plain");
  10740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10741. EXPECT_EQ(StatusCode::OK_200, res->status);
  10742. svr.stop();
  10743. thread.join();
  10744. ASSERT_FALSE(svr.is_running());
  10745. res = cli.Post("/hi", "data", "text/plain");
  10746. ASSERT_FALSE(res);
  10747. }
  10748. TEST(ServerStopTest, ListenFailure) {
  10749. Server svr;
  10750. auto t = thread([&]() {
  10751. auto ret = svr.listen("????", PORT);
  10752. EXPECT_FALSE(ret);
  10753. });
  10754. svr.wait_until_ready();
  10755. svr.stop();
  10756. t.join();
  10757. }
  10758. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10759. TEST(ServerStopTest, Decommision) {
  10760. Server svr;
  10761. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10762. for (int i = 0; i < 4; i++) {
  10763. auto is_even = !(i % 2);
  10764. std::thread t{[&] {
  10765. try {
  10766. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10767. if (is_even) {
  10768. throw std::runtime_error("Some thing that happens to go wrong.");
  10769. }
  10770. svr.listen(HOST, PORT);
  10771. } catch (...) { svr.decommission(); }
  10772. }};
  10773. svr.wait_until_ready();
  10774. // Server is up
  10775. {
  10776. Client cli(HOST, PORT);
  10777. auto res = cli.Get("/hi");
  10778. if (is_even) {
  10779. EXPECT_FALSE(res);
  10780. } else {
  10781. EXPECT_TRUE(res);
  10782. EXPECT_EQ("hi...", res->body);
  10783. }
  10784. }
  10785. svr.stop();
  10786. t.join();
  10787. // Server is down...
  10788. {
  10789. Client cli(HOST, PORT);
  10790. auto res = cli.Get("/hi");
  10791. EXPECT_FALSE(res);
  10792. }
  10793. }
  10794. }
  10795. #endif
  10796. // Helper function for string body upload progress tests
  10797. template <typename SetupHandler, typename ClientCall>
  10798. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10799. ClientCall &&client_call,
  10800. const string &body) {
  10801. Server svr;
  10802. setup_handler(svr);
  10803. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10804. auto se = detail::scope_exit([&] {
  10805. svr.stop();
  10806. t.join();
  10807. });
  10808. svr.wait_until_ready();
  10809. Client cli(HOST, PORT);
  10810. vector<uint64_t> progress_values;
  10811. bool progress_called = false;
  10812. auto res =
  10813. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10814. progress_values.push_back(current);
  10815. progress_called = true;
  10816. return true;
  10817. });
  10818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10819. EXPECT_EQ(200, res->status);
  10820. EXPECT_TRUE(progress_called);
  10821. }
  10822. TEST(UploadProgressTest, PostStringBodyBasic) {
  10823. TestStringBodyUploadProgress(
  10824. [](Server &svr) {
  10825. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10826. res.set_content("received", "text/plain");
  10827. });
  10828. },
  10829. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10830. return cli.Post("/test", body, "text/plain", progress_callback);
  10831. },
  10832. "test data for upload progress");
  10833. }
  10834. TEST(UploadProgressTest, PutStringBodyBasic) {
  10835. TestStringBodyUploadProgress(
  10836. [](Server &svr) {
  10837. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10838. res.set_content("put received", "text/plain");
  10839. });
  10840. },
  10841. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10842. return cli.Put("/test", body, "text/plain", progress_callback);
  10843. },
  10844. "put test data for upload progress");
  10845. }
  10846. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10847. TestStringBodyUploadProgress(
  10848. [](Server &svr) {
  10849. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10850. res.set_content("patch received", "text/plain");
  10851. });
  10852. },
  10853. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10854. return cli.Patch("/test", body, "text/plain", progress_callback);
  10855. },
  10856. "patch test data for upload progress");
  10857. }
  10858. // Helper function for content provider upload progress tests
  10859. template <typename SetupHandler, typename ClientCall>
  10860. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10861. ClientCall &&client_call) {
  10862. Server svr;
  10863. setup_handler(svr);
  10864. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10865. auto se = detail::scope_exit([&] {
  10866. svr.stop();
  10867. t.join();
  10868. });
  10869. svr.wait_until_ready();
  10870. Client cli(HOST, PORT);
  10871. vector<uint64_t> progress_values;
  10872. auto res =
  10873. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10874. progress_values.push_back(current);
  10875. return true;
  10876. });
  10877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10878. EXPECT_EQ(200, res->status);
  10879. EXPECT_FALSE(progress_values.empty());
  10880. }
  10881. TEST(UploadProgressTest, PostContentProviderProgress) {
  10882. TestContentProviderUploadProgress(
  10883. [](Server &svr) {
  10884. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10885. res.set_content("provider received", "text/plain");
  10886. });
  10887. },
  10888. [](Client &cli, UploadProgress progress_callback) {
  10889. return cli.Post(
  10890. "/test", 9,
  10891. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10892. sink.os << "test data";
  10893. return true;
  10894. },
  10895. "text/plain", progress_callback);
  10896. });
  10897. }
  10898. // Helper function for multipart upload progress tests
  10899. template <typename SetupHandler, typename ClientCall>
  10900. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10901. ClientCall &&client_call,
  10902. const string &endpoint) {
  10903. Server svr;
  10904. setup_handler(svr);
  10905. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10906. auto se = detail::scope_exit([&] {
  10907. svr.stop();
  10908. t.join();
  10909. });
  10910. svr.wait_until_ready();
  10911. Client cli(HOST, PORT);
  10912. vector<uint64_t> progress_values;
  10913. UploadFormDataItems items = {
  10914. {"field1", "value1", "", ""},
  10915. {"field2", "longer value for progress tracking test", "", ""},
  10916. {"file1", "file content data for upload progress", "test.txt",
  10917. "text/plain"}};
  10918. auto res = client_call(cli, endpoint, items,
  10919. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10920. progress_values.push_back(current);
  10921. return true;
  10922. });
  10923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10924. EXPECT_EQ(200, res->status);
  10925. EXPECT_FALSE(progress_values.empty());
  10926. }
  10927. TEST(UploadProgressTest, PostMultipartProgress) {
  10928. TestMultipartUploadProgress(
  10929. [](Server &svr) {
  10930. svr.Post("/multipart", [](const Request &req, Response &res) {
  10931. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10932. res.set_content("multipart received", "text/plain");
  10933. });
  10934. },
  10935. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10936. UploadProgress progress_callback) {
  10937. return cli.Post(endpoint, items, progress_callback);
  10938. },
  10939. "/multipart");
  10940. }
  10941. // Helper function for basic download progress tests
  10942. template <typename SetupHandler, typename ClientCall>
  10943. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10944. ClientCall &&client_call, const string &endpoint,
  10945. size_t expected_content_size) {
  10946. Server svr;
  10947. setup_handler(svr);
  10948. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10949. auto se = detail::scope_exit([&] {
  10950. svr.stop();
  10951. t.join();
  10952. });
  10953. svr.wait_until_ready();
  10954. Client cli(HOST, PORT);
  10955. vector<uint64_t> progress_values;
  10956. auto res = client_call(cli, endpoint,
  10957. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10958. progress_values.push_back(current);
  10959. return true;
  10960. });
  10961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10962. EXPECT_EQ(200, res->status);
  10963. EXPECT_FALSE(progress_values.empty());
  10964. EXPECT_EQ(expected_content_size, res->body.size());
  10965. }
  10966. TEST(DownloadProgressTest, GetBasic) {
  10967. TestBasicDownloadProgress(
  10968. [](Server &svr) {
  10969. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10970. string content(1000, 'D');
  10971. res.set_content(content, "text/plain");
  10972. });
  10973. },
  10974. [](Client &cli, const string &endpoint,
  10975. DownloadProgress progress_callback) {
  10976. return cli.Get(endpoint, progress_callback);
  10977. },
  10978. "/download", 1000u);
  10979. }
  10980. // Helper function for content receiver download progress tests
  10981. template <typename SetupHandler, typename ClientCall>
  10982. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10983. ClientCall &&client_call,
  10984. const string &endpoint,
  10985. size_t expected_content_size) {
  10986. Server svr;
  10987. setup_handler(svr);
  10988. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10989. auto se = detail::scope_exit([&] {
  10990. svr.stop();
  10991. t.join();
  10992. });
  10993. svr.wait_until_ready();
  10994. Client cli(HOST, PORT);
  10995. vector<uint64_t> progress_values;
  10996. string received_body;
  10997. auto res = client_call(
  10998. cli, endpoint,
  10999. [&](const char *data, size_t data_length) -> bool {
  11000. received_body.append(data, data_length);
  11001. return true;
  11002. },
  11003. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11004. progress_values.push_back(current);
  11005. return true;
  11006. });
  11007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11008. EXPECT_EQ(200, res->status);
  11009. EXPECT_FALSE(progress_values.empty());
  11010. EXPECT_EQ(expected_content_size, received_body.size());
  11011. EXPECT_TRUE(res->body.empty());
  11012. }
  11013. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11014. TestContentReceiverDownloadProgress(
  11015. [](Server &svr) {
  11016. svr.Get("/download-receiver",
  11017. [](const Request & /*req*/, Response &res) {
  11018. string content(2000, 'R');
  11019. res.set_content(content, "text/plain");
  11020. });
  11021. },
  11022. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11023. DownloadProgress progress_callback) {
  11024. return cli.Get(endpoint, content_receiver, progress_callback);
  11025. },
  11026. "/download-receiver", 2000u);
  11027. }
  11028. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11029. // A provider reaching a pass with nothing to hand over - an empty buffer
  11030. // popped off a queue, say - must not be taken to mean the body is finished.
  11031. // It used to end the loop with the terminating chunk unwritten while the
  11032. // server still considered the response complete, so the peer waited for an
  11033. // end that never arrived.
  11034. Server svr;
  11035. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11036. auto step = std::make_shared<int>(0);
  11037. res.set_chunked_content_provider("text/plain",
  11038. [step](size_t /*offset*/, DataSink &sink) {
  11039. switch ((*step)++) {
  11040. case 0: sink.write("", 0); break;
  11041. case 1: sink.write("hello", 5); break;
  11042. default: sink.done(); break;
  11043. }
  11044. return true;
  11045. });
  11046. });
  11047. auto port = svr.bind_to_any_port(HOST);
  11048. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11049. auto listen_se = detail::scope_exit([&] {
  11050. svr.stop();
  11051. listen_thread.join();
  11052. ASSERT_FALSE(svr.is_running());
  11053. });
  11054. svr.wait_until_ready();
  11055. Client cli(HOST, port);
  11056. // Without the fix the body is never terminated, so bound the wait rather
  11057. // than letting the test hang on the default read timeout.
  11058. cli.set_read_timeout(5, 0);
  11059. auto res = cli.Get("/stream");
  11060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11061. EXPECT_EQ(StatusCode::OK_200, res->status);
  11062. EXPECT_EQ("hello", res->body);
  11063. }
  11064. TEST(StreamingTest, NoContentLengthStreaming) {
  11065. Server svr;
  11066. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11067. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11068. if (offset < 6) {
  11069. sink.os << (offset < 3 ? "a" : "b");
  11070. } else {
  11071. sink.done();
  11072. }
  11073. return true;
  11074. });
  11075. });
  11076. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11077. auto listen_se = detail::scope_exit([&] {
  11078. svr.stop();
  11079. listen_thread.join();
  11080. ASSERT_FALSE(svr.is_running());
  11081. });
  11082. svr.wait_until_ready();
  11083. Client client(HOST, PORT);
  11084. auto get_thread = std::thread([&client]() {
  11085. std::string s;
  11086. auto res =
  11087. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11088. s += std::string(data, len);
  11089. return true;
  11090. });
  11091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11092. EXPECT_EQ(StatusCode::OK_200, res->status);
  11093. EXPECT_EQ("aaabbb", s);
  11094. });
  11095. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11096. // Give GET time to get a few messages.
  11097. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11098. }
  11099. TEST(MountTest, Unmount) {
  11100. Server svr;
  11101. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11102. auto se = detail::scope_exit([&] {
  11103. svr.stop();
  11104. listen_thread.join();
  11105. ASSERT_FALSE(svr.is_running());
  11106. });
  11107. svr.wait_until_ready();
  11108. Client cli("localhost", PORT);
  11109. svr.set_mount_point("/mount2", "./www2");
  11110. auto res = cli.Get("/");
  11111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11112. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11113. res = cli.Get("/mount2/dir/test.html");
  11114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11115. EXPECT_EQ(StatusCode::OK_200, res->status);
  11116. svr.set_mount_point("/", "./www");
  11117. res = cli.Get("/dir/");
  11118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11119. EXPECT_EQ(StatusCode::OK_200, res->status);
  11120. svr.remove_mount_point("/");
  11121. res = cli.Get("/dir/");
  11122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11123. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11124. svr.remove_mount_point("/mount2");
  11125. res = cli.Get("/mount2/dir/test.html");
  11126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11127. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11128. }
  11129. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11130. Server svr;
  11131. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11132. svr.Get("/api/hello", [](const Request &, Response &res) {
  11133. res.set_content("api", "text/plain");
  11134. });
  11135. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11136. auto se = detail::scope_exit([&] {
  11137. svr.stop();
  11138. listen_thread.join();
  11139. ASSERT_FALSE(svr.is_running());
  11140. });
  11141. svr.wait_until_ready();
  11142. Client cli(HOST, PORT);
  11143. auto res = cli.Get("/dir/test.html");
  11144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11145. EXPECT_EQ(StatusCode::OK_200, res->status);
  11146. res = cli.Get("/api/hello");
  11147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11148. EXPECT_EQ(StatusCode::OK_200, res->status);
  11149. EXPECT_EQ("api", res->body);
  11150. }
  11151. TEST(MountTest, PathSegmentBoundary) {
  11152. Server svr;
  11153. svr.set_mount_point("/mount2", "./www2");
  11154. svr.set_mount_point("/", "./www");
  11155. auto port = svr.bind_to_any_port(HOST);
  11156. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11157. auto se = detail::scope_exit([&] {
  11158. svr.stop();
  11159. listen_thread.join();
  11160. ASSERT_FALSE(svr.is_running());
  11161. });
  11162. svr.wait_until_ready();
  11163. Client cli(HOST, port);
  11164. auto res = cli.Get("/mount2/dir/test.html");
  11165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11166. EXPECT_EQ(StatusCode::OK_200, res->status);
  11167. // "/mount2" must not match part-way through a path segment.
  11168. res = cli.Get("/mount2dir/test.html");
  11169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11170. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11171. // A mount point ending in '/' keeps matching every path below it.
  11172. res = cli.Get("/dir/test.html");
  11173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11174. EXPECT_EQ(StatusCode::OK_200, res->status);
  11175. }
  11176. TEST(MountTest, Redicect) {
  11177. Server svr;
  11178. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11179. auto se = detail::scope_exit([&] {
  11180. svr.stop();
  11181. listen_thread.join();
  11182. ASSERT_FALSE(svr.is_running());
  11183. });
  11184. svr.set_mount_point("/", "./www");
  11185. svr.wait_until_ready();
  11186. Client cli("localhost", PORT);
  11187. auto res = cli.Get("/dir/");
  11188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11189. EXPECT_EQ(StatusCode::OK_200, res->status);
  11190. res = cli.Get("/dir");
  11191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11192. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11193. res = cli.Get("/file");
  11194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11195. EXPECT_EQ(StatusCode::OK_200, res->status);
  11196. res = cli.Get("/file/");
  11197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11198. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11199. cli.set_follow_location(true);
  11200. res = cli.Get("/dir");
  11201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11202. EXPECT_EQ(StatusCode::OK_200, res->status);
  11203. }
  11204. TEST(MountTest, MultibytesPathName) {
  11205. Server svr;
  11206. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11207. auto se = detail::scope_exit([&] {
  11208. svr.stop();
  11209. listen_thread.join();
  11210. ASSERT_FALSE(svr.is_running());
  11211. });
  11212. svr.set_mount_point("/", "./www");
  11213. svr.wait_until_ready();
  11214. Client cli("localhost", PORT);
  11215. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11217. EXPECT_EQ(StatusCode::OK_200, res->status);
  11218. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11219. }
  11220. // A mount point serves no path with an empty segment or one ending in '.' or
  11221. // a space, so a guard in the pre-routing handler sees the path of every file
  11222. // that is served
  11223. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11224. Server svr;
  11225. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11226. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11227. if (req.path == "/dir/test.html") {
  11228. res.status = StatusCode::Unauthorized_401;
  11229. return Server::HandlerResponse::Handled;
  11230. }
  11231. return Server::HandlerResponse::Unhandled;
  11232. });
  11233. auto port = svr.bind_to_any_port(HOST);
  11234. ASSERT_LT(0, port);
  11235. thread t = thread([&] { svr.listen_after_bind(); });
  11236. auto se = detail::scope_exit([&] {
  11237. svr.stop();
  11238. t.join();
  11239. ASSERT_FALSE(svr.is_running());
  11240. });
  11241. svr.wait_until_ready();
  11242. Client cli(HOST, port);
  11243. for (auto path :
  11244. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11245. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11246. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11247. "/dir/test.html%3A%3A$DATA"}) {
  11248. SCOPED_TRACE(path);
  11249. auto res = cli.Get(path);
  11250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11251. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11252. }
  11253. }
  11254. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11255. Server svr;
  11256. svr.set_mount_point("/", "./www");
  11257. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11258. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11259. auto port = svr.bind_to_any_port(HOST);
  11260. ASSERT_GT(port, 0);
  11261. thread t = thread([&] { svr.listen_after_bind(); });
  11262. auto se = detail::scope_exit([&] {
  11263. svr.stop();
  11264. t.join();
  11265. ASSERT_FALSE(svr.is_running());
  11266. });
  11267. svr.wait_until_ready();
  11268. Client cli(HOST, port);
  11269. auto res = cli.Get("/dir/test.abcde");
  11270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11271. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11272. res = cli.Get("/dir/test.html");
  11273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11274. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11275. }
  11276. #ifdef _WIN32
  11277. // Issue #2435: mmap::open() must succeed even when another handle holds
  11278. // the file open for writing (e.g. an active log file).
  11279. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11280. const char *path = "mmap_concurrent_writer_test.txt";
  11281. const char *content = "hello";
  11282. {
  11283. std::ofstream f(path, std::ios::binary);
  11284. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11285. }
  11286. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11287. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11288. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11289. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11290. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11291. detail::mmap m(path);
  11292. ASSERT_TRUE(m.is_open());
  11293. EXPECT_EQ(strlen(content), m.size());
  11294. char buf[8];
  11295. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11296. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11297. }
  11298. #endif
  11299. #ifndef _WIN32
  11300. // A directory or a device has no size to serve.
  11301. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11302. const char *path = "./mmap_not_regular_test_dir";
  11303. ASSERT_EQ(0, ::mkdir(path, 0755));
  11304. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11305. for (auto p : {path, "/dev/null"}) {
  11306. detail::mmap m(p);
  11307. EXPECT_FALSE(m.is_open()) << p;
  11308. EXPECT_EQ(0U, m.size()) << p;
  11309. }
  11310. Server svr;
  11311. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11312. res.set_file_content("/dev/null");
  11313. });
  11314. auto port = svr.bind_to_any_port(HOST);
  11315. thread t = thread([&] { svr.listen_after_bind(); });
  11316. auto se = detail::scope_exit([&] {
  11317. svr.stop();
  11318. t.join();
  11319. });
  11320. svr.wait_until_ready();
  11321. auto res = Client(HOST, port).Get("/null");
  11322. ASSERT_TRUE(res);
  11323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11324. }
  11325. #endif
  11326. #ifdef __linux__
  11327. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11328. TEST(MmapTest, FileIsNotMapped) {
  11329. const char *path = "mmap_not_mapped_test.txt";
  11330. {
  11331. std::ofstream f(path, std::ios::binary);
  11332. f << "hello";
  11333. }
  11334. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11335. detail::mmap m(path);
  11336. ASSERT_TRUE(m.is_open());
  11337. std::ifstream maps("/proc/self/maps");
  11338. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11339. std::istreambuf_iterator<char>());
  11340. EXPECT_EQ(std::string::npos, mappings.find(path));
  11341. }
  11342. #endif
  11343. TEST(KeepAliveTest, ReadTimeout) {
  11344. Server svr;
  11345. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11346. std::this_thread::sleep_for(std::chrono::seconds(2));
  11347. res.set_content("a", "text/plain");
  11348. });
  11349. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11350. res.set_content("b", "text/plain");
  11351. });
  11352. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. listen_thread.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli("localhost", PORT);
  11360. cli.set_keep_alive(true);
  11361. cli.set_read_timeout(std::chrono::seconds(1));
  11362. auto resa = cli.Get("/a");
  11363. ASSERT_FALSE(resa);
  11364. EXPECT_EQ(Error::Read, resa.error());
  11365. auto resb = cli.Get("/b");
  11366. ASSERT_TRUE(resb);
  11367. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11368. EXPECT_EQ("b", resb->body);
  11369. }
  11370. TEST(KeepAliveTest, MaxCount) {
  11371. size_t keep_alive_max_count = 3;
  11372. Server svr;
  11373. svr.set_keep_alive_max_count(keep_alive_max_count);
  11374. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11375. res.set_content("Hello World!", "text/plain");
  11376. });
  11377. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11378. auto se = detail::scope_exit([&] {
  11379. svr.stop();
  11380. listen_thread.join();
  11381. ASSERT_FALSE(svr.is_running());
  11382. });
  11383. svr.wait_until_ready();
  11384. Client cli(HOST, PORT);
  11385. cli.set_keep_alive(true);
  11386. for (size_t i = 0; i < 5; i++) {
  11387. auto result = cli.Get("/hi");
  11388. ASSERT_TRUE(result);
  11389. EXPECT_EQ(StatusCode::OK_200, result->status);
  11390. if (i == keep_alive_max_count - 1) {
  11391. EXPECT_EQ("close", result->get_header_value("Connection"));
  11392. } else {
  11393. EXPECT_FALSE(result->has_header("Connection"));
  11394. }
  11395. }
  11396. }
  11397. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11398. // can pull the next one into the server's buffer. The server must serve it
  11399. // without waiting for the socket to become readable again. The keep-alive
  11400. // timeout outlasts the client's read timeout, so a request left waiting for it
  11401. // shows up as a missing response.
  11402. static void serve_pipelining_routes(Server &svr,
  11403. const std::function<void(int)> &client) {
  11404. svr.set_keep_alive_timeout(5);
  11405. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11406. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11407. });
  11408. svr.Post("/echo", [](const Request &req, Response &res) {
  11409. res.set_content("echo " + req.body, "text/plain");
  11410. });
  11411. auto port = svr.bind_to_any_port(HOST);
  11412. thread t = thread([&] { svr.listen_after_bind(); });
  11413. auto se = detail::scope_exit([&] {
  11414. svr.stop();
  11415. t.join();
  11416. });
  11417. svr.wait_until_ready();
  11418. client(port);
  11419. }
  11420. static std::string
  11421. send_pipelined_requests(const std::vector<std::string> &parts) {
  11422. Server svr;
  11423. std::string res;
  11424. serve_pipelining_routes(svr, [&](int port) {
  11425. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11426. });
  11427. return res;
  11428. }
  11429. static void expect_in_order(const std::string &res,
  11430. const std::vector<std::string> &bodies) {
  11431. size_t pos = 0;
  11432. for (const auto &body : bodies) {
  11433. pos = res.find(body, pos);
  11434. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11435. pos += body.size();
  11436. }
  11437. }
  11438. TEST(KeepAliveTest, PipelinedRequests) {
  11439. auto res = send_pipelined_requests(
  11440. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11441. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11442. "Content-Length: 4\r\n\r\nbody"
  11443. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11444. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11445. }
  11446. // The second request starts in the server's buffer and ends on the socket.
  11447. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11448. auto res =
  11449. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11450. "GET /hi/2 HTTP/1.1\r\nHo",
  11451. "st: localhost\r\nConnection: close\r\n\r\n"});
  11452. expect_in_order(res, {"hi 1", "hi 2"});
  11453. }
  11454. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11455. // CRLF after a body does not turn into a 400 for the next request.
  11456. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11457. auto res = send_pipelined_requests(
  11458. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11459. "Content-Length: 4\r\n\r\nbody\r\n"
  11460. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11461. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11462. expect_in_order(res, {"echo body", "hi 2"});
  11463. }
  11464. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11465. // must not be served as the next request.
  11466. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11467. auto res = send_pipelined_requests(
  11468. {"INVALID REQUEST LINE\r\n\r\n"
  11469. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11470. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11471. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11472. }
  11473. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11474. // Over TLS, the next request is held by the TLS library as already decrypted
  11475. // data rather than on the socket.
  11476. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11477. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11478. std::string res;
  11479. serve_pipelining_routes(svr, [&](int port) {
  11480. // One part, so all three requests arrive in one TLS record
  11481. EXPECT_TRUE(send_ssl_request_in_parts(
  11482. 2,
  11483. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11484. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11485. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11486. &res, port));
  11487. });
  11488. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11489. }
  11490. #endif
  11491. TEST(KeepAliveTest, Issue1041) {
  11492. Server svr;
  11493. svr.set_keep_alive_timeout(3);
  11494. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11495. res.set_content("Hello World!", "text/plain");
  11496. });
  11497. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11498. auto se = detail::scope_exit([&] {
  11499. svr.stop();
  11500. listen_thread.join();
  11501. ASSERT_FALSE(svr.is_running());
  11502. });
  11503. svr.wait_until_ready();
  11504. Client cli(HOST, PORT);
  11505. cli.set_keep_alive(true);
  11506. auto result = cli.Get("/hi");
  11507. ASSERT_TRUE(result);
  11508. EXPECT_EQ(StatusCode::OK_200, result->status);
  11509. std::this_thread::sleep_for(std::chrono::seconds(5));
  11510. result = cli.Get("/hi");
  11511. ASSERT_TRUE(result);
  11512. EXPECT_EQ(StatusCode::OK_200, result->status);
  11513. }
  11514. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11515. Server svr;
  11516. svr.set_keep_alive_max_count(0);
  11517. std::set<int> remote_ports;
  11518. svr.Get("/hi", [&](const Request &req, Response &res) {
  11519. remote_ports.insert(req.remote_port);
  11520. res.set_content("hi", "text/plain");
  11521. });
  11522. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11523. auto se = detail::scope_exit([&] {
  11524. svr.stop();
  11525. listen_thread.join();
  11526. ASSERT_FALSE(svr.is_running());
  11527. });
  11528. svr.wait_until_ready();
  11529. Client cli(HOST, PORT);
  11530. cli.set_keep_alive(true);
  11531. for (int i = 0; i < 3; i++) {
  11532. auto res = cli.Get("/hi");
  11533. ASSERT_TRUE(res);
  11534. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11535. }
  11536. // All three over one connection
  11537. EXPECT_EQ(1u, remote_ports.size());
  11538. }
  11539. // Forward declaration (see the base64_encode note).
  11540. namespace httplib {
  11541. namespace detail {
  11542. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11543. } // namespace detail
  11544. } // namespace httplib
  11545. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11546. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11547. #ifndef _WIN32
  11548. signal(SIGPIPE, SIG_IGN);
  11549. #endif
  11550. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11551. ASSERT_NE(INVALID_SOCKET, srv);
  11552. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11553. default_socket_options(srv);
  11554. sockaddr_in addr{};
  11555. addr.sin_family = AF_INET;
  11556. addr.sin_port = 0;
  11557. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11558. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11559. ASSERT_EQ(0, ::listen(srv, 2));
  11560. socklen_t addr_len = sizeof(addr);
  11561. ASSERT_EQ(0,
  11562. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11563. auto port = ntohs(addr.sin_port);
  11564. struct Peer {
  11565. socket_t sock = INVALID_SOCKET;
  11566. #ifdef CPPHTTPLIB_SSL_ENABLED
  11567. tls::session_t session = nullptr;
  11568. #endif
  11569. };
  11570. #ifdef CPPHTTPLIB_SSL_ENABLED
  11571. tls::ctx_t ctx = nullptr;
  11572. if (use_tls) {
  11573. ctx = tls::create_server_context();
  11574. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11575. nullptr);
  11576. }
  11577. auto ctx_se = detail::scope_exit([&] {
  11578. if (ctx) { tls::free_context(ctx); }
  11579. });
  11580. #endif
  11581. auto close_peer = [](Peer &peer) {
  11582. #ifdef CPPHTTPLIB_SSL_ENABLED
  11583. if (peer.session) { tls::free_session(peer.session); }
  11584. #endif
  11585. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11586. };
  11587. auto accept_peer = [&]() {
  11588. Peer peer;
  11589. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11590. peer.sock = ::accept(srv, nullptr, nullptr);
  11591. if (peer.sock == INVALID_SOCKET) { return peer; }
  11592. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11593. #ifdef CPPHTTPLIB_SSL_ENABLED
  11594. if (use_tls) {
  11595. peer.session = tls::create_session(ctx, peer.sock);
  11596. tls::TlsError err;
  11597. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
  11598. close_peer(peer);
  11599. return Peer();
  11600. }
  11601. }
  11602. #endif
  11603. return peer;
  11604. };
  11605. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11606. #ifdef CPPHTTPLIB_SSL_ENABLED
  11607. tls::TlsError err;
  11608. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11609. #endif
  11610. return detail::read_socket(peer.sock, buf, len, 0);
  11611. };
  11612. auto read_head = [&](const Peer &peer) {
  11613. std::string head;
  11614. char buf[1024];
  11615. while (head.find("\r\n\r\n") == std::string::npos) {
  11616. auto n = read_some(peer, buf, sizeof(buf));
  11617. if (n <= 0) { break; }
  11618. head.append(buf, static_cast<size_t>(n));
  11619. }
  11620. };
  11621. auto send_text = [](const Peer &peer, const std::string &text) {
  11622. #ifdef CPPHTTPLIB_SSL_ENABLED
  11623. tls::TlsError err;
  11624. if (peer.session) {
  11625. tls::write(peer.session, text.data(), text.size(), err);
  11626. return;
  11627. }
  11628. #endif
  11629. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11630. };
  11631. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11632. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11633. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11634. // Sent once the first response is read, so that it lands on an idle socket
  11635. std::promise<void> first_response_read;
  11636. auto first_response_read_future = first_response_read.get_future();
  11637. auto server_thread = std::thread([&] {
  11638. auto peer1 = accept_peer();
  11639. if (peer1.sock == INVALID_SOCKET) { return; }
  11640. read_head(peer1);
  11641. if (same_write) {
  11642. send_text(peer1, first + stray);
  11643. } else {
  11644. send_text(peer1, first);
  11645. first_response_read_future.wait_for(std::chrono::seconds(5));
  11646. send_text(peer1, stray);
  11647. }
  11648. // peer1 stays open, so only the unread data can tell the client
  11649. auto peer2 = accept_peer();
  11650. if (peer2.sock != INVALID_SOCKET) {
  11651. read_head(peer2);
  11652. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11653. "Connection: close\r\n\r\nsecond");
  11654. close_peer(peer2);
  11655. }
  11656. close_peer(peer1);
  11657. });
  11658. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11659. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11660. std::to_string(port));
  11661. #ifdef CPPHTTPLIB_SSL_ENABLED
  11662. cli.enable_server_certificate_verification(false);
  11663. #endif
  11664. cli.set_keep_alive(true);
  11665. cli.set_read_timeout(5, 0);
  11666. auto res = cli.Get("/1");
  11667. first_response_read.set_value();
  11668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11669. EXPECT_EQ("first", res->body);
  11670. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11671. res = cli.Get("/2");
  11672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11673. EXPECT_EQ(StatusCode::OK_200, res->status);
  11674. EXPECT_EQ("second", res->body);
  11675. }
  11676. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11677. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11678. }
  11679. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11680. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11681. }
  11682. #ifdef CPPHTTPLIB_SSL_ENABLED
  11683. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11684. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11685. }
  11686. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11687. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11688. }
  11689. #endif
  11690. TEST(KeepAliveTest, Issue1959) {
  11691. Server svr;
  11692. svr.set_keep_alive_timeout(5);
  11693. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11694. res.set_content("a", "text/plain");
  11695. });
  11696. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11697. auto se = detail::scope_exit([&] {
  11698. if (!svr.is_running()) return;
  11699. svr.stop();
  11700. listen_thread.join();
  11701. ASSERT_FALSE(svr.is_running());
  11702. });
  11703. svr.wait_until_ready();
  11704. Client cli("localhost", PORT);
  11705. cli.set_keep_alive(true);
  11706. using namespace std::chrono;
  11707. auto start = steady_clock::now();
  11708. cli.Get("/a");
  11709. svr.stop();
  11710. listen_thread.join();
  11711. auto end = steady_clock::now();
  11712. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11713. EXPECT_LT(elapsed, 5000);
  11714. }
  11715. #ifdef CPPHTTPLIB_SSL_ENABLED
  11716. TEST(KeepAliveTest, SSLClientReconnection) {
  11717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11718. ASSERT_TRUE(svr.is_valid());
  11719. svr.set_keep_alive_timeout(1);
  11720. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11721. res.set_content("Hello World!", "text/plain");
  11722. });
  11723. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11724. auto se = detail::scope_exit([&] {
  11725. svr.stop();
  11726. listen_thread.join();
  11727. ASSERT_FALSE(svr.is_running());
  11728. });
  11729. svr.wait_until_ready();
  11730. SSLClient cli(HOST, PORT);
  11731. cli.enable_server_certificate_verification(false);
  11732. cli.set_keep_alive(true);
  11733. auto result = cli.Get("/hi");
  11734. ASSERT_TRUE(result);
  11735. EXPECT_EQ(StatusCode::OK_200, result->status);
  11736. result = cli.Get("/hi");
  11737. ASSERT_TRUE(result);
  11738. EXPECT_EQ(StatusCode::OK_200, result->status);
  11739. std::this_thread::sleep_for(std::chrono::seconds(2));
  11740. // Recoonect
  11741. result = cli.Get("/hi");
  11742. ASSERT_TRUE(result);
  11743. EXPECT_EQ(StatusCode::OK_200, result->status);
  11744. result = cli.Get("/hi");
  11745. ASSERT_TRUE(result);
  11746. EXPECT_EQ(StatusCode::OK_200, result->status);
  11747. }
  11748. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11750. ASSERT_TRUE(svr.is_valid());
  11751. svr.set_keep_alive_timeout(1);
  11752. std::string content = "reconnect";
  11753. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11754. res.set_content("Hello World!", "text/plain");
  11755. });
  11756. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11757. auto se = detail::scope_exit([&] {
  11758. svr.stop();
  11759. listen_thread.join();
  11760. ASSERT_FALSE(svr.is_running());
  11761. });
  11762. svr.wait_until_ready();
  11763. SSLClient cli(HOST, PORT);
  11764. cli.enable_server_certificate_verification(false);
  11765. cli.set_keep_alive(true);
  11766. auto result = cli.Post(
  11767. "/hi", content.size(),
  11768. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11769. sink.write(content.c_str(), content.size());
  11770. return true;
  11771. },
  11772. "text/plain");
  11773. ASSERT_TRUE(result);
  11774. EXPECT_EQ(200, result->status);
  11775. std::this_thread::sleep_for(std::chrono::seconds(2));
  11776. // Recoonect
  11777. result = cli.Post(
  11778. "/hi", content.size(),
  11779. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11780. sink.write(content.c_str(), content.size());
  11781. return true;
  11782. },
  11783. "text/plain");
  11784. ASSERT_TRUE(result);
  11785. EXPECT_EQ(200, result->status);
  11786. result = cli.Post(
  11787. "/hi", content.size(),
  11788. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11789. sink.write(content.c_str(), content.size());
  11790. return true;
  11791. },
  11792. "text/plain");
  11793. ASSERT_TRUE(result);
  11794. EXPECT_EQ(200, result->status);
  11795. }
  11796. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11797. using namespace httplib::tls;
  11798. {
  11799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11800. ASSERT_TRUE(svr.is_valid());
  11801. svr.Get("/sni", [&](const Request &req, Response &res) {
  11802. std::string expected = req.sni();
  11803. EXPECT_EQ(expected, req.get_param_value("expected"));
  11804. res.set_content("ok", "text/plain");
  11805. });
  11806. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11807. auto se = detail::scope_exit([&] {
  11808. svr.stop();
  11809. listen_thread.join();
  11810. ASSERT_FALSE(svr.is_running());
  11811. });
  11812. svr.wait_until_ready();
  11813. {
  11814. SSLClient cli("localhost", PORT);
  11815. cli.enable_server_certificate_verification(false);
  11816. auto res = cli.Get("/sni?expected=localhost");
  11817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11818. }
  11819. {
  11820. SSLClient cli("::1", PORT);
  11821. cli.enable_server_certificate_verification(false);
  11822. auto res = cli.Get("/sni?expected=");
  11823. // NOTE: This may fail if the server is listening on IPv4 only
  11824. // (e.g., when localhost resolves to 127.0.0.1 only)
  11825. if (res) {
  11826. EXPECT_EQ(StatusCode::OK_200, res->status);
  11827. } else {
  11828. EXPECT_EQ(Error::Connection, res.error());
  11829. }
  11830. }
  11831. }
  11832. }
  11833. // The SNI of a failed handshake does not reach the next connection that the
  11834. // same worker thread serves
  11835. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11836. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11837. ASSERT_TRUE(svr.is_valid());
  11838. svr.new_task_queue = [] { return new ThreadPool(1); };
  11839. svr.Get("/sni", [](const Request &req, Response &res) {
  11840. res.set_content(req.sni(), "text/plain");
  11841. });
  11842. auto port = svr.bind_to_any_port("127.0.0.1");
  11843. ASSERT_LT(0, port);
  11844. thread t = thread([&] { svr.listen_after_bind(); });
  11845. auto se = detail::scope_exit([&] {
  11846. svr.stop();
  11847. t.join();
  11848. ASSERT_FALSE(svr.is_running());
  11849. });
  11850. svr.wait_until_ready();
  11851. {
  11852. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11853. SSLClient cli("localhost", port);
  11854. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11855. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11856. auto res = cli.Get("/sni");
  11857. ASSERT_FALSE(res);
  11858. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11859. }
  11860. // An IP host sends no SNI (RFC 6066)
  11861. SSLClient cli("127.0.0.1", port);
  11862. cli.enable_server_certificate_verification(false);
  11863. auto res = cli.Get("/sni");
  11864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11865. EXPECT_EQ("", res->body);
  11866. }
  11867. #endif
  11868. TEST(ClientProblemDetectionTest, ContentProvider) {
  11869. Server svr;
  11870. size_t content_length = 1024 * 1024;
  11871. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11872. res.set_content_provider(
  11873. content_length, "text/plain",
  11874. [&](size_t offset, size_t length, DataSink &sink) {
  11875. auto out_len = std::min(length, static_cast<size_t>(1024));
  11876. std::string out(out_len, '@');
  11877. sink.write(out.data(), out_len);
  11878. return offset < 4096;
  11879. },
  11880. [](bool success) { ASSERT_FALSE(success); });
  11881. });
  11882. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11883. res.set_content_provider(
  11884. 0, "text/plain",
  11885. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11886. EXPECT_TRUE(false);
  11887. return true;
  11888. },
  11889. [](bool success) { ASSERT_FALSE(success); });
  11890. });
  11891. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11892. auto se = detail::scope_exit([&] {
  11893. svr.stop();
  11894. listen_thread.join();
  11895. ASSERT_FALSE(svr.is_running());
  11896. });
  11897. svr.wait_until_ready();
  11898. Client cli("localhost", PORT);
  11899. {
  11900. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11901. size_t /*data_length*/) { return false; });
  11902. ASSERT_FALSE(res);
  11903. }
  11904. {
  11905. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11906. size_t /*data_length*/) { return false; });
  11907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11908. }
  11909. }
  11910. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11911. // A provider that reports success without writing anything and without
  11912. // calling done() used to be handed the same offset and length again on every
  11913. // pass, so it spun for as long as the peer stayed connected.
  11914. Server svr;
  11915. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11916. res.set_content("ok", "text/plain");
  11917. });
  11918. auto port = svr.bind_to_any_port(HOST);
  11919. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11920. auto se = detail::scope_exit([&] {
  11921. svr.stop();
  11922. listen_thread.join();
  11923. ASSERT_FALSE(svr.is_running());
  11924. });
  11925. svr.wait_until_ready();
  11926. std::atomic<int> call_count{0};
  11927. Client cli(HOST, port);
  11928. auto res = cli.Post(
  11929. "/", 1024,
  11930. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11931. // Give up after enough passes to show the spin, so that losing the
  11932. // check below fails this test instead of hanging it.
  11933. return ++call_count < 100;
  11934. },
  11935. "text/plain");
  11936. ASSERT_FALSE(res);
  11937. EXPECT_EQ(Error::Write, res.error());
  11938. EXPECT_EQ(1, call_count.load());
  11939. }
  11940. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11941. // A writer only has to assign `write`. The other three used to be left as
  11942. // empty std::functions, so a provider calling one threw
  11943. // std::bad_function_call out of the thread running it and took the whole
  11944. // process down.
  11945. DataSink sink;
  11946. std::string written;
  11947. sink.write = [&](const char *data, size_t data_len) {
  11948. written.append(data, data_len);
  11949. return true;
  11950. };
  11951. EXPECT_TRUE(sink.is_writable());
  11952. sink.done();
  11953. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11954. EXPECT_TRUE(written.empty());
  11955. }
  11956. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11957. // A sink that cannot carry trailers still has to finish.
  11958. DataSink sink;
  11959. auto done_count = 0;
  11960. sink.done = [&]() { done_count++; };
  11961. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11962. EXPECT_EQ(1, done_count);
  11963. }
  11964. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11965. Server svr;
  11966. const std::string body(4096, 'x');
  11967. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11968. res.set_content_provider(body.size(), "text/plain",
  11969. [&](size_t offset, size_t length, DataSink &sink) {
  11970. sink.write(body.data() + offset, length);
  11971. sink.done();
  11972. return true;
  11973. });
  11974. });
  11975. auto port = svr.bind_to_any_port(HOST);
  11976. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11977. auto se = detail::scope_exit([&] {
  11978. svr.stop();
  11979. listen_thread.join();
  11980. ASSERT_FALSE(svr.is_running());
  11981. });
  11982. svr.wait_until_ready();
  11983. Client cli(HOST, port);
  11984. auto res = cli.Get("/");
  11985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11986. EXPECT_EQ(StatusCode::OK_200, res->status);
  11987. EXPECT_EQ(body, res->body);
  11988. }
  11989. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11990. Server svr;
  11991. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11992. res.set_content_provider(
  11993. 1024, "text/plain",
  11994. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11995. sink.write("hello", 5);
  11996. sink.done(); // short of the 1024 bytes the response promised
  11997. return true;
  11998. });
  11999. });
  12000. auto port = svr.bind_to_any_port(HOST);
  12001. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12002. auto se = detail::scope_exit([&] {
  12003. svr.stop();
  12004. listen_thread.join();
  12005. ASSERT_FALSE(svr.is_running());
  12006. });
  12007. svr.wait_until_ready();
  12008. Client cli(HOST, port);
  12009. cli.set_read_timeout(5, 0);
  12010. // The response is short of its Content-Length, so the client cannot read a
  12011. // complete body. What matters is that this returns at all: a no-op done()
  12012. // would leave the writer looping over a provider that never makes progress.
  12013. auto res = cli.Get("/");
  12014. EXPECT_FALSE(res);
  12015. }
  12016. // Read as the next response by a peer that sees it after a framed body.
  12017. static const std::string smuggled_response =
  12018. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12019. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12020. Server svr;
  12021. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12022. res.set_content_provider(
  12023. 5, "text/plain",
  12024. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12025. auto data = "AAAAA" + smuggled_response;
  12026. sink.write(data.data(), data.size());
  12027. return true;
  12028. });
  12029. });
  12030. thread t = thread([&] { svr.listen(HOST, PORT); });
  12031. auto se = detail::scope_exit([&] {
  12032. svr.stop();
  12033. t.join();
  12034. ASSERT_FALSE(svr.is_running());
  12035. });
  12036. svr.wait_until_ready();
  12037. std::string resp;
  12038. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12039. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12040. resp.clear();
  12041. ASSERT_TRUE(send_request(
  12042. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12043. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12044. }
  12045. TEST(NoContentTest, BodyIsNotSent) {
  12046. Server svr;
  12047. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12048. res.status = StatusCode::NoContent_204;
  12049. res.set_content(smuggled_response, "text/plain");
  12050. });
  12051. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12052. res.status = StatusCode::NotModified_304;
  12053. res.set_chunked_content_provider(
  12054. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12055. sink.write(smuggled_response.data(), smuggled_response.size());
  12056. sink.done();
  12057. return true;
  12058. });
  12059. });
  12060. thread t = thread([&] { svr.listen(HOST, PORT); });
  12061. auto se = detail::scope_exit([&] {
  12062. svr.stop();
  12063. t.join();
  12064. ASSERT_FALSE(svr.is_running());
  12065. });
  12066. svr.wait_until_ready();
  12067. for (auto path : {"/204", "/304"}) {
  12068. std::string resp;
  12069. ASSERT_TRUE(send_request(
  12070. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12071. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12072. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12073. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12074. }
  12075. }
  12076. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12077. Server svr;
  12078. std::atomic<bool> smuggled(false);
  12079. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12080. res.set_content("ok", "text/plain");
  12081. });
  12082. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12083. smuggled = true;
  12084. });
  12085. auto port = svr.bind_to_any_port(HOST);
  12086. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12087. auto se = detail::scope_exit([&] {
  12088. svr.stop();
  12089. listen_thread.join();
  12090. ASSERT_FALSE(svr.is_running());
  12091. });
  12092. svr.wait_until_ready();
  12093. // What follows the body would be read as the next request.
  12094. Client cli(HOST, port);
  12095. auto res = cli.Post(
  12096. "/", 5,
  12097. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12098. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12099. sink.write(data.data(), data.size());
  12100. return true;
  12101. },
  12102. "text/plain");
  12103. ASSERT_FALSE(res);
  12104. EXPECT_EQ(Error::Write, res.error());
  12105. EXPECT_FALSE(smuggled);
  12106. }
  12107. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12108. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12109. // The compressed path builds the whole body before connecting, so this
  12110. // fails client-side and never reaches a server.
  12111. Client cli(HOST, PORT);
  12112. cli.set_compress(true);
  12113. auto res = cli.Post(
  12114. "/", 1024,
  12115. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12116. sink.write("hello", 5);
  12117. sink.done(); // short of the 1024 bytes the request announced
  12118. return true;
  12119. },
  12120. "text/plain");
  12121. ASSERT_FALSE(res);
  12122. EXPECT_EQ(Error::Write, res.error());
  12123. }
  12124. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12125. Server svr;
  12126. std::string received;
  12127. size_t content_length_count = 0;
  12128. bool has_transfer_encoding = true;
  12129. svr.Post("/echo", [&](const Request &req, Response &res) {
  12130. received = req.body;
  12131. content_length_count = req.get_header_value_count("Content-Length");
  12132. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12133. res.set_content("ok", "text/plain");
  12134. });
  12135. svr.Get("/next", [](const Request &, Response &res) {
  12136. res.set_content("next", "text/plain");
  12137. });
  12138. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12139. auto se = detail::scope_exit([&] {
  12140. svr.stop();
  12141. listen_thread.join();
  12142. ASSERT_FALSE(svr.is_running());
  12143. });
  12144. svr.wait_until_ready();
  12145. Client cli(HOST, PORT);
  12146. cli.set_keep_alive(true);
  12147. cli.set_compress(true);
  12148. const std::string body = "hello world";
  12149. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12150. auto res = cli.Post("/echo", headers, body, "text/plain");
  12151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12152. EXPECT_EQ(StatusCode::OK_200, res->status);
  12153. EXPECT_EQ(body, received);
  12154. EXPECT_EQ(1u, content_length_count);
  12155. EXPECT_FALSE(has_transfer_encoding);
  12156. // The rest of a truncated body would be read as this request
  12157. auto res2 = cli.Get("/next");
  12158. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12159. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12160. EXPECT_EQ("next", res2->body);
  12161. }
  12162. #endif
  12163. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12164. Server svr;
  12165. std::string received;
  12166. size_t content_length_count = 1;
  12167. bool has_transfer_encoding = false;
  12168. svr.Post("/echo", [&](const Request &req, Response &res) {
  12169. received = req.body;
  12170. content_length_count = req.get_header_value_count("Content-Length");
  12171. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12172. res.set_content("ok", "text/plain");
  12173. });
  12174. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12175. auto se = detail::scope_exit([&] {
  12176. svr.stop();
  12177. listen_thread.join();
  12178. ASSERT_FALSE(svr.is_running());
  12179. });
  12180. svr.wait_until_ready();
  12181. Client cli(HOST, PORT);
  12182. cli.set_keep_alive(true);
  12183. const std::string body = "hello world";
  12184. Headers headers = {{"Content-Length", "5"}};
  12185. auto res = cli.Post(
  12186. "/echo", headers,
  12187. [&](size_t /*offset*/, DataSink &sink) {
  12188. sink.write(body.data(), body.size());
  12189. sink.done();
  12190. return true;
  12191. },
  12192. "text/plain");
  12193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12194. EXPECT_EQ(StatusCode::OK_200, res->status);
  12195. EXPECT_EQ(body, received);
  12196. EXPECT_EQ(0u, content_length_count);
  12197. EXPECT_TRUE(has_transfer_encoding);
  12198. }
  12199. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12200. Server svr;
  12201. svr.set_error_handler([](Request const &, Response &res) -> void {
  12202. res.set_chunked_content_provider(
  12203. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12204. sink.os << "hello";
  12205. sink.os << "world";
  12206. sink.done();
  12207. return true;
  12208. });
  12209. });
  12210. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12211. auto se = detail::scope_exit([&] {
  12212. svr.stop();
  12213. listen_thread.join();
  12214. ASSERT_FALSE(svr.is_running());
  12215. });
  12216. svr.wait_until_ready();
  12217. Client cli("localhost", PORT);
  12218. auto res = cli.Get("/");
  12219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12220. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12221. EXPECT_EQ("helloworld", res->body);
  12222. }
  12223. // A body set after a content provider must replace it, not be sent through it.
  12224. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12225. Server svr;
  12226. svr.set_mount_point("/", "./www");
  12227. svr.set_file_request_handler([](const Request &req, Response &res) {
  12228. if (req.path == "/dir/test.html") {
  12229. res.status = StatusCode::Forbidden_403;
  12230. res.set_content(std::string(5000, 'D'), "text/plain");
  12231. } else if (req.path == "/file") {
  12232. res.status = StatusCode::Forbidden_403;
  12233. res.body = "Denied";
  12234. }
  12235. });
  12236. auto port = svr.bind_to_any_port(HOST);
  12237. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12238. auto se = detail::scope_exit([&] {
  12239. svr.stop();
  12240. t.join();
  12241. ASSERT_FALSE(svr.is_running());
  12242. });
  12243. svr.wait_until_ready();
  12244. Client cli(HOST, port);
  12245. {
  12246. auto res = cli.Get("/dir/test.html");
  12247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12248. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12249. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12250. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12251. }
  12252. {
  12253. auto res = cli.Get("/file");
  12254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12255. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12256. EXPECT_EQ("Denied", res->body);
  12257. }
  12258. {
  12259. auto res = cli.Get("/dir/index.html");
  12260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12261. EXPECT_EQ(StatusCode::OK_200, res->status);
  12262. EXPECT_EQ(0U, res->body.find("<html>"));
  12263. }
  12264. }
  12265. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12266. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12267. Server svr;
  12268. std::vector<bool> released;
  12269. std::mutex released_mutex;
  12270. auto releaser = [&](bool success) {
  12271. std::lock_guard<std::mutex> guard(released_mutex);
  12272. released.push_back(success);
  12273. };
  12274. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12275. return sink.write(&"hello"[offset], length);
  12276. };
  12277. svr.Get("/sized", [&](const Request &, Response &res) {
  12278. res.status = StatusCode::NotFound_404;
  12279. res.set_content_provider(5, "text/plain", provider, releaser);
  12280. });
  12281. svr.Get("/chunked", [&](const Request &, Response &res) {
  12282. res.status = StatusCode::ServiceUnavailable_503;
  12283. res.set_chunked_content_provider(
  12284. "text/plain",
  12285. [](size_t, DataSink &sink) {
  12286. sink.os << "chunk";
  12287. sink.done();
  12288. return true;
  12289. },
  12290. releaser);
  12291. });
  12292. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12293. res.set_content_provider(5, "text/plain", provider, releaser);
  12294. throw std::runtime_error("after the provider");
  12295. });
  12296. svr.set_error_handler([](const Request &req, Response &res) {
  12297. // Leave the exception handler's content to it.
  12298. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12299. res.set_content(std::string(1000, 'E'), "text/html");
  12300. return Server::HandlerResponse::Handled;
  12301. });
  12302. svr.set_exception_handler(
  12303. [](const Request &, Response &res, std::exception_ptr) {
  12304. res.status = StatusCode::InternalServerError_500;
  12305. res.set_content(std::string(1000, 'X'), "text/html");
  12306. });
  12307. auto port = svr.bind_to_any_port(HOST);
  12308. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12309. auto se = detail::scope_exit([&] {
  12310. svr.stop();
  12311. t.join();
  12312. ASSERT_FALSE(svr.is_running());
  12313. });
  12314. svr.wait_until_ready();
  12315. Client cli(HOST, port);
  12316. {
  12317. auto res = cli.Get("/sized");
  12318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12319. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12320. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12321. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12322. }
  12323. {
  12324. auto res = cli.Get("/chunked");
  12325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12326. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12327. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12328. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12329. }
  12330. {
  12331. auto res = cli.Get("/throw");
  12332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12333. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12334. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12335. }
  12336. std::lock_guard<std::mutex> guard(released_mutex);
  12337. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12338. }
  12339. #endif
  12340. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12341. Server svr;
  12342. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12343. return sink.write(&"abc"[offset], length);
  12344. };
  12345. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12346. res.set_file_content("./www/dir/test.html");
  12347. res.set_content("body", "text/plain");
  12348. });
  12349. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12350. res.set_content(std::string(100, 'B'), "text/plain");
  12351. res.set_file_content("./www/dir/test.html");
  12352. });
  12353. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12354. res.set_content(std::string(100, 'B'), "text/plain");
  12355. res.set_content_provider(3, "text/x-provider", abc);
  12356. });
  12357. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12358. res.set_content_provider(3, "text/x-provider", abc);
  12359. res.set_content(std::string(100, 'B'), "text/plain");
  12360. });
  12361. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12362. res.set_content_provider(3, "text/x-provider", abc);
  12363. res.set_file_content("./www/dir/test.html", "text/x-file");
  12364. });
  12365. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12366. res.set_file_content("./www/dir/test.html");
  12367. res.set_header("Content-Type", "text/x-handler");
  12368. });
  12369. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12370. res.set_content_provider(3, "text/plain", abc);
  12371. res.body = "direct";
  12372. });
  12373. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12374. res.set_file_content("./www/dir/test.html");
  12375. res.body = "direct";
  12376. });
  12377. auto port = svr.bind_to_any_port(HOST);
  12378. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12379. auto se = detail::scope_exit([&] {
  12380. svr.stop();
  12381. t.join();
  12382. ASSERT_FALSE(svr.is_running());
  12383. });
  12384. svr.wait_until_ready();
  12385. Client cli(HOST, port);
  12386. auto expect_body = [&](const char *path, const std::string &body,
  12387. const std::string &type) {
  12388. // Uncompressed, so Content-Length can be compared with the body.
  12389. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12390. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12391. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12392. EXPECT_EQ(body, res->body) << path;
  12393. EXPECT_EQ(std::to_string(body.size()),
  12394. res->get_header_value("Content-Length"))
  12395. << path;
  12396. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12397. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12398. };
  12399. expect_body("/file-then-body", "body", "text/plain");
  12400. expect_body("/body-then-file", "test.html", "text/html");
  12401. expect_body("/body-then-provider", "abc", "text/x-provider");
  12402. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12403. expect_body("/provider-then-file", "test.html", "text/x-file");
  12404. expect_body("/file-then-header", "test.html", "text/x-handler");
  12405. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12406. expect_body("/file-then-direct-body", "direct", "text/plain");
  12407. // Ranges are checked against the body, not the dropped provider.
  12408. {
  12409. auto res = cli.Get("/provider-then-direct-body",
  12410. Headers{{make_range_header({{1, 2}})}});
  12411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12412. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12413. EXPECT_EQ("ir", res->body);
  12414. }
  12415. {
  12416. auto res = cli.Get("/file-then-direct-body",
  12417. Headers{{make_range_header({{7, 8}})}});
  12418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12419. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12420. }
  12421. }
  12422. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12423. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12424. const char *path = "./truncated_while_served.txt";
  12425. const size_t size = 32 * 1024 * 1024;
  12426. {
  12427. std::ofstream f(path, std::ios::binary);
  12428. f << std::string(size, 'x');
  12429. }
  12430. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12431. // Over TLS, where the bytes are encrypted in this process rather than
  12432. // copied by send().
  12433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12434. svr.Get("/file", [&](const Request &, Response &res) {
  12435. res.set_file_content(path, "text/plain");
  12436. });
  12437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12438. auto se = detail::scope_exit([&] {
  12439. svr.stop();
  12440. thread.join();
  12441. ASSERT_FALSE(svr.is_running());
  12442. });
  12443. svr.wait_until_ready();
  12444. // The file shrinks once the first bytes are in, as a rewrite in place
  12445. // would, and reading the mapping past its new end used to raise SIGBUS.
  12446. SSLClient cli(HOST, PORT);
  12447. cli.enable_server_certificate_verification(false);
  12448. size_t received = 0;
  12449. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12450. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12451. received += len;
  12452. return true;
  12453. });
  12454. EXPECT_FALSE(res);
  12455. EXPECT_LT(received, size);
  12456. }
  12457. #endif
  12458. // Forward declaration (see the base64_encode note).
  12459. namespace httplib {
  12460. namespace detail {
  12461. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12462. const std::string &content_type,
  12463. EncodingType encoding);
  12464. } // namespace detail
  12465. } // namespace httplib
  12466. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12467. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12468. ASSERT_TRUE(mm->is_open());
  12469. Response res;
  12470. detail::set_file_content_provider(res, mm, "text/html",
  12471. detail::EncodingType::None);
  12472. std::string out;
  12473. DataSink sink;
  12474. sink.write = [&](const char *d, size_t l) {
  12475. out.append(d, l);
  12476. return true;
  12477. };
  12478. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12479. EXPECT_EQ("test.html", out);
  12480. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12481. EXPECT_EQ("test.html", out);
  12482. }
  12483. TEST(LongPollingTest, ClientCloseDetection) {
  12484. Server svr;
  12485. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12486. res.set_chunked_content_provider(
  12487. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12488. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12489. sink.os << "hello";
  12490. auto count = 10;
  12491. while (count > 0 && sink.is_writable()) {
  12492. this_thread::sleep_for(chrono::milliseconds(10));
  12493. count--;
  12494. }
  12495. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12496. return true;
  12497. });
  12498. });
  12499. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12500. auto se = detail::scope_exit([&] {
  12501. svr.stop();
  12502. listen_thread.join();
  12503. ASSERT_FALSE(svr.is_running());
  12504. });
  12505. svr.wait_until_ready();
  12506. Client cli("localhost", PORT);
  12507. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12508. EXPECT_EQ("hello", string(data, data_length));
  12509. return false; // close the socket immediately.
  12510. });
  12511. ASSERT_FALSE(res);
  12512. }
  12513. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12514. Server svr;
  12515. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12516. res.set_chunked_content_provider(
  12517. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12518. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12519. sink.os << "hello";
  12520. EXPECT_TRUE(sink.os.good());
  12521. // Wait for the client to close the connection
  12522. auto count = 10;
  12523. while (count > 0 && sink.is_writable()) {
  12524. this_thread::sleep_for(chrono::milliseconds(10));
  12525. count--;
  12526. }
  12527. // After client disconnect, write repeatedly until the socket
  12528. // write actually fails (small writes may be absorbed by the
  12529. // kernel buffer)
  12530. std::string chunk(1024, 'x');
  12531. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12532. sink.os << chunk;
  12533. }
  12534. EXPECT_TRUE(sink.os.fail());
  12535. return true;
  12536. });
  12537. });
  12538. auto port = svr.bind_to_any_port("localhost");
  12539. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12540. auto se = detail::scope_exit([&] {
  12541. svr.stop();
  12542. listen_thread.join();
  12543. ASSERT_FALSE(svr.is_running());
  12544. });
  12545. svr.wait_until_ready();
  12546. Client cli("localhost", port);
  12547. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12548. EXPECT_EQ("hello", string(data, data_length));
  12549. return false; // close the socket immediately.
  12550. });
  12551. ASSERT_FALSE(res);
  12552. }
  12553. TEST(GetWithParametersTest, GetWithParameters) {
  12554. Server svr;
  12555. svr.Get("/", [&](const Request &req, Response &) {
  12556. EXPECT_EQ("world", req.get_param_value("hello"));
  12557. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12558. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12559. });
  12560. svr.Get("/params", [&](const Request &req, Response &) {
  12561. EXPECT_EQ("world", req.get_param_value("hello"));
  12562. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12563. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12564. });
  12565. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12566. EXPECT_EQ("resource-id", req.matches[1]);
  12567. EXPECT_EQ("foo", req.get_param_value("param1"));
  12568. EXPECT_EQ("bar", req.get_param_value("param2"));
  12569. });
  12570. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12571. EXPECT_EQ("user-id", req.path_params.at("id"));
  12572. EXPECT_EQ("foo", req.get_param_value("param1"));
  12573. EXPECT_EQ("bar", req.get_param_value("param2"));
  12574. });
  12575. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12576. auto se = detail::scope_exit([&] {
  12577. svr.stop();
  12578. listen_thread.join();
  12579. ASSERT_FALSE(svr.is_running());
  12580. });
  12581. svr.wait_until_ready();
  12582. {
  12583. Client cli(HOST, PORT);
  12584. Params params;
  12585. params.emplace("hello", "world");
  12586. params.emplace("hello2", "world2");
  12587. params.emplace("hello3", "world3");
  12588. auto res = cli.Get("/", params, Headers{});
  12589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12590. EXPECT_EQ(StatusCode::OK_200, res->status);
  12591. }
  12592. {
  12593. Client cli(HOST, PORT);
  12594. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12596. EXPECT_EQ(StatusCode::OK_200, res->status);
  12597. }
  12598. {
  12599. Client cli(HOST, PORT);
  12600. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12602. EXPECT_EQ(StatusCode::OK_200, res->status);
  12603. }
  12604. {
  12605. Client cli(HOST, PORT);
  12606. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12608. EXPECT_EQ(StatusCode::OK_200, res->status);
  12609. }
  12610. }
  12611. TEST(GetWithParametersTest, GetWithParameters2) {
  12612. Server svr;
  12613. svr.Get("/", [&](const Request &req, Response &res) {
  12614. auto text = req.get_param_value("hello");
  12615. res.set_content(text, "text/plain");
  12616. });
  12617. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12618. auto se = detail::scope_exit([&] {
  12619. svr.stop();
  12620. listen_thread.join();
  12621. ASSERT_FALSE(svr.is_running());
  12622. });
  12623. svr.wait_until_ready();
  12624. Client cli("localhost", PORT);
  12625. Params params;
  12626. params.emplace("hello", "world");
  12627. std::string body;
  12628. auto res = cli.Get("/", params, Headers{},
  12629. [&](const char *data, size_t data_length) {
  12630. body.append(data, data_length);
  12631. return true;
  12632. });
  12633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12634. EXPECT_EQ(StatusCode::OK_200, res->status);
  12635. EXPECT_EQ("world", body);
  12636. }
  12637. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12638. Server svr;
  12639. svr.Get("/search", [&](const Request &req, Response &res) {
  12640. auto q = req.get_param_value("q");
  12641. res.set_content(q, "text/plain");
  12642. });
  12643. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12644. auto se = detail::scope_exit([&] {
  12645. svr.stop();
  12646. listen_thread.join();
  12647. ASSERT_FALSE(svr.is_running());
  12648. });
  12649. svr.wait_until_ready();
  12650. Client cli("localhost", PORT);
  12651. // Verify that Get(path, params) works without requiring Headers argument
  12652. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12654. EXPECT_EQ(StatusCode::OK_200, res->status);
  12655. EXPECT_EQ("cpp-httplib", res->body);
  12656. }
  12657. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12658. auto host = "httpbingo.org";
  12659. auto path = std::string{"/range/32"};
  12660. #ifdef CPPHTTPLIB_SSL_ENABLED
  12661. SSLClient cli(host);
  12662. #else
  12663. Client cli(host);
  12664. #endif
  12665. cli.set_default_headers({make_range_header({{1, 10}})});
  12666. cli.set_connection_timeout(5);
  12667. {
  12668. auto res = cli.Get(path);
  12669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12670. EXPECT_EQ("bcdefghijk", res->body);
  12671. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12672. }
  12673. {
  12674. auto res = cli.Get(path);
  12675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12676. EXPECT_EQ("bcdefghijk", res->body);
  12677. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12678. }
  12679. }
  12680. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12681. Server svr;
  12682. svr.set_default_headers({{"Hello", "World"}});
  12683. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12684. res.set_content("ok", "text/plain");
  12685. });
  12686. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12687. auto se = detail::scope_exit([&] {
  12688. svr.stop();
  12689. listen_thread.join();
  12690. ASSERT_FALSE(svr.is_running());
  12691. });
  12692. svr.wait_until_ready();
  12693. Client cli("localhost", PORT);
  12694. auto res = cli.Get("/");
  12695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12696. EXPECT_EQ(StatusCode::OK_200, res->status);
  12697. EXPECT_EQ("ok", res->body);
  12698. EXPECT_EQ("World", res->get_header_value("Hello"));
  12699. }
  12700. #ifdef CPPHTTPLIB_SSL_ENABLED
  12701. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12702. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12703. ASSERT_TRUE(svr.is_valid());
  12704. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12705. std::this_thread::sleep_for(std::chrono::seconds(2));
  12706. res.set_content("a", "text/plain");
  12707. });
  12708. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12709. res.set_content("b", "text/plain");
  12710. });
  12711. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12712. auto se = detail::scope_exit([&] {
  12713. svr.stop();
  12714. listen_thread.join();
  12715. ASSERT_FALSE(svr.is_running());
  12716. });
  12717. svr.wait_until_ready();
  12718. SSLClient cli("localhost", PORT);
  12719. cli.enable_server_certificate_verification(false);
  12720. cli.set_keep_alive(true);
  12721. cli.set_read_timeout(std::chrono::seconds(1));
  12722. auto resa = cli.Get("/a");
  12723. ASSERT_TRUE(!resa);
  12724. EXPECT_EQ(Error::Read, resa.error());
  12725. auto resb = cli.Get("/b");
  12726. ASSERT_TRUE(resb);
  12727. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12728. EXPECT_EQ("b", resb->body);
  12729. }
  12730. // Closing an idle keep-alive connection sends close_notify and returns. The
  12731. // server must not wait for the client's close_notify: an idle client never
  12732. // sends one, so the worker would be held until the read timeout expires, and
  12733. // stop() would wait for it.
  12734. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12735. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12736. ASSERT_TRUE(svr.is_valid());
  12737. svr.set_keep_alive_timeout(1);
  12738. svr.set_read_timeout(10, 0);
  12739. svr.Get("/", [](const Request &, Response &res) {
  12740. res.set_content("ok", "text/plain");
  12741. });
  12742. auto port = svr.bind_to_any_port(HOST);
  12743. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12744. auto se = detail::scope_exit([&] {
  12745. if (listen_thread.joinable()) {
  12746. svr.stop();
  12747. listen_thread.join();
  12748. }
  12749. });
  12750. svr.wait_until_ready();
  12751. SSLClient cli(HOST, port);
  12752. cli.enable_server_certificate_verification(false);
  12753. cli.set_keep_alive(true);
  12754. auto res = cli.Get("/");
  12755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12756. EXPECT_EQ(StatusCode::OK_200, res->status);
  12757. // Stay idle past the keep-alive timeout so the server closes the connection.
  12758. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12759. auto start = std::chrono::steady_clock::now();
  12760. svr.stop();
  12761. listen_thread.join();
  12762. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12763. std::chrono::steady_clock::now() - start)
  12764. .count();
  12765. EXPECT_LT(elapsed, 3000);
  12766. }
  12767. #endif
  12768. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12769. protected:
  12770. ServerTestWithAI_PASSIVE()
  12771. : cli_(HOST, PORT)
  12772. #ifdef CPPHTTPLIB_SSL_ENABLED
  12773. ,
  12774. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12775. #endif
  12776. {
  12777. #ifdef CPPHTTPLIB_SSL_ENABLED
  12778. cli_.enable_server_certificate_verification(false);
  12779. #endif
  12780. }
  12781. virtual void SetUp() {
  12782. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12783. res.set_content("Hello World!", "text/plain");
  12784. });
  12785. t_ = thread(
  12786. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12787. svr_.wait_until_ready();
  12788. }
  12789. virtual void TearDown() {
  12790. svr_.stop();
  12791. t_.join();
  12792. }
  12793. #ifdef CPPHTTPLIB_SSL_ENABLED
  12794. SSLClient cli_;
  12795. SSLServer svr_;
  12796. #else
  12797. Client cli_;
  12798. Server svr_;
  12799. #endif
  12800. thread t_;
  12801. };
  12802. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12803. auto res = cli_.Get("/hi");
  12804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12805. EXPECT_EQ(StatusCode::OK_200, res->status);
  12806. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12807. EXPECT_EQ("Hello World!", res->body);
  12808. }
  12809. class ServerUpDownTest : public ::testing::Test {
  12810. protected:
  12811. ServerUpDownTest() : cli_(HOST, PORT) {}
  12812. virtual void SetUp() {
  12813. t_ = thread([&]() {
  12814. svr_.bind_to_any_port(HOST);
  12815. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12816. ASSERT_TRUE(svr_.listen_after_bind());
  12817. });
  12818. svr_.wait_until_ready();
  12819. }
  12820. virtual void TearDown() {
  12821. svr_.stop();
  12822. t_.join();
  12823. }
  12824. Client cli_;
  12825. Server svr_;
  12826. thread t_;
  12827. };
  12828. TEST_F(ServerUpDownTest, QuickStartStop) {
  12829. // Should not crash, especially when run with
  12830. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12831. }
  12832. class PayloadMaxLengthTest : public ::testing::Test {
  12833. protected:
  12834. PayloadMaxLengthTest()
  12835. : cli_(HOST, PORT)
  12836. #ifdef CPPHTTPLIB_SSL_ENABLED
  12837. ,
  12838. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12839. #endif
  12840. {
  12841. #ifdef CPPHTTPLIB_SSL_ENABLED
  12842. cli_.enable_server_certificate_verification(false);
  12843. #endif
  12844. }
  12845. virtual void SetUp() {
  12846. svr_.set_payload_max_length(8);
  12847. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12848. res.set_content("test", "text/plain");
  12849. });
  12850. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12851. svr_.wait_until_ready();
  12852. }
  12853. virtual void TearDown() {
  12854. svr_.stop();
  12855. t_.join();
  12856. }
  12857. #ifdef CPPHTTPLIB_SSL_ENABLED
  12858. SSLClient cli_;
  12859. SSLServer svr_;
  12860. #else
  12861. Client cli_;
  12862. Server svr_;
  12863. #endif
  12864. thread t_;
  12865. };
  12866. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12867. auto res = cli_.Post("/test", "123456789", "text/plain");
  12868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12869. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12870. res = cli_.Post("/test", "12345678", "text/plain");
  12871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12872. EXPECT_EQ(StatusCode::OK_200, res->status);
  12873. }
  12874. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12875. // Test chunked encoding with payload exceeding the 8-byte limit
  12876. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12877. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12879. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12880. }
  12881. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12882. // Test chunked encoding with payload within the 8-byte limit
  12883. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12884. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12886. EXPECT_EQ(StatusCode::OK_200, res->status);
  12887. }
  12888. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12889. // Test using send_request to send chunked data exceeding payload limit
  12890. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12891. "Host: " +
  12892. std::string(HOST) + ":" + std::to_string(PORT) +
  12893. "\r\n"
  12894. "Transfer-Encoding: chunked\r\n"
  12895. "Connection: close\r\n"
  12896. "\r\n"
  12897. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12898. "0123456789\r\n"
  12899. "0\r\n" // End chunk
  12900. "\r\n";
  12901. std::string response;
  12902. bool result = send_request(1, chunked_request, &response);
  12903. if (!result) {
  12904. // If send_request fails, it might be because the server closed the
  12905. // connection due to payload limit enforcement, which is acceptable
  12906. SUCCEED()
  12907. << "Server rejected oversized chunked request (connection closed)";
  12908. } else {
  12909. // If we got a response, check if it's an error response or connection was
  12910. // closed early Short response length indicates connection was closed due to
  12911. // payload limit
  12912. if (response.length() <= 10) {
  12913. SUCCEED() << "Server closed connection for oversized chunked request";
  12914. } else {
  12915. // Check for error status codes
  12916. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12917. response.find("Payload Too Large") != std::string::npos ||
  12918. response.find("400") != std::string::npos);
  12919. }
  12920. }
  12921. }
  12922. class LargePayloadMaxLengthTest : public ::testing::Test {
  12923. protected:
  12924. LargePayloadMaxLengthTest()
  12925. : cli_(HOST, PORT)
  12926. #ifdef CPPHTTPLIB_SSL_ENABLED
  12927. ,
  12928. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12929. #endif
  12930. {
  12931. #ifdef CPPHTTPLIB_SSL_ENABLED
  12932. cli_.enable_server_certificate_verification(false);
  12933. #endif
  12934. }
  12935. virtual void SetUp() {
  12936. // Set 10MB payload limit
  12937. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12938. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12939. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12940. res.set_content("Large payload test", "text/plain");
  12941. });
  12942. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12943. svr_.wait_until_ready();
  12944. }
  12945. virtual void TearDown() {
  12946. svr_.stop();
  12947. t_.join();
  12948. }
  12949. #ifdef CPPHTTPLIB_SSL_ENABLED
  12950. SSLClient cli_;
  12951. SSLServer svr_;
  12952. #else
  12953. Client cli_;
  12954. Server svr_;
  12955. #endif
  12956. thread t_;
  12957. };
  12958. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12959. // Test chunked encoding with payload within 10MB limit
  12960. std::string medium_payload(5 * 1024 * 1024,
  12961. 'A'); // 5MB payload, within 10MB limit
  12962. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12964. EXPECT_EQ(StatusCode::OK_200, res->status);
  12965. }
  12966. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12967. // Test chunked encoding with payload exceeding 10MB limit
  12968. std::string large_payload(12 * 1024 * 1024,
  12969. 'B'); // 12MB payload, exceeds 10MB limit
  12970. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12971. // Server may either return 413 or close the connection
  12972. if (res) {
  12973. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12974. } else {
  12975. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12976. }
  12977. }
  12978. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12979. Server svr;
  12980. svr.Get("/", [](const Request &, Response &res) {
  12981. // Claims the most the client accepts, far more than it sends, then drops
  12982. // the connection.
  12983. res.set_content_provider(std::string().max_size(), "text/plain",
  12984. [](size_t, size_t, DataSink &sink) {
  12985. sink.write("abc", 3);
  12986. return false;
  12987. });
  12988. });
  12989. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12990. auto se = detail::scope_exit([&] {
  12991. svr.stop();
  12992. thread.join();
  12993. ASSERT_FALSE(svr.is_running());
  12994. });
  12995. svr.wait_until_ready();
  12996. Client cli(HOST, PORT);
  12997. cli.set_payload_max_length(0);
  12998. EXPECT_FALSE(cli.Get("/"));
  12999. }
  13000. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13001. // Stream API does, not as a plain read failure
  13002. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13003. Server svr;
  13004. svr.Get("/big", [](const Request &, Response &res) {
  13005. res.set_content(std::string(100000, 'b'), "text/plain");
  13006. });
  13007. auto port = svr.bind_to_any_port(HOST);
  13008. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13009. auto se = detail::scope_exit([&] {
  13010. svr.stop();
  13011. thread.join();
  13012. });
  13013. svr.wait_until_ready();
  13014. Client cli(HOST, port);
  13015. cli.set_payload_max_length(1000);
  13016. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13017. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13018. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13019. [](const char *, size_t) { return true; });
  13020. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13021. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13022. // Small on the wire, over the limit once decompressed
  13023. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13024. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13025. #endif
  13026. }
  13027. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13028. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13029. // path.
  13030. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13031. Server svr;
  13032. const size_t LIMIT = 64 * 1024; // 64KB
  13033. svr.set_payload_max_length(LIMIT);
  13034. size_t total = 0;
  13035. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13036. const ContentReader &content_reader) {
  13037. content_reader([&](const char * /*data*/, size_t len) {
  13038. total += len;
  13039. return true;
  13040. });
  13041. res.status = 200;
  13042. res.set_content("stream_ok", "text/plain");
  13043. });
  13044. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13045. auto se = detail::scope_exit([&] {
  13046. svr.stop();
  13047. thread.join();
  13048. ASSERT_FALSE(svr.is_running());
  13049. });
  13050. svr.wait_until_ready();
  13051. // Prepare 256KB raw data and gzip-compress it
  13052. std::string raw(256 * 1024, 'A');
  13053. std::string gz;
  13054. {
  13055. z_stream zs{};
  13056. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13057. Z_DEFAULT_STRATEGY);
  13058. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13059. zs.avail_in = static_cast<uInt>(raw.size());
  13060. char outbuf[4096];
  13061. int ret;
  13062. do {
  13063. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13064. zs.avail_out = sizeof(outbuf);
  13065. ret = deflate(&zs, Z_FINISH);
  13066. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13067. } while (ret != Z_STREAM_END);
  13068. deflateEnd(&zs);
  13069. }
  13070. Client cli(HOST, PORT);
  13071. cli.set_connection_timeout(std::chrono::seconds(5));
  13072. Headers headers = {{"Content-Encoding", "gzip"}};
  13073. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13074. "application/octet-stream");
  13075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13076. // Server must reject oversized decompressed payloads with 413.
  13077. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13078. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13079. EXPECT_LE(total, LIMIT);
  13080. }
  13081. #endif
  13082. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13083. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13084. // the payload must be passed through untouched instead of being rejected.
  13085. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13086. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13087. Server svr;
  13088. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13089. res.set_content(body, "image/jpeg");
  13090. res.set_header("Content-Encoding", "UTF-8");
  13091. });
  13092. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13093. res.set_content(body, "image/jpeg");
  13094. res.set_header("Content-Encoding", "identity");
  13095. });
  13096. svr.Post("/echo", [](const Request &req, Response &res) {
  13097. res.set_content(req.body, "image/jpeg");
  13098. });
  13099. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13100. auto se = detail::scope_exit([&] {
  13101. svr.stop();
  13102. t.join();
  13103. ASSERT_FALSE(svr.is_running());
  13104. });
  13105. svr.wait_until_ready();
  13106. Client cli(HOST, PORT);
  13107. {
  13108. auto res = cli.Get("/image");
  13109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13110. EXPECT_EQ(StatusCode::OK_200, res->status);
  13111. EXPECT_EQ(body, res->body);
  13112. }
  13113. {
  13114. auto res = cli.Get("/identity");
  13115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13116. EXPECT_EQ(StatusCode::OK_200, res->status);
  13117. EXPECT_EQ(body, res->body);
  13118. }
  13119. {
  13120. // The same applies to a request body reaching the server.
  13121. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13122. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13124. EXPECT_EQ(StatusCode::OK_200, res->status);
  13125. EXPECT_EQ(body, res->body);
  13126. }
  13127. }
  13128. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13129. // gzip-encoded response even when the build has no zlib support.
  13130. static const char GZIPPED_HELLO_WORLD[] = {
  13131. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13132. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13133. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13134. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13135. // A content coding is a whole token, not something the field value merely
  13136. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13137. // as "fibre" look like Brotli, and turned a multi-coding value like
  13138. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13139. // it was never meant to see.
  13140. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13141. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13142. Server svr;
  13143. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13144. res.set_content(body, "image/jpeg");
  13145. res.set_header("Content-Encoding", "fibre");
  13146. });
  13147. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13148. res.set_content(body, "image/jpeg");
  13149. res.set_header("Content-Encoding", "gzip, br");
  13150. });
  13151. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13152. res.set_content(body, "image/jpeg");
  13153. res.set_header("Content-Encoding", "x-zstd-ish");
  13154. });
  13155. auto port = svr.bind_to_any_port(HOST);
  13156. thread t = thread([&]() { svr.listen_after_bind(); });
  13157. auto se = detail::scope_exit([&] {
  13158. svr.stop();
  13159. t.join();
  13160. ASSERT_FALSE(svr.is_running());
  13161. });
  13162. svr.wait_until_ready();
  13163. Client cli(HOST, port);
  13164. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13165. auto res = cli.Get(path);
  13166. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13167. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13168. // Not a coding we recognize, so the payload comes back untouched
  13169. EXPECT_EQ(body, res->body) << path;
  13170. }
  13171. }
  13172. // A content coding cpp-httplib recognizes but was not built with must be
  13173. // reported as such. Handing the still-compressed payload back to the caller
  13174. // would silently corrupt it.
  13175. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13176. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13177. Server svr;
  13178. // "image/jpeg" keeps the server from applying a content coding of its own,
  13179. // so the hand-crafted Content-Encoding below survives.
  13180. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13181. res.set_content(gzipped, "image/jpeg");
  13182. res.set_header("Content-Encoding", "gzip");
  13183. });
  13184. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13185. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13186. res.set_content(gzipped, "image/jpeg");
  13187. res.set_header("Content-Encoding", "GZIP");
  13188. });
  13189. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13190. auto se = detail::scope_exit([&] {
  13191. svr.stop();
  13192. t.join();
  13193. ASSERT_FALSE(svr.is_running());
  13194. });
  13195. svr.wait_until_ready();
  13196. Client cli(HOST, PORT);
  13197. {
  13198. auto res = cli.Get("/gzipped");
  13199. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13201. EXPECT_EQ("Hello World!", res->body);
  13202. #else
  13203. ASSERT_FALSE(res);
  13204. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13205. #endif
  13206. }
  13207. {
  13208. // open_stream() must behave the same way.
  13209. auto handle = cli.open_stream("GET", "/gzipped");
  13210. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13211. ASSERT_TRUE(handle.is_valid());
  13212. std::string received;
  13213. char buf[256];
  13214. ssize_t n;
  13215. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13216. received.append(buf, static_cast<size_t>(n));
  13217. }
  13218. EXPECT_EQ("Hello World!", received);
  13219. #else
  13220. EXPECT_FALSE(handle.is_valid());
  13221. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13222. #endif
  13223. }
  13224. {
  13225. // A differently-cased coding must not be mistaken for an unknown one, or
  13226. // the body would be handed back still compressed.
  13227. auto res = cli.Get("/gzipped-uppercase");
  13228. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13230. EXPECT_EQ("Hello World!", res->body);
  13231. #else
  13232. ASSERT_FALSE(res);
  13233. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13234. #endif
  13235. }
  13236. }
  13237. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13238. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13239. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13240. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13241. // body a second time and appending a second Content-Encoding field line, so
  13242. // clients that decode one coding per listed value handed back raw gzip bytes.
  13243. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13244. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13245. Server svr;
  13246. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13247. // keeps the server from applying a coding of its own.
  13248. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13249. res.set_content(gzipped, "text/plain");
  13250. res.set_header("Content-Encoding", "gzip");
  13251. });
  13252. auto port = svr.bind_to_any_port(HOST);
  13253. thread t = thread([&]() { svr.listen_after_bind(); });
  13254. auto se = detail::scope_exit([&] {
  13255. svr.stop();
  13256. t.join();
  13257. ASSERT_FALSE(svr.is_running());
  13258. });
  13259. svr.wait_until_ready();
  13260. Client cli(HOST, port);
  13261. Headers headers = {{"Accept-Encoding", "gzip"}};
  13262. auto res = cli.Get("/pre-gzipped", headers);
  13263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13264. EXPECT_EQ(StatusCode::OK_200, res->status);
  13265. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13266. EXPECT_EQ("Hello World!", res->body);
  13267. }
  13268. // set_compress(false) sends every handler response as it is, buffered or
  13269. // streamed
  13270. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13271. const std::string text(1000, 'a');
  13272. Server svr;
  13273. svr.set_compress(false);
  13274. svr.Get("/buffered", [&](const Request &, Response &res) {
  13275. res.set_content(text, "text/plain");
  13276. });
  13277. svr.Get("/streamed", [&](const Request &, Response &res) {
  13278. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13279. sink.write(text.data(), text.size());
  13280. sink.done();
  13281. return true;
  13282. });
  13283. });
  13284. auto port = svr.bind_to_any_port(HOST);
  13285. ASSERT_LT(0, port);
  13286. thread t = thread([&] { svr.listen_after_bind(); });
  13287. auto se = detail::scope_exit([&] {
  13288. svr.stop();
  13289. t.join();
  13290. ASSERT_FALSE(svr.is_running());
  13291. });
  13292. svr.wait_until_ready();
  13293. Client cli(HOST, port);
  13294. cli.set_decompress(false);
  13295. for (auto path : {"/buffered", "/streamed"}) {
  13296. SCOPED_TRACE(path);
  13297. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13299. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13300. EXPECT_EQ(text, res->body);
  13301. }
  13302. }
  13303. // A chunked provider settles its coding where the headers are written and
  13304. // reuses it at write time. Both ends of that have to hold: a handler's own
  13305. // Content-Encoding suppresses the coding, and a response without one is still
  13306. // compressed as it always was.
  13307. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13308. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13309. const std::string plain = "Hello World! Hello World! Hello World!";
  13310. Server svr;
  13311. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13312. res.set_header("Content-Encoding", "gzip");
  13313. res.set_chunked_content_provider(
  13314. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13315. sink.write(gzipped.data(), gzipped.size());
  13316. sink.done();
  13317. return true;
  13318. });
  13319. });
  13320. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13321. res.set_chunked_content_provider(
  13322. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13323. sink.write(plain.data(), plain.size());
  13324. sink.done();
  13325. return true;
  13326. });
  13327. });
  13328. auto port = svr.bind_to_any_port(HOST);
  13329. thread t = thread([&]() { svr.listen_after_bind(); });
  13330. auto se = detail::scope_exit([&] {
  13331. svr.stop();
  13332. t.join();
  13333. ASSERT_FALSE(svr.is_running());
  13334. });
  13335. svr.wait_until_ready();
  13336. Client cli(HOST, port);
  13337. Headers headers = {{"Accept-Encoding", "gzip"}};
  13338. {
  13339. auto res = cli.Get("/pre-gzipped", headers);
  13340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13341. EXPECT_EQ(StatusCode::OK_200, res->status);
  13342. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13343. EXPECT_EQ("Hello World!", res->body);
  13344. }
  13345. {
  13346. auto res = cli.Get("/negotiated", headers);
  13347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13348. EXPECT_EQ(StatusCode::OK_200, res->status);
  13349. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13350. EXPECT_EQ(plain, res->body);
  13351. }
  13352. }
  13353. #endif
  13354. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13355. // the same message as the comma-joined one, so both have to be read the same
  13356. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13357. // single gzip coding, and a body the sender says was encoded twice was handed
  13358. // back after one pass, still compressed but presented as decoded.
  13359. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13360. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13361. Server svr;
  13362. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13363. res.set_content(body, "image/jpeg");
  13364. res.headers.emplace("Content-Encoding", "gzip");
  13365. res.headers.emplace("Content-Encoding", "gzip");
  13366. });
  13367. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13368. res.set_content(body, "image/jpeg");
  13369. res.set_header("Content-Encoding", "gzip, gzip");
  13370. });
  13371. auto port = svr.bind_to_any_port(HOST);
  13372. thread t = thread([&]() { svr.listen_after_bind(); });
  13373. auto se = detail::scope_exit([&] {
  13374. svr.stop();
  13375. t.join();
  13376. ASSERT_FALSE(svr.is_running());
  13377. });
  13378. svr.wait_until_ready();
  13379. Client cli(HOST, port);
  13380. // Two codings is not something cpp-httplib decodes, so both representations
  13381. // take the pass-through path rather than one of them being gunzipped once.
  13382. for (const char *path : {"/split", "/joined"}) {
  13383. auto res = cli.Get(path);
  13384. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13385. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13386. EXPECT_EQ(body, res->body) << path;
  13387. }
  13388. }
  13389. // Regression test for DoS vulnerability: a malicious server sending a response
  13390. // without Content-Length header must not cause unbounded memory consumption on
  13391. // the client side. The client should stop reading after a reasonable limit,
  13392. // similar to the server-side set_payload_max_length protection.
  13393. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13394. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13395. #ifndef _WIN32
  13396. signal(SIGPIPE, SIG_IGN);
  13397. #endif
  13398. auto server_thread = std::thread([] {
  13399. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13400. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13401. default_socket_options(srv);
  13402. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13403. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13404. sockaddr_in addr{};
  13405. addr.sin_family = AF_INET;
  13406. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13407. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13408. int opt = 1;
  13409. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13410. #ifdef _WIN32
  13411. reinterpret_cast<const char *>(&opt),
  13412. #else
  13413. &opt,
  13414. #endif
  13415. sizeof(opt));
  13416. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13417. ::listen(srv, 1);
  13418. sockaddr_in cli_addr{};
  13419. socklen_t cli_len = sizeof(cli_addr);
  13420. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13421. if (cli != INVALID_SOCKET) {
  13422. char buf[4096];
  13423. ::recv(cli, buf, sizeof(buf), 0);
  13424. // Malicious response: no Content-Length, no chunked encoding
  13425. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13426. "Connection: close\r\n"
  13427. "\r\n";
  13428. ::send(cli,
  13429. #ifdef _WIN32
  13430. static_cast<const char *>(response_header.c_str()),
  13431. static_cast<int>(response_header.size()),
  13432. #else
  13433. response_header.c_str(), response_header.size(),
  13434. #endif
  13435. 0);
  13436. // Send 10MB of data
  13437. std::string chunk(64 * 1024, 'A');
  13438. size_t total_sent = 0;
  13439. while (total_sent < MALICIOUS_DATA_SIZE) {
  13440. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13441. auto sent = ::send(cli,
  13442. #ifdef _WIN32
  13443. static_cast<const char *>(chunk.c_str()),
  13444. static_cast<int>(to_send),
  13445. #else
  13446. chunk.c_str(), to_send,
  13447. #endif
  13448. 0);
  13449. if (sent <= 0) break;
  13450. total_sent += static_cast<size_t>(sent);
  13451. }
  13452. detail::close_socket(cli);
  13453. }
  13454. detail::close_socket(srv);
  13455. });
  13456. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13457. size_t total_read = 0;
  13458. {
  13459. Client cli("127.0.0.1", PORT + 2);
  13460. cli.set_read_timeout(5, 0);
  13461. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13462. auto stream = cli.open_stream("GET", "/malicious");
  13463. ASSERT_TRUE(stream.is_valid());
  13464. char buffer[64 * 1024];
  13465. ssize_t n;
  13466. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13467. total_read += static_cast<size_t>(n);
  13468. }
  13469. } // StreamHandle and Client destroyed here, closing the socket
  13470. server_thread.join();
  13471. // With set_payload_max_length, the client must stop reading before consuming
  13472. // all 10MB. The read loop should be cut off at or near the configured limit.
  13473. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13474. << "Client read " << total_read << " bytes, exceeding the configured "
  13475. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13476. }
  13477. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13478. // the entire response body without truncation.
  13479. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13480. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13481. #ifndef _WIN32
  13482. signal(SIGPIPE, SIG_IGN);
  13483. #endif
  13484. auto server_thread = std::thread([] {
  13485. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13486. default_socket_options(srv);
  13487. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13488. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13489. sockaddr_in addr{};
  13490. addr.sin_family = AF_INET;
  13491. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13492. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13493. int opt = 1;
  13494. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13495. #ifdef _WIN32
  13496. reinterpret_cast<const char *>(&opt),
  13497. #else
  13498. &opt,
  13499. #endif
  13500. sizeof(opt));
  13501. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13502. ::listen(srv, 1);
  13503. sockaddr_in cli_addr{};
  13504. socklen_t cli_len = sizeof(cli_addr);
  13505. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13506. if (cli != INVALID_SOCKET) {
  13507. char buf[4096];
  13508. ::recv(cli, buf, sizeof(buf), 0);
  13509. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13510. "Connection: close\r\n"
  13511. "\r\n";
  13512. ::send(cli,
  13513. #ifdef _WIN32
  13514. static_cast<const char *>(response_header.c_str()),
  13515. static_cast<int>(response_header.size()),
  13516. #else
  13517. response_header.c_str(), response_header.size(),
  13518. #endif
  13519. 0);
  13520. std::string chunk(64 * 1024, 'A');
  13521. size_t total_sent = 0;
  13522. while (total_sent < DATA_SIZE) {
  13523. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13524. auto sent = ::send(cli,
  13525. #ifdef _WIN32
  13526. static_cast<const char *>(chunk.c_str()),
  13527. static_cast<int>(to_send),
  13528. #else
  13529. chunk.c_str(), to_send,
  13530. #endif
  13531. 0);
  13532. if (sent <= 0) break;
  13533. total_sent += static_cast<size_t>(sent);
  13534. }
  13535. #ifdef _WIN32
  13536. ::shutdown(cli, SD_SEND);
  13537. #else
  13538. ::shutdown(cli, SHUT_WR);
  13539. #endif
  13540. // Drain until the client closes its end, ensuring all data is delivered
  13541. char drain[1024];
  13542. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13543. detail::close_socket(cli);
  13544. }
  13545. detail::close_socket(srv);
  13546. });
  13547. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13548. size_t total_read = 0;
  13549. {
  13550. Client cli("127.0.0.1", PORT + 2);
  13551. cli.set_read_timeout(5, 0);
  13552. cli.set_payload_max_length(0); // 0 means no limit
  13553. auto stream = cli.open_stream("GET", "/data");
  13554. ASSERT_TRUE(stream.is_valid());
  13555. char buffer[64 * 1024];
  13556. ssize_t n;
  13557. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13558. total_read += static_cast<size_t>(n);
  13559. }
  13560. }
  13561. server_thread.join();
  13562. EXPECT_EQ(total_read, DATA_SIZE)
  13563. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13564. << " bytes without truncation, but only read " << total_read << " bytes.";
  13565. }
  13566. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13567. // enormous Content-Length must not cause the client to pre-allocate a huge
  13568. // response body buffer. The reservation is capped at payload_max_length_, and
  13569. // the read itself fails when the body exceeds the limit.
  13570. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13571. #ifndef _WIN32
  13572. signal(SIGPIPE, SIG_IGN);
  13573. #endif
  13574. auto server_thread = std::thread([] {
  13575. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13576. default_socket_options(srv);
  13577. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13578. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13579. sockaddr_in addr{};
  13580. addr.sin_family = AF_INET;
  13581. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13582. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13583. int opt = 1;
  13584. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13585. #ifdef _WIN32
  13586. reinterpret_cast<const char *>(&opt),
  13587. #else
  13588. &opt,
  13589. #endif
  13590. sizeof(opt));
  13591. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13592. ::listen(srv, 1);
  13593. sockaddr_in cli_addr{};
  13594. socklen_t cli_len = sizeof(cli_addr);
  13595. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13596. if (cli != INVALID_SOCKET) {
  13597. char buf[4096];
  13598. ::recv(cli, buf, sizeof(buf), 0);
  13599. // Malicious response: claim a 20GB body but send only a tiny payload.
  13600. std::string response = "HTTP/1.1 200 OK\r\n"
  13601. "Content-Length: 20000000000\r\n"
  13602. "\r\n"
  13603. "abc";
  13604. ::send(cli,
  13605. #ifdef _WIN32
  13606. static_cast<const char *>(response.c_str()),
  13607. static_cast<int>(response.size()),
  13608. #else
  13609. response.c_str(), response.size(),
  13610. #endif
  13611. 0);
  13612. detail::close_socket(cli);
  13613. }
  13614. detail::close_socket(srv);
  13615. });
  13616. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13617. {
  13618. Client cli("127.0.0.1", PORT + 2);
  13619. cli.set_read_timeout(5, 0);
  13620. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13621. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13622. // (server claims more bytes than payload_max_length permits), but it must
  13623. // not exhaust memory before getting there.
  13624. auto res = cli.Get("/malicious");
  13625. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13626. }
  13627. server_thread.join();
  13628. }
  13629. // Verify that content_receiver bypasses the default payload_max_length,
  13630. // allowing streaming downloads larger than 100MB without requiring an explicit
  13631. // set_payload_max_length call.
  13632. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13633. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13634. #ifndef _WIN32
  13635. signal(SIGPIPE, SIG_IGN);
  13636. #endif
  13637. auto server_thread = std::thread([] {
  13638. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13639. default_socket_options(srv);
  13640. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13641. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13642. sockaddr_in addr{};
  13643. addr.sin_family = AF_INET;
  13644. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13645. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13646. int opt = 1;
  13647. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13648. #ifdef _WIN32
  13649. reinterpret_cast<const char *>(&opt),
  13650. #else
  13651. &opt,
  13652. #endif
  13653. sizeof(opt));
  13654. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13655. ::listen(srv, 1);
  13656. sockaddr_in cli_addr{};
  13657. socklen_t cli_len = sizeof(cli_addr);
  13658. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13659. if (cli != INVALID_SOCKET) {
  13660. char buf[4096];
  13661. ::recv(cli, buf, sizeof(buf), 0);
  13662. // Response with Content-Length larger than default 100MB limit
  13663. auto content_length = std::to_string(DATA_SIZE);
  13664. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13665. "Content-Length: " +
  13666. content_length +
  13667. "\r\n"
  13668. "Connection: close\r\n"
  13669. "\r\n";
  13670. ::send(cli,
  13671. #ifdef _WIN32
  13672. static_cast<const char *>(response_header.c_str()),
  13673. static_cast<int>(response_header.size()),
  13674. #else
  13675. response_header.c_str(), response_header.size(),
  13676. #endif
  13677. 0);
  13678. std::string chunk(64 * 1024, 'A');
  13679. size_t total_sent = 0;
  13680. while (total_sent < DATA_SIZE) {
  13681. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13682. auto sent = ::send(cli,
  13683. #ifdef _WIN32
  13684. static_cast<const char *>(chunk.c_str()),
  13685. static_cast<int>(to_send),
  13686. #else
  13687. chunk.c_str(), to_send,
  13688. #endif
  13689. 0);
  13690. if (sent <= 0) break;
  13691. total_sent += static_cast<size_t>(sent);
  13692. }
  13693. detail::close_socket(cli);
  13694. }
  13695. detail::close_socket(srv);
  13696. });
  13697. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13698. size_t total_received = 0;
  13699. {
  13700. Client cli("127.0.0.1", PORT + 2);
  13701. cli.set_read_timeout(10, 0);
  13702. // Do NOT call set_payload_max_length — use the default 100MB limit
  13703. auto res =
  13704. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13705. total_received += data_length;
  13706. return true;
  13707. });
  13708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13709. EXPECT_EQ(StatusCode::OK_200, res->status);
  13710. }
  13711. server_thread.join();
  13712. EXPECT_EQ(total_received, DATA_SIZE)
  13713. << "With content_receiver, the client should read all " << DATA_SIZE
  13714. << " bytes despite the default 100MB payload_max_length, but only read "
  13715. << total_received << " bytes.";
  13716. }
  13717. // Verify that an explicit set_payload_max_length smaller than the response is
  13718. // enforced even when a content_receiver is used.
  13719. TEST(ClientVulnerabilityTest,
  13720. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13721. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13722. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13723. #ifndef _WIN32
  13724. signal(SIGPIPE, SIG_IGN);
  13725. #endif
  13726. auto server_thread = std::thread([] {
  13727. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13728. default_socket_options(srv);
  13729. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13730. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13731. sockaddr_in addr{};
  13732. addr.sin_family = AF_INET;
  13733. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13734. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13735. int opt = 1;
  13736. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13737. #ifdef _WIN32
  13738. reinterpret_cast<const char *>(&opt),
  13739. #else
  13740. &opt,
  13741. #endif
  13742. sizeof(opt));
  13743. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13744. ::listen(srv, 1);
  13745. sockaddr_in cli_addr{};
  13746. socklen_t cli_len = sizeof(cli_addr);
  13747. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13748. if (cli != INVALID_SOCKET) {
  13749. char buf[4096];
  13750. ::recv(cli, buf, sizeof(buf), 0);
  13751. auto content_length = std::to_string(DATA_SIZE);
  13752. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13753. "Content-Length: " +
  13754. content_length +
  13755. "\r\n"
  13756. "Connection: close\r\n"
  13757. "\r\n";
  13758. ::send(cli,
  13759. #ifdef _WIN32
  13760. static_cast<const char *>(response_header.c_str()),
  13761. static_cast<int>(response_header.size()),
  13762. #else
  13763. response_header.c_str(), response_header.size(),
  13764. #endif
  13765. 0);
  13766. std::string chunk(64 * 1024, 'A');
  13767. size_t total_sent = 0;
  13768. while (total_sent < DATA_SIZE) {
  13769. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13770. auto sent = ::send(cli,
  13771. #ifdef _WIN32
  13772. static_cast<const char *>(chunk.c_str()),
  13773. static_cast<int>(to_send),
  13774. #else
  13775. chunk.c_str(), to_send,
  13776. #endif
  13777. 0);
  13778. if (sent <= 0) break;
  13779. total_sent += static_cast<size_t>(sent);
  13780. }
  13781. detail::close_socket(cli);
  13782. }
  13783. detail::close_socket(srv);
  13784. });
  13785. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13786. size_t total_received = 0;
  13787. {
  13788. Client cli("127.0.0.1", PORT + 2);
  13789. cli.set_read_timeout(10, 0);
  13790. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13791. auto res =
  13792. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13793. total_received += data_length;
  13794. return true;
  13795. });
  13796. // Should fail because 200MB exceeds the explicit 150MB limit
  13797. EXPECT_FALSE(res);
  13798. }
  13799. server_thread.join();
  13800. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13801. << "Client with content_receiver should respect the explicit "
  13802. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13803. << total_received << " bytes.";
  13804. }
  13805. // Verify that an explicit set_payload_max_length larger than the response
  13806. // allows the content_receiver to read all data successfully.
  13807. TEST(ClientVulnerabilityTest,
  13808. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13809. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13810. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13811. #ifndef _WIN32
  13812. signal(SIGPIPE, SIG_IGN);
  13813. #endif
  13814. auto server_thread = std::thread([] {
  13815. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13816. default_socket_options(srv);
  13817. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13818. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13819. sockaddr_in addr{};
  13820. addr.sin_family = AF_INET;
  13821. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13822. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13823. int opt = 1;
  13824. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13825. #ifdef _WIN32
  13826. reinterpret_cast<const char *>(&opt),
  13827. #else
  13828. &opt,
  13829. #endif
  13830. sizeof(opt));
  13831. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13832. ::listen(srv, 1);
  13833. sockaddr_in cli_addr{};
  13834. socklen_t cli_len = sizeof(cli_addr);
  13835. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13836. if (cli != INVALID_SOCKET) {
  13837. char buf[4096];
  13838. ::recv(cli, buf, sizeof(buf), 0);
  13839. auto content_length = std::to_string(DATA_SIZE);
  13840. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13841. "Content-Length: " +
  13842. content_length +
  13843. "\r\n"
  13844. "Connection: close\r\n"
  13845. "\r\n";
  13846. ::send(cli,
  13847. #ifdef _WIN32
  13848. static_cast<const char *>(response_header.c_str()),
  13849. static_cast<int>(response_header.size()),
  13850. #else
  13851. response_header.c_str(), response_header.size(),
  13852. #endif
  13853. 0);
  13854. std::string chunk(64 * 1024, 'A');
  13855. size_t total_sent = 0;
  13856. while (total_sent < DATA_SIZE) {
  13857. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13858. auto sent = ::send(cli,
  13859. #ifdef _WIN32
  13860. static_cast<const char *>(chunk.c_str()),
  13861. static_cast<int>(to_send),
  13862. #else
  13863. chunk.c_str(), to_send,
  13864. #endif
  13865. 0);
  13866. if (sent <= 0) break;
  13867. total_sent += static_cast<size_t>(sent);
  13868. }
  13869. #ifdef _WIN32
  13870. ::shutdown(cli, SD_SEND);
  13871. #else
  13872. ::shutdown(cli, SHUT_WR);
  13873. #endif
  13874. char drain[1024];
  13875. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13876. detail::close_socket(cli);
  13877. }
  13878. detail::close_socket(srv);
  13879. });
  13880. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13881. size_t total_received = 0;
  13882. {
  13883. Client cli("127.0.0.1", PORT + 2);
  13884. cli.set_read_timeout(10, 0);
  13885. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13886. auto res =
  13887. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13888. total_received += data_length;
  13889. return true;
  13890. });
  13891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13892. EXPECT_EQ(StatusCode::OK_200, res->status);
  13893. }
  13894. server_thread.join();
  13895. EXPECT_EQ(total_received, DATA_SIZE)
  13896. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13897. << " bytes (larger than " << DATA_SIZE
  13898. << " bytes response), content_receiver should read all data, but only "
  13899. "read "
  13900. << total_received << " bytes.";
  13901. }
  13902. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13903. // Regression test for "zip bomb" attack on the client side: a malicious server
  13904. // sends a small gzip-compressed response that decompresses to a huge payload.
  13905. // The client must enforce payload_max_length on the decompressed size.
  13906. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13907. constexpr size_t DECOMPRESSED_SIZE =
  13908. 10 * 1024 * 1024; // 10MB after decompression
  13909. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13910. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13911. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13912. std::string compressed;
  13913. {
  13914. httplib::detail::gzip_compressor compressor;
  13915. bool ok =
  13916. compressor.compress(uncompressed.data(), uncompressed.size(),
  13917. /*last=*/true, [&](const char *buf, size_t len) {
  13918. compressed.append(buf, len);
  13919. return true;
  13920. });
  13921. ASSERT_TRUE(ok);
  13922. }
  13923. // Sanity: compressed data should be much smaller than the decompressed size
  13924. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13925. #ifndef _WIN32
  13926. signal(SIGPIPE, SIG_IGN);
  13927. #endif
  13928. // Set up the listening socket in the main thread so the server is guaranteed
  13929. // to be ready before the client connects (eliminates race condition).
  13930. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13931. default_socket_options(srv);
  13932. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13933. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13934. sockaddr_in addr{};
  13935. addr.sin_family = AF_INET;
  13936. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13937. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13938. int opt = 1;
  13939. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13940. #ifdef _WIN32
  13941. reinterpret_cast<const char *>(&opt),
  13942. #else
  13943. &opt,
  13944. #endif
  13945. sizeof(opt));
  13946. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13947. ASSERT_EQ(0, ::listen(srv, 1));
  13948. auto server_thread = std::thread([&compressed, srv] {
  13949. sockaddr_in cli_addr{};
  13950. socklen_t cli_len = sizeof(cli_addr);
  13951. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13952. if (cli != INVALID_SOCKET) {
  13953. // Read the full HTTP request (until \r\n\r\n)
  13954. char buf[4096];
  13955. size_t total = 0;
  13956. while (total < sizeof(buf)) {
  13957. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13958. if (n <= 0) break;
  13959. total += static_cast<size_t>(n);
  13960. // Check for end of headers
  13961. if (total >= 4) {
  13962. std::string req(buf, total);
  13963. if (req.find("\r\n\r\n") != std::string::npos) break;
  13964. }
  13965. }
  13966. // Malicious response: gzip-compressed body, no Content-Length
  13967. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13968. "Content-Encoding: gzip\r\n"
  13969. "Connection: close\r\n"
  13970. "\r\n";
  13971. ::send(cli,
  13972. #ifdef _WIN32
  13973. static_cast<const char *>(response_header.c_str()),
  13974. static_cast<int>(response_header.size()),
  13975. #else
  13976. response_header.c_str(), response_header.size(),
  13977. #endif
  13978. 0);
  13979. // Send the compressed payload (small on the wire, huge when decompressed)
  13980. size_t total_sent = 0;
  13981. while (total_sent < compressed.size()) {
  13982. auto to_send = std::min(compressed.size() - total_sent,
  13983. static_cast<size_t>(64 * 1024));
  13984. auto sent =
  13985. ::send(cli,
  13986. #ifdef _WIN32
  13987. static_cast<const char *>(compressed.c_str() + total_sent),
  13988. static_cast<int>(to_send),
  13989. #else
  13990. compressed.c_str() + total_sent, to_send,
  13991. #endif
  13992. 0);
  13993. if (sent <= 0) break;
  13994. total_sent += static_cast<size_t>(sent);
  13995. }
  13996. detail::close_socket(cli);
  13997. }
  13998. });
  13999. auto se = detail::scope_exit([&] {
  14000. detail::close_socket(srv);
  14001. server_thread.join();
  14002. });
  14003. size_t total_decompressed = 0;
  14004. {
  14005. Client cli("127.0.0.1", PORT + 3);
  14006. cli.set_read_timeout(5, 0);
  14007. cli.set_decompress(true);
  14008. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14009. auto stream = cli.open_stream("GET", "/zipbomb");
  14010. ASSERT_TRUE(stream.is_valid());
  14011. char buffer[64 * 1024];
  14012. ssize_t n;
  14013. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14014. total_decompressed += static_cast<size_t>(n);
  14015. }
  14016. }
  14017. // The decompressed size must be capped by payload_max_length. Without
  14018. // protection, the client would decompress the full 10MB from a tiny
  14019. // compressed payload, enabling a zip bomb DoS attack.
  14020. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14021. << "Client decompressed " << total_decompressed
  14022. << " bytes from a gzip response. The decompressed size should be "
  14023. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14024. }
  14025. #endif
  14026. TEST(HostAndPortPropertiesTest, NoSSL) {
  14027. httplib::Client cli("www.google.com", 1234);
  14028. ASSERT_EQ("www.google.com", cli.host());
  14029. ASSERT_EQ(1234, cli.port());
  14030. }
  14031. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14032. httplib::Client cli("www.google.com:1234");
  14033. ASSERT_EQ("www.google.com", cli.host());
  14034. ASSERT_EQ(1234, cli.port());
  14035. }
  14036. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14037. // Port number that overflows int — should not crash, client becomes invalid
  14038. httplib::Client cli("http://www.google.com:99999999999999999999");
  14039. ASSERT_FALSE(cli.is_valid());
  14040. }
  14041. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14042. // Port 99999 exceeds valid range (1-65535) — should not crash
  14043. httplib::Client cli("http://www.google.com:99999");
  14044. ASSERT_FALSE(cli.is_valid());
  14045. auto res = cli.Get("/");
  14046. EXPECT_FALSE(res);
  14047. EXPECT_EQ(Error::Connection, res.error());
  14048. }
  14049. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14050. httplib::Client cli("http://user:pass@localhost:1234");
  14051. ASSERT_FALSE(cli.is_valid());
  14052. EXPECT_FALSE(cli.Get("/"));
  14053. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14054. }
  14055. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14056. httplib::Client cli("http://www.google.com:80abc");
  14057. ASSERT_FALSE(cli.is_valid());
  14058. }
  14059. #ifdef CPPHTTPLIB_SSL_ENABLED
  14060. TEST(HostAndPortPropertiesTest, SSL) {
  14061. httplib::SSLClient cli("www.google.com");
  14062. ASSERT_EQ("www.google.com", cli.host());
  14063. ASSERT_EQ(443, cli.port());
  14064. }
  14065. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14066. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14067. std::string cert;
  14068. read_file(CA_CERT_FILE, cert);
  14069. httplib::SSLClient httplib_client("www.google.com");
  14070. // Load CA store first time
  14071. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14072. // Load CA store second time (update)
  14073. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14074. // Verify client is still valid and can make connections
  14075. httplib_client.enable_server_certificate_verification(true);
  14076. auto res = httplib_client.Get("/");
  14077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14078. // Google may return 200 or 301 depending on various factors
  14079. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14080. res->status == StatusCode::MovedPermanently_301);
  14081. }
  14082. TEST(SSLClientTest, ServerNameIndication_Online) {
  14083. auto host = "httpbingo.org";
  14084. auto path = std::string{"/get"};
  14085. SSLClient cli(host, 443);
  14086. auto res = cli.Get(path);
  14087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14088. ASSERT_EQ(StatusCode::OK_200, res->status);
  14089. }
  14090. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14091. // Use a site that will cause SSL verification failure due to self-signed cert
  14092. SSLClient cli("self-signed.badssl.com", 443);
  14093. cli.enable_server_certificate_verification(true);
  14094. auto res = cli.Get("/");
  14095. ASSERT_TRUE(!res);
  14096. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14097. // Verify backend error is captured for SSLServerVerification
  14098. // This occurs when certificate verification fails
  14099. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14100. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14101. EXPECT_NE(0UL, res.ssl_backend_error());
  14102. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14103. res.ssl_error());
  14104. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14105. #if !defined(_WIN32) || \
  14106. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14107. // On non-Windows or when Windows Schannel is disabled, the error comes
  14108. // from OpenSSL's verification
  14109. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14110. res.ssl_backend_error());
  14111. #endif
  14112. #endif
  14113. }
  14114. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14115. // Use a site where hostname doesn't match the certificate
  14116. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14117. SSLClient cli("wrong.host.badssl.com", 443);
  14118. cli.enable_server_certificate_verification(true);
  14119. cli.enable_server_hostname_verification(true);
  14120. auto res = cli.Get("/");
  14121. ASSERT_TRUE(!res);
  14122. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14123. // Verify backend error is captured for hostname verification failure
  14124. EXPECT_NE(0UL, res.ssl_backend_error());
  14125. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14126. res.ssl_error());
  14127. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14128. #if !defined(_WIN32) || \
  14129. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14130. // On non-Windows or when Windows Schannel is disabled, the error comes
  14131. // from OpenSSL's hostname verification
  14132. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14133. res.ssl_backend_error());
  14134. #endif
  14135. #endif
  14136. }
  14137. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14138. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14139. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14140. SSLClient cli("www.google.com", 443);
  14141. cli.enable_server_certificate_verification(true);
  14142. auto res = cli.Get("/");
  14143. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14144. }
  14145. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14146. SSLClient cli("www.google.com", 443);
  14147. cli.enable_server_certificate_verification(true);
  14148. cli.enable_windows_certificate_verification(false);
  14149. auto res = cli.Get("/");
  14150. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14151. }
  14152. // The server sends an intermediate cross-signed by a root Windows trusts,
  14153. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14154. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14155. SSLClient cli("accounts.spotify.com", 443);
  14156. auto res = cli.Get("/");
  14157. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14158. << " ssl_backend_error=" << res.ssl_backend_error();
  14159. }
  14160. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14161. // policy status, which no backend reports for a self-signed certificate.
  14162. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14163. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14164. ASSERT_TRUE(svr.is_valid());
  14165. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14166. auto se = detail::scope_exit([&] {
  14167. svr.stop();
  14168. t.join();
  14169. ASSERT_FALSE(svr.is_running());
  14170. });
  14171. svr.wait_until_ready();
  14172. SSLClient cli("127.0.0.1", PORT);
  14173. cli.set_connection_timeout(30);
  14174. auto res = cli.Get("/");
  14175. ASSERT_FALSE(res);
  14176. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14177. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14178. }
  14179. #endif
  14180. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14181. Client cli("https://google.com");
  14182. auto res = cli.Get("/");
  14183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14184. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14185. }
  14186. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14187. SSLClient cli("google.com");
  14188. cli.set_ca_cert_path(CA_CERT_FILE);
  14189. auto res = cli.Get("/");
  14190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14191. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14192. }
  14193. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14194. SSLClient cli("google.com");
  14195. cli.enable_server_certificate_verification(true);
  14196. cli.set_ca_cert_path("hello");
  14197. auto res = cli.Get("/");
  14198. ASSERT_TRUE(!res);
  14199. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14200. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14201. // should be set
  14202. EXPECT_EQ(0, res.ssl_error());
  14203. // Verify backend error is captured for SSLLoadingCerts
  14204. // This error occurs when loading CA certificates fails
  14205. EXPECT_NE(0UL, res.ssl_backend_error());
  14206. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14207. // OpenSSL specific error codes:
  14208. // > openssl errstr 0x80000002
  14209. // error:80000002:system library::No such file or directory
  14210. // > openssl errstr 0xA000126
  14211. // error:0A000126:SSL routines::unexpected eof while reading
  14212. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14213. res.ssl_backend_error() == 0xA000126);
  14214. #endif
  14215. }
  14216. TEST(SSLClientTest, ServerCertificateVerification4) {
  14217. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14218. ASSERT_TRUE(svr.is_valid());
  14219. svr.Get("/test", [&](const Request &, Response &res) {
  14220. res.set_content("test", "text/plain");
  14221. svr.stop();
  14222. ASSERT_TRUE(true);
  14223. });
  14224. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14225. auto se = detail::scope_exit([&] {
  14226. t.join();
  14227. ASSERT_FALSE(svr.is_running());
  14228. });
  14229. svr.wait_until_ready();
  14230. SSLClient cli("127.0.0.1", PORT);
  14231. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14232. cli.enable_server_certificate_verification(true);
  14233. cli.set_connection_timeout(30);
  14234. auto res = cli.Get("/test");
  14235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14236. ASSERT_EQ(StatusCode::OK_200, res->status);
  14237. }
  14238. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14239. std::string cert;
  14240. read_file(CA_CERT_FILE, cert);
  14241. SSLClient cli("google.com");
  14242. cli.load_ca_cert_store(cert.data(), cert.size());
  14243. const auto res = cli.Get("/");
  14244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14245. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14246. }
  14247. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14248. // clang-format off
  14249. static constexpr char cert[] =
  14250. "GlobalSign Root CA\n"
  14251. "==================\n"
  14252. "-----BEGIN CERTIFICATE-----\n"
  14253. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14254. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14255. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14256. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14257. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14258. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14259. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14260. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14261. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14262. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14263. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14264. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14265. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14266. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14267. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14268. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14269. "-----END CERTIFICATE-----\n";
  14270. // clang-format on
  14271. SSLClient cli("google.com");
  14272. cli.load_ca_cert_store(cert, sizeof(cert));
  14273. const auto res = cli.Get("/");
  14274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14275. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14276. }
  14277. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14278. SSLClient cli("www.youtube.com");
  14279. cli.set_ca_cert_path(CA_CERT_FILE);
  14280. cli.enable_server_certificate_verification(true);
  14281. cli.set_follow_location(true);
  14282. auto res = cli.Get("/");
  14283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14284. ASSERT_EQ(StatusCode::OK_200, res->status);
  14285. }
  14286. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14287. SSLClient cli("wWw.YouTube.Com");
  14288. cli.set_ca_cert_path(CA_CERT_FILE);
  14289. cli.enable_server_certificate_verification(true);
  14290. cli.enable_server_hostname_verification(true);
  14291. cli.set_follow_location(true);
  14292. auto res = cli.Get("/");
  14293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14294. ASSERT_EQ(StatusCode::OK_200, res->status);
  14295. }
  14296. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14297. SSLClient cli("gOoGlE.COm");
  14298. cli.enable_server_certificate_verification(true);
  14299. cli.enable_server_hostname_verification(true);
  14300. cli.set_follow_location(true);
  14301. auto res = cli.Get("/");
  14302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14303. ASSERT_EQ(StatusCode::OK_200, res->status);
  14304. }
  14305. TEST(SSLClientTest, Issue2004_Online) {
  14306. Client client("https://google.com");
  14307. client.set_follow_location(true);
  14308. auto res = client.Get("/");
  14309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14310. ASSERT_EQ(StatusCode::OK_200, res->status);
  14311. auto body = res->body;
  14312. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14313. }
  14314. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14315. // Create SSLClient with invalid cert/key to make is_valid() return false
  14316. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14317. "nonexistent_key.pem");
  14318. // is_valid() should be false due to cert loading failure
  14319. ASSERT_FALSE(cli.is_valid());
  14320. auto res = cli.Get("/");
  14321. ASSERT_FALSE(res);
  14322. EXPECT_EQ(Error::SSLConnection, res.error());
  14323. }
  14324. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14325. // Test for Issue #2251: SSL error not properly reported when client cert
  14326. // and key paths are swapped or mismatched
  14327. // This simulates the scenario where user accidentally swaps the cert and key
  14328. // files
  14329. // Using client cert file as private key and vice versa (completely wrong)
  14330. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14331. // Should fail validation due to cert/key mismatch
  14332. ASSERT_FALSE(cli.is_valid());
  14333. // Attempt to make a request should fail with proper error
  14334. auto res = cli.Get("/");
  14335. ASSERT_FALSE(res);
  14336. EXPECT_EQ(Error::SSLConnection, res.error());
  14337. // SSL error should be recorded in the Result object (this is the key fix for
  14338. // Issue #2251)
  14339. auto backend_error = res.ssl_backend_error();
  14340. EXPECT_NE(0u, backend_error);
  14341. }
  14342. // Tests cert/key mismatch detection at the TLS context level
  14343. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14344. // Test that using mismatched cert/key causes connection failure.
  14345. // We verify this at the SSLClient level rather than through internal
  14346. // TLS API functions.
  14347. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14348. cli.enable_server_certificate_verification(false);
  14349. cli.set_connection_timeout(2);
  14350. // The mismatch should cause a connection or handshake error
  14351. auto res = cli.Get("/test");
  14352. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14353. // Either way, the request should fail
  14354. EXPECT_FALSE(res);
  14355. }
  14356. #endif
  14357. #if 0
  14358. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14359. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14360. ASSERT_TRUE(cli != nullptr);
  14361. cli->set_address_family(AF_INET6);
  14362. cli->set_interface("en0");
  14363. auto res = cli->Get("/get");
  14364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14365. ASSERT_EQ(StatusCode::OK_200, res->status);
  14366. }
  14367. #endif
  14368. // Client certificate tests - work with all TLS backends
  14369. #ifdef CPPHTTPLIB_SSL_ENABLED
  14370. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14371. void ClientCertPresent(
  14372. const std::string &client_cert_file,
  14373. const std::string &client_private_key_file,
  14374. const std::string &client_encrypted_private_key_pass = std::string(),
  14375. const ClientCertServerSetup &setup = nullptr) {
  14376. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14377. ASSERT_TRUE(svr.is_valid());
  14378. if (setup) { setup(svr); }
  14379. svr.Get("/test", [&](const Request &req, Response &res) {
  14380. res.set_content("test", "text/plain");
  14381. auto cert = req.peer_cert();
  14382. ASSERT_TRUE(static_cast<bool>(cert));
  14383. std::string common_name = cert.subject_cn();
  14384. EXPECT_EQ("Common Name", common_name);
  14385. });
  14386. auto port = svr.bind_to_any_port(HOST);
  14387. ASSERT_LT(0, port);
  14388. thread t = thread([&]() { svr.listen_after_bind(); });
  14389. auto se = detail::scope_exit([&] {
  14390. svr.stop();
  14391. t.join();
  14392. ASSERT_FALSE(svr.is_running());
  14393. });
  14394. svr.wait_until_ready();
  14395. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14396. client_encrypted_private_key_pass);
  14397. cli.enable_server_certificate_verification(false);
  14398. cli.set_connection_timeout(30);
  14399. auto res = cli.Get("/test");
  14400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14401. ASSERT_EQ(StatusCode::OK_200, res->status);
  14402. }
  14403. TEST(SSLClientServerTest, ClientCertPresent) {
  14404. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14405. }
  14406. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14407. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14408. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14409. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14410. }
  14411. // Expects svr, which must require client certificates, to reject a client
  14412. // that has none
  14413. void RejectsClientWithoutCert(SSLServer &svr) {
  14414. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14415. auto port = svr.bind_to_any_port(HOST);
  14416. ASSERT_LT(0, port);
  14417. thread t = thread([&]() { svr.listen_after_bind(); });
  14418. auto se = detail::scope_exit([&] {
  14419. svr.stop();
  14420. t.join();
  14421. ASSERT_FALSE(svr.is_running());
  14422. });
  14423. svr.wait_until_ready();
  14424. SSLClient cli(HOST, port);
  14425. cli.set_connection_timeout(30);
  14426. // Skip the server certificate check, so that the request fails because the
  14427. // client certificate is missing rather than because cert.pem is not trusted
  14428. cli.enable_server_certificate_verification(false);
  14429. auto res = cli.Get("/test");
  14430. ASSERT_FALSE(res);
  14431. // The server rejects the client during the handshake, or on TLS 1.3 right
  14432. // after it, which the client notices on its first write or read
  14433. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14434. res.error() == Error::Write || res.error() == Error::Read)
  14435. << to_string(res.error());
  14436. if (res.error() == Error::SSLConnection) {
  14437. EXPECT_NE(0UL, res.ssl_backend_error());
  14438. }
  14439. // A rejection noticed on the write keeps the TLS error the write hit
  14440. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14441. }
  14442. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14444. ASSERT_TRUE(svr.is_valid());
  14445. if (setup) { setup(svr); }
  14446. RejectsClientWithoutCert(svr);
  14447. }
  14448. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14449. // A server that requires client certificates must keep requiring them after
  14450. // setup changes it, and keep accepting a client that has one
  14451. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14452. ClientCertMissing(setup);
  14453. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14454. setup);
  14455. }
  14456. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14457. ClientCertStillRequired([](SSLServer &svr) {
  14458. ASSERT_TRUE(tls::set_verify_callback(
  14459. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14460. });
  14461. }
  14462. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14463. ClientCertStillRequired([](SSLServer &svr) {
  14464. ASSERT_TRUE(tls::set_verify_callback(
  14465. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14466. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14467. });
  14468. }
  14469. // The client verifies the server certificate during the handshake, so a
  14470. // server that fails the check never gets the client certificate, even when a
  14471. // verifier of the client's own accepts it
  14472. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14473. struct Case {
  14474. const char *trusted_ca;
  14475. const char *host;
  14476. Error error;
  14477. };
  14478. // cert2.pem names localhost: the first client does not trust it, and the
  14479. // second trusts it but asks for another name
  14480. for (const auto &c :
  14481. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14482. Case{SERVER_CERT2_FILE, "example.com",
  14483. Error::SSLServerHostnameVerification}}) {
  14484. for (auto with_verifier : {false, true}) {
  14485. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14486. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14487. CLIENT_CA_CERT_FILE);
  14488. ASSERT_TRUE(svr.is_valid());
  14489. std::atomic<bool> got_client_cert{false};
  14490. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14491. [&](const tls::VerifyContext &) {
  14492. got_client_cert = true;
  14493. return true;
  14494. }));
  14495. auto port = svr.bind_to_any_port("127.0.0.1");
  14496. ASSERT_LT(0, port);
  14497. thread t = thread([&] { svr.listen_after_bind(); });
  14498. svr.wait_until_ready();
  14499. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14500. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14501. cli.set_ca_cert_path(c.trusted_ca);
  14502. if (with_verifier) {
  14503. cli.set_server_certificate_verifier(
  14504. [](const tls::VerifyContext &) { return true; });
  14505. }
  14506. auto res = cli.Get("/");
  14507. EXPECT_FALSE(res);
  14508. EXPECT_EQ(c.error, res.error());
  14509. svr.stop();
  14510. t.join();
  14511. EXPECT_FALSE(got_client_cert);
  14512. }
  14513. }
  14514. }
  14515. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14516. std::string cert_pem, key_pem, ca_pem;
  14517. read_file(SERVER_CERT_FILE, cert_pem);
  14518. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14519. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14520. ASSERT_TRUE(
  14521. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14522. }
  14523. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14524. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14525. ASSERT_TRUE(svr.is_valid());
  14526. UpdateCertsPemWithClientCA(svr);
  14527. RejectsClientWithoutCert(svr);
  14528. }
  14529. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14530. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14531. }
  14532. // A TLS error from one request must not show up in a later request's Result
  14533. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14534. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14535. ASSERT_TRUE(svr.is_valid());
  14536. svr.Get("/test", [](const Request &, Response &res) {
  14537. res.set_content("test", "text/plain");
  14538. });
  14539. auto port = svr.bind_to_any_port(HOST);
  14540. ASSERT_LT(0, port);
  14541. thread t = thread([&]() { svr.listen_after_bind(); });
  14542. auto se = detail::scope_exit([&] {
  14543. svr.stop();
  14544. t.join();
  14545. ASSERT_FALSE(svr.is_running());
  14546. });
  14547. svr.wait_until_ready();
  14548. SSLClient cli(HOST, port);
  14549. cli.set_connection_timeout(30);
  14550. cli.enable_server_hostname_verification(false);
  14551. // cert.pem is not trusted, so the handshake fails
  14552. ASSERT_FALSE(cli.Get("/test"));
  14553. cli.enable_server_certificate_verification(false);
  14554. auto res = cli.Get("/test");
  14555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14556. EXPECT_EQ(0, res.ssl_error());
  14557. EXPECT_EQ(0UL, res.ssl_backend_error());
  14558. }
  14559. // PEM memory-based constructor tests (works with all TLS backends).
  14560. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14561. // terminator after it.
  14562. void PemMemoryClientCertPresent(
  14563. const std::string &client_cert_file,
  14564. const std::string &client_private_key_file,
  14565. const std::string &client_encrypted_private_key_pass = std::string(),
  14566. bool exact_size = false) {
  14567. // Read PEM files into memory
  14568. std::string server_cert_pem, server_key_pem;
  14569. std::string client_ca_pem;
  14570. std::string client_cert_pem, client_key_pem;
  14571. read_file(SERVER_CERT_FILE, server_cert_pem);
  14572. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14573. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14574. read_file(client_cert_file, client_cert_pem);
  14575. read_file(client_private_key_file, client_key_pem);
  14576. std::list<std::vector<char>> exact_copies;
  14577. auto data = [&](const std::string &pem) -> const char * {
  14578. if (!exact_size) { return pem.c_str(); }
  14579. exact_copies.emplace_back(pem.begin(), pem.end());
  14580. return exact_copies.back().data();
  14581. };
  14582. // Create server with PEM memory
  14583. SSLServer::PemMemory server_pem = {
  14584. data(server_cert_pem),
  14585. server_cert_pem.size(),
  14586. data(server_key_pem),
  14587. server_key_pem.size(),
  14588. data(client_ca_pem),
  14589. client_ca_pem.size(),
  14590. nullptr // no password for server key
  14591. };
  14592. SSLServer svr(server_pem);
  14593. ASSERT_TRUE(svr.is_valid());
  14594. svr.Get("/test", [&](const Request &req, Response &res) {
  14595. res.set_content("test", "text/plain");
  14596. auto cert = req.peer_cert();
  14597. ASSERT_TRUE(static_cast<bool>(cert));
  14598. EXPECT_EQ("Common Name", cert.subject_cn());
  14599. });
  14600. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14601. auto se = detail::scope_exit([&] {
  14602. svr.stop();
  14603. t.join();
  14604. ASSERT_FALSE(svr.is_running());
  14605. });
  14606. svr.wait_until_ready();
  14607. // Create client with PEM memory
  14608. const char *password = client_encrypted_private_key_pass.empty()
  14609. ? nullptr
  14610. : client_encrypted_private_key_pass.c_str();
  14611. SSLClient::PemMemory client_pem = {
  14612. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14613. client_key_pem.size(), password};
  14614. SSLClient cli(HOST, PORT, client_pem);
  14615. cli.enable_server_certificate_verification(false);
  14616. cli.set_connection_timeout(30);
  14617. auto res = cli.Get("/test");
  14618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14619. ASSERT_EQ(StatusCode::OK_200, res->status);
  14620. }
  14621. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14622. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14623. }
  14624. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14625. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14626. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14627. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14628. }
  14629. // A server built from PEM memory with a client CA requires client certificates,
  14630. // also when the CA is a NUL-terminated string passed with a length of 0
  14631. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14632. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14633. read_file(SERVER_CERT_FILE, server_cert_pem);
  14634. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14635. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14636. SSLServer::PemMemory server_pem = {
  14637. server_cert_pem.c_str(),
  14638. server_cert_pem.size(),
  14639. server_key_pem.c_str(),
  14640. server_key_pem.size(),
  14641. client_ca_pem.c_str(),
  14642. client_ca_pem.size(),
  14643. nullptr // no password for server key
  14644. };
  14645. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14646. SCOPED_TRACE(client_ca_pem_len);
  14647. server_pem.client_ca_pem_len = client_ca_pem_len;
  14648. SSLServer svr(server_pem);
  14649. ASSERT_TRUE(svr.is_valid());
  14650. RejectsClientWithoutCert(svr);
  14651. }
  14652. // An empty CA fails to load instead of turning the check off
  14653. server_pem.client_ca_pem = "";
  14654. server_pem.client_ca_pem_len = 0;
  14655. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14656. }
  14657. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14658. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14659. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14660. true);
  14661. }
  14662. // A length shorter than the PEM cuts it short, so it no longer loads
  14663. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14664. std::string cert, key;
  14665. read_file(SERVER_CERT_FILE, cert);
  14666. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14667. for (auto cut_cert : {true, false}) {
  14668. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14669. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14670. SSLServer::PemMemory server_pem = {
  14671. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14672. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14673. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14674. key_len, nullptr};
  14675. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14676. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14677. key.c_str(), key_len, nullptr};
  14678. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14679. }
  14680. }
  14681. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14682. class NoListenSSLServer : public SSLServer {
  14683. public:
  14684. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14685. const char *client_ca_cert_file_path,
  14686. const char *client_ca_cert_dir_path = nullptr)
  14687. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14688. client_ca_cert_dir_path),
  14689. stop_(false) {}
  14690. std::atomic_bool stop_;
  14691. private:
  14692. bool process_and_close_socket(socket_t /*sock*/) override {
  14693. // Don't create SSL context
  14694. while (!stop_.load()) {
  14695. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14696. }
  14697. return true;
  14698. }
  14699. };
  14700. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14701. CLIENT_CA_CERT_FILE);
  14702. ASSERT_TRUE(svr.is_valid());
  14703. svr.Get("/test", [&](const Request &, Response &res) {
  14704. res.set_content("test", "text/plain");
  14705. });
  14706. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14707. auto se = detail::scope_exit([&] {
  14708. svr.stop_ = true;
  14709. svr.stop();
  14710. t.join();
  14711. ASSERT_FALSE(svr.is_running());
  14712. });
  14713. svr.wait_until_ready();
  14714. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14715. cli.enable_server_certificate_verification(false);
  14716. cli.set_connection_timeout(1);
  14717. auto res = cli.Get("/test");
  14718. ASSERT_TRUE(!res);
  14719. EXPECT_EQ(Error::SSLConnection, res.error());
  14720. // Timeout results in WantRead error code (maps to backend-specific value)
  14721. EXPECT_NE(0, res.ssl_error());
  14722. }
  14723. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14724. // Test SSLServer with client certificate verification using the standard
  14725. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14726. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14727. CLIENT_CA_CERT_DIR);
  14728. ASSERT_TRUE(svr.is_valid());
  14729. svr.Get("/test", [&](const Request &req, Response &res) {
  14730. res.set_content("test", "text/plain");
  14731. auto cert = req.peer_cert();
  14732. ASSERT_TRUE(static_cast<bool>(cert));
  14733. auto common_name = cert.subject_cn();
  14734. EXPECT_EQ("Common Name", common_name);
  14735. });
  14736. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14737. auto se = detail::scope_exit([&] {
  14738. svr.stop();
  14739. t.join();
  14740. ASSERT_FALSE(svr.is_running());
  14741. });
  14742. svr.wait_until_ready();
  14743. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14744. cli.enable_server_certificate_verification(false);
  14745. cli.set_connection_timeout(30);
  14746. auto res = cli.Get("/test");
  14747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14748. ASSERT_EQ(StatusCode::OK_200, res->status);
  14749. }
  14750. // Test verify_hostname on every backend: a host is named by a SAN only
  14751. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14752. using namespace httplib::tls;
  14753. // We need a running server to test against
  14754. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14755. ASSERT_TRUE(svr.is_valid());
  14756. svr.Get("/test", [](const Request &, Response &res) {
  14757. res.set_content("ok", "text/plain");
  14758. });
  14759. thread t([&]() { svr.listen(HOST, PORT); });
  14760. auto se = detail::scope_exit([&] {
  14761. svr.stop();
  14762. t.join();
  14763. });
  14764. svr.wait_until_ready();
  14765. bool verify_callback_called = false;
  14766. bool verify_result_wrong = false;
  14767. SSLClient cli(HOST, PORT);
  14768. cli.enable_server_certificate_verification(true);
  14769. cli.set_ca_cert_path(CA_CERT_FILE);
  14770. cli.set_connection_timeout(5);
  14771. // Note: Test certificate has CN="Common Name", not "localhost"
  14772. bool verify_result_cn = false;
  14773. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14774. verify_callback_called = true;
  14775. if (!ctx.cert) return false;
  14776. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14777. verify_result_cn = ctx.check_hostname("Common Name");
  14778. // Test 2: wrong hostname should not match
  14779. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14780. return true; // Accept for the purpose of this test
  14781. });
  14782. auto res = cli.Get("/test");
  14783. // The request may succeed or fail depending on cert configuration
  14784. // but the callback should have been called
  14785. ASSERT_TRUE(verify_callback_called)
  14786. << "Verify callback should have been called";
  14787. EXPECT_FALSE(verify_result_cn)
  14788. << "verify_hostname must not match the certificate CN (no SAN)";
  14789. // Wrong hostname should not match
  14790. EXPECT_FALSE(verify_result_wrong)
  14791. << "verify_hostname should not match 'wronghost.example.com'";
  14792. }
  14793. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14794. // backend verifies it.
  14795. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14796. // Certificate CN is "localhost" and it carries no SAN.
  14797. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14798. ASSERT_TRUE(svr.is_valid());
  14799. svr.Get("/test", [](const Request &, Response &res) {
  14800. res.set_content("ok", "text/plain");
  14801. });
  14802. auto port = svr.bind_to_any_port(HOST);
  14803. thread t([&]() { svr.listen_after_bind(); });
  14804. auto se = detail::scope_exit([&] {
  14805. svr.stop();
  14806. t.join();
  14807. });
  14808. svr.wait_until_ready();
  14809. SSLClient cli("localhost", port);
  14810. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14811. cli.enable_server_certificate_verification(true);
  14812. cli.set_connection_timeout(5);
  14813. auto res = cli.Get("/test");
  14814. ASSERT_FALSE(res);
  14815. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14816. // The same certificate is accepted once host name verification is off, so the
  14817. // failure above is the host name and not the chain.
  14818. cli.enable_server_hostname_verification(false);
  14819. res = cli.Get("/test");
  14820. ASSERT_TRUE(res) << to_string(res.error());
  14821. EXPECT_EQ(StatusCode::OK_200, res->status);
  14822. }
  14823. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14824. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14825. // X509_check_ip behavior and must hold for every backend.
  14826. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14827. using namespace httplib::tls;
  14828. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14829. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14830. ASSERT_TRUE(svr.is_valid());
  14831. svr.Get("/test", [](const Request &, Response &res) {
  14832. res.set_content("ok", "text/plain");
  14833. });
  14834. thread t([&]() { svr.listen(HOST, PORT); });
  14835. auto se = detail::scope_exit([&] {
  14836. svr.stop();
  14837. t.join();
  14838. });
  14839. svr.wait_until_ready();
  14840. bool verify_callback_called = false;
  14841. bool ip_matched_via_cn = true;
  14842. SSLClient cli(HOST, PORT);
  14843. cli.enable_server_certificate_verification(true);
  14844. cli.set_ca_cert_path(CA_CERT_FILE);
  14845. cli.set_connection_timeout(5);
  14846. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14847. verify_callback_called = true;
  14848. if (!ctx.cert) return false;
  14849. // The IP appears only in the CN, so it must NOT be accepted.
  14850. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14851. return true; // Accept for the purpose of this test
  14852. });
  14853. cli.Get("/test");
  14854. ASSERT_TRUE(verify_callback_called)
  14855. << "Verify callback should have been called";
  14856. EXPECT_FALSE(ip_matched_via_cn)
  14857. << "An IP host must not be authenticated via the certificate CN";
  14858. }
  14859. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14860. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14861. using namespace httplib::tls;
  14862. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14863. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14864. ASSERT_TRUE(svr.is_valid());
  14865. svr.Get("/test", [](const Request &, Response &res) {
  14866. res.set_content("ok", "text/plain");
  14867. });
  14868. thread t([&]() { svr.listen(HOST, PORT); });
  14869. auto se = detail::scope_exit([&] {
  14870. svr.stop();
  14871. t.join();
  14872. });
  14873. svr.wait_until_ready();
  14874. bool verify_callback_called = false;
  14875. bool san_matched = false;
  14876. bool wrong_ipv6_matched = true;
  14877. bool cn_ipv6_matched = true;
  14878. SSLClient cli(HOST, PORT);
  14879. cli.enable_server_certificate_verification(true);
  14880. cli.set_ca_cert_path(CA_CERT_FILE);
  14881. cli.set_connection_timeout(5);
  14882. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14883. verify_callback_called = true;
  14884. if (!ctx.cert) return false;
  14885. // Matches the IPv6 iPAddress SAN.
  14886. san_matched = ctx.check_hostname("2001:db8::1");
  14887. // A different IPv6 address must not match.
  14888. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14889. // "::1" lives only in the CN, so it must not be accepted.
  14890. cn_ipv6_matched = ctx.check_hostname("::1");
  14891. return true; // Accept for the purpose of this test
  14892. });
  14893. cli.Get("/test");
  14894. ASSERT_TRUE(verify_callback_called)
  14895. << "Verify callback should have been called";
  14896. EXPECT_TRUE(san_matched)
  14897. << "verify_hostname should match an IPv6 iPAddress SAN";
  14898. EXPECT_FALSE(wrong_ipv6_matched)
  14899. << "verify_hostname should not match a non-matching IPv6 address";
  14900. EXPECT_FALSE(cn_ipv6_matched)
  14901. << "An IPv6 host must not be authenticated via the certificate CN";
  14902. }
  14903. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14904. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14905. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14906. using namespace httplib::tls;
  14907. // SANs: DNS:a.zz, IP:42.46.122.122
  14908. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14909. ASSERT_TRUE(svr.is_valid());
  14910. svr.Get("/test", [](const Request &, Response &res) {
  14911. res.set_content("ok", "text/plain");
  14912. });
  14913. auto port = svr.bind_to_any_port(HOST);
  14914. thread t([&]() { svr.listen_after_bind(); });
  14915. auto se = detail::scope_exit([&] {
  14916. svr.stop();
  14917. t.join();
  14918. });
  14919. svr.wait_until_ready();
  14920. bool verify_callback_called = false;
  14921. bool dns_san_matched = false;
  14922. bool ip_san_matched = false;
  14923. bool ip_matched_via_dns_san = true;
  14924. bool dns_matched_via_ip_san = true;
  14925. bool cn_matched_next_to_dns_san = true;
  14926. SSLClient cli(HOST, port);
  14927. cli.enable_server_certificate_verification(true);
  14928. cli.set_ca_cert_path(CA_CERT_FILE);
  14929. cli.set_connection_timeout(5);
  14930. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14931. verify_callback_called = true;
  14932. if (!ctx.cert) return false;
  14933. dns_san_matched = ctx.check_hostname("a.zz");
  14934. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14935. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14936. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14937. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14938. return true; // Accept for the purpose of this test
  14939. });
  14940. cli.Get("/test");
  14941. ASSERT_TRUE(verify_callback_called)
  14942. << "Verify callback should have been called";
  14943. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14944. EXPECT_TRUE(ip_san_matched)
  14945. << "verify_hostname should match an iPAddress SAN";
  14946. EXPECT_FALSE(ip_matched_via_dns_san)
  14947. << "An IP host must not be authenticated via a dNSName SAN";
  14948. EXPECT_FALSE(dns_matched_via_ip_san)
  14949. << "A DNS host must not be authenticated via an iPAddress SAN";
  14950. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14951. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14952. }
  14953. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14954. // "www.*.example.test" names one host and not every host under example.test.
  14955. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14956. using namespace httplib::tls;
  14957. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14958. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14959. ASSERT_TRUE(svr.is_valid());
  14960. svr.Get("/test", [](const Request &, Response &res) {
  14961. res.set_content("ok", "text/plain");
  14962. });
  14963. auto port = svr.bind_to_any_port(HOST);
  14964. thread t([&]() { svr.listen_after_bind(); });
  14965. auto se = detail::scope_exit([&] {
  14966. svr.stop();
  14967. t.join();
  14968. });
  14969. svr.wait_until_ready();
  14970. bool verify_callback_called = false;
  14971. bool leftmost_wildcard_matched = false;
  14972. bool wildcard_spanned_labels = true;
  14973. bool inner_wildcard_matched = true;
  14974. SSLClient cli(HOST, port);
  14975. cli.enable_server_certificate_verification(true);
  14976. cli.set_ca_cert_path(CA_CERT_FILE);
  14977. cli.set_connection_timeout(5);
  14978. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14979. verify_callback_called = true;
  14980. if (!ctx.cert) return false;
  14981. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14982. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14983. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14984. return true; // Accept for the purpose of this test
  14985. });
  14986. cli.Get("/test");
  14987. ASSERT_TRUE(verify_callback_called)
  14988. << "Verify callback should have been called";
  14989. EXPECT_TRUE(leftmost_wildcard_matched)
  14990. << "A leftmost wildcard should match a single label";
  14991. EXPECT_FALSE(wildcard_spanned_labels)
  14992. << "A wildcard label must not match more than one label";
  14993. EXPECT_FALSE(inner_wildcard_matched)
  14994. << "A wildcard outside the leftmost label must not be honoured";
  14995. }
  14996. // sans() must report each SAN entry under its own type.
  14997. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14998. using namespace httplib::tls;
  14999. // SANs: DNS:a.zz, IP:42.46.122.122
  15000. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15001. ASSERT_TRUE(svr.is_valid());
  15002. svr.Get("/test", [](const Request &, Response &res) {
  15003. res.set_content("ok", "text/plain");
  15004. });
  15005. auto port = svr.bind_to_any_port(HOST);
  15006. thread t([&]() { svr.listen_after_bind(); });
  15007. auto se = detail::scope_exit([&] {
  15008. svr.stop();
  15009. t.join();
  15010. });
  15011. svr.wait_until_ready();
  15012. bool verify_callback_called = false;
  15013. std::vector<SanEntry> sans;
  15014. SSLClient cli(HOST, port);
  15015. cli.enable_server_certificate_verification(true);
  15016. cli.set_ca_cert_path(CA_CERT_FILE);
  15017. cli.set_connection_timeout(5);
  15018. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15019. verify_callback_called = true;
  15020. if (!ctx.cert) return false;
  15021. sans = ctx.sans();
  15022. return true; // Accept for the purpose of this test
  15023. });
  15024. cli.Get("/test");
  15025. ASSERT_TRUE(verify_callback_called)
  15026. << "Verify callback should have been called";
  15027. auto has_san = [&](SanType type, const std::string &value) {
  15028. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15029. return san.type == type && san.value == value;
  15030. });
  15031. };
  15032. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15033. << "sans() should report the dNSName SAN";
  15034. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15035. << "sans() should report the iPAddress SAN";
  15036. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15037. << "sans() must not report the dNSName SAN as an address";
  15038. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15039. << "sans() must not report the iPAddress SAN as a DNS name";
  15040. }
  15041. #endif
  15042. // mbedTLS-specific callback constructor test
  15043. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15044. #ifdef CPPHTTPLIB_SSL_ENABLED
  15045. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15047. ASSERT_TRUE(svr.is_valid());
  15048. // Set up a handler to verify client certificate is present
  15049. bool client_cert_verified = false;
  15050. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15051. // Verify that client certificate was provided
  15052. client_cert_verified = true;
  15053. res.set_content("success", "text/plain");
  15054. });
  15055. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15056. auto se = detail::scope_exit([&] {
  15057. svr.stop();
  15058. t.join();
  15059. ASSERT_FALSE(svr.is_running());
  15060. });
  15061. svr.wait_until_ready();
  15062. // Client with certificate
  15063. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15064. cli.enable_server_certificate_verification(false);
  15065. cli.set_connection_timeout(30);
  15066. auto res = cli.Get("/test");
  15067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15068. ASSERT_EQ(StatusCode::OK_200, res->status);
  15069. ASSERT_TRUE(client_cert_verified);
  15070. EXPECT_EQ("success", res->body);
  15071. }
  15072. #endif
  15073. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15074. // backends
  15075. #ifdef CPPHTTPLIB_SSL_ENABLED
  15076. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15077. using namespace httplib::tls;
  15078. // Test that when client CA cert file is provided,
  15079. // the server properly requests and validates client certificates
  15080. // Create a server with client authentication
  15081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15082. ASSERT_TRUE(svr.is_valid());
  15083. bool handler_called = false;
  15084. svr.Get("/test", [&](const Request &req, Response &res) {
  15085. handler_called = true;
  15086. // Verify that a client certificate was provided
  15087. auto cert = req.peer_cert();
  15088. ASSERT_TRUE(static_cast<bool>(cert));
  15089. // Get the issuer name
  15090. std::string issuer_str = cert.issuer_name();
  15091. ASSERT_FALSE(issuer_str.empty());
  15092. // The client certificate should be issued by our test CA
  15093. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15094. res.set_content("authenticated", "text/plain");
  15095. });
  15096. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15097. auto se = detail::scope_exit([&] {
  15098. svr.stop();
  15099. t.join();
  15100. ASSERT_FALSE(svr.is_running());
  15101. });
  15102. svr.wait_until_ready();
  15103. // Connect with a client certificate issued by the CA
  15104. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15105. cli.enable_server_certificate_verification(false);
  15106. cli.set_connection_timeout(30);
  15107. auto res = cli.Get("/test");
  15108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15109. ASSERT_EQ(StatusCode::OK_200, res->status);
  15110. ASSERT_TRUE(handler_called);
  15111. EXPECT_EQ("authenticated", res->body);
  15112. }
  15113. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15114. using namespace httplib::tls;
  15115. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15116. ASSERT_TRUE(svr.is_valid());
  15117. svr.Get("/test", [](const Request &, Response &res) {
  15118. res.set_content("ok", "text/plain");
  15119. });
  15120. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15121. auto se = detail::scope_exit([&] {
  15122. svr.stop();
  15123. t.join();
  15124. });
  15125. svr.wait_until_ready();
  15126. SSLClient cli(HOST, PORT);
  15127. cli.enable_server_certificate_verification(false);
  15128. cli.set_connection_timeout(30);
  15129. bool cert_checked = false;
  15130. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15131. if (ctx.cert) {
  15132. auto sans = ctx.sans();
  15133. // Test certificate may or may not have SANs - just verify the API
  15134. // works If SANs exist, verify the types are valid
  15135. for (const auto &san : sans) {
  15136. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15137. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15138. san.type == SanType::OTHER);
  15139. EXPECT_FALSE(san.value.empty());
  15140. }
  15141. cert_checked = true;
  15142. }
  15143. return true;
  15144. });
  15145. auto res = cli.Get("/test");
  15146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15147. EXPECT_TRUE(cert_checked);
  15148. }
  15149. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15150. using namespace httplib::tls;
  15151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15152. ASSERT_TRUE(svr.is_valid());
  15153. svr.Get("/test", [](const Request &, Response &res) {
  15154. res.set_content("ok", "text/plain");
  15155. });
  15156. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15157. auto se = detail::scope_exit([&] {
  15158. svr.stop();
  15159. t.join();
  15160. });
  15161. svr.wait_until_ready();
  15162. SSLClient cli(HOST, PORT);
  15163. cli.enable_server_certificate_verification(false);
  15164. cli.set_connection_timeout(30);
  15165. bool validity_checked = false;
  15166. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15167. if (ctx.cert) {
  15168. time_t not_before = 0, not_after = 0;
  15169. bool result = ctx.validity(not_before, not_after);
  15170. EXPECT_TRUE(result);
  15171. // Verify that not_before < now < not_after for a valid cert
  15172. time_t now = time(nullptr);
  15173. EXPECT_LT(not_before, now);
  15174. EXPECT_GT(not_after, now);
  15175. validity_checked = true;
  15176. }
  15177. return true;
  15178. });
  15179. auto res = cli.Get("/test");
  15180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15181. EXPECT_TRUE(validity_checked);
  15182. }
  15183. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15184. using namespace httplib::tls;
  15185. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15186. ASSERT_TRUE(svr.is_valid());
  15187. svr.Get("/test", [](const Request &, Response &res) {
  15188. res.set_content("ok", "text/plain");
  15189. });
  15190. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15191. auto se = detail::scope_exit([&] {
  15192. svr.stop();
  15193. t.join();
  15194. });
  15195. svr.wait_until_ready();
  15196. SSLClient cli(HOST, PORT);
  15197. cli.enable_server_certificate_verification(false);
  15198. cli.set_connection_timeout(30);
  15199. bool serial_checked = false;
  15200. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15201. if (ctx.cert) {
  15202. std::string serial = ctx.serial();
  15203. EXPECT_FALSE(serial.empty());
  15204. // Serial should be a hex string
  15205. for (char c : serial) {
  15206. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15207. (c >= 'a' && c <= 'f'));
  15208. }
  15209. serial_checked = true;
  15210. }
  15211. return true;
  15212. });
  15213. auto res = cli.Get("/test");
  15214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15215. EXPECT_TRUE(serial_checked);
  15216. }
  15217. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15218. // Test 1: Valid CA file - no error should be recorded
  15219. {
  15220. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15221. CLIENT_CA_CERT_FILE);
  15222. ASSERT_TRUE(svr.is_valid());
  15223. // With valid setup, last_ssl_error should be 0
  15224. EXPECT_EQ(0, svr.ssl_last_error());
  15225. }
  15226. // Test 2: Invalid CA file content
  15227. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15228. {
  15229. // Create a temporary file with completely invalid content
  15230. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15231. {
  15232. std::ofstream ofs(temp_invalid_ca);
  15233. ofs << "This is not a certificate file at all\n";
  15234. ofs << "Just plain text content\n";
  15235. }
  15236. // Create server with invalid CA file
  15237. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15238. // Clean up temporary file
  15239. std::remove(temp_invalid_ca);
  15240. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15241. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15242. // Note: SSL_CTX_load_verify_locations typically fails first,
  15243. // but our error handling code path is still exercised
  15244. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15245. }
  15246. }
  15247. TEST(VerifyCallbackTest, VerifyContextFields) {
  15248. using namespace httplib::tls;
  15249. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15250. ASSERT_TRUE(svr.is_valid());
  15251. svr.Get("/test", [](const Request &, Response &res) {
  15252. res.set_content("ok", "text/plain");
  15253. });
  15254. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15255. auto se = detail::scope_exit([&] {
  15256. svr.stop();
  15257. t.join();
  15258. });
  15259. svr.wait_until_ready();
  15260. SSLClient cli(HOST, PORT);
  15261. cli.enable_server_certificate_verification(false);
  15262. cli.set_connection_timeout(30);
  15263. int callback_count = 0;
  15264. bool saw_leaf_cert = false;
  15265. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15266. if (ctx.cert) {
  15267. callback_count++;
  15268. // We should see at least one certificate (the leaf)
  15269. std::string cn = ctx.subject_cn();
  15270. if (!cn.empty()) { saw_leaf_cert = true; }
  15271. // Verify context fields are populated
  15272. EXPECT_NE(ctx.session, nullptr);
  15273. EXPECT_GE(ctx.depth, 0);
  15274. }
  15275. return true;
  15276. });
  15277. auto res = cli.Get("/test");
  15278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15279. EXPECT_GT(callback_count, 0);
  15280. EXPECT_TRUE(saw_leaf_cert);
  15281. }
  15282. // A verifier that accepts runs alongside the built-in verification, and is the
  15283. // only check once that is turned off.
  15284. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15285. using namespace httplib::tls;
  15286. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15287. ASSERT_TRUE(svr.is_valid());
  15288. svr.Get("/test", [](const Request &, Response &res) {
  15289. res.set_content("ok", "text/plain");
  15290. });
  15291. auto port = svr.bind_to_any_port(HOST);
  15292. thread t([&]() { svr.listen_after_bind(); });
  15293. auto se = detail::scope_exit([&] {
  15294. svr.stop();
  15295. t.join();
  15296. });
  15297. svr.wait_until_ready();
  15298. SSLClient cli(HOST, port);
  15299. cli.enable_server_hostname_verification(false);
  15300. auto calls = 0;
  15301. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15302. calls++;
  15303. return true;
  15304. });
  15305. // cert.pem is not trusted
  15306. auto res = cli.Get("/test");
  15307. ASSERT_FALSE(res);
  15308. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15309. EXPECT_GT(calls, 0);
  15310. cli.enable_server_certificate_verification(false);
  15311. res = cli.Get("/test");
  15312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15313. EXPECT_EQ("ok", res->body);
  15314. }
  15315. // A verifier belongs to the client that set it, not to the thread that set it.
  15316. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15317. using namespace httplib::tls;
  15318. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15319. ASSERT_TRUE(svr.is_valid());
  15320. svr.Get("/test", [](const Request &, Response &res) {
  15321. res.set_content("ok", "text/plain");
  15322. });
  15323. auto port = svr.bind_to_any_port(HOST);
  15324. thread t([&]() { svr.listen_after_bind(); });
  15325. auto se = detail::scope_exit([&] {
  15326. svr.stop();
  15327. t.join();
  15328. });
  15329. svr.wait_until_ready();
  15330. auto rejecting_calls = 0;
  15331. SSLClient rejecting(HOST, port);
  15332. rejecting.enable_server_certificate_verification(false);
  15333. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15334. rejecting_calls++;
  15335. return false;
  15336. });
  15337. auto accepting_calls = 0;
  15338. SSLClient accepting(HOST, port);
  15339. accepting.enable_server_certificate_verification(false);
  15340. // Set on another thread than the requests below.
  15341. thread([&]() {
  15342. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15343. accepting_calls++;
  15344. return true;
  15345. });
  15346. }).join();
  15347. // Requested on another thread than the verifier was set on.
  15348. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15349. EXPECT_GT(rejecting_calls, 0);
  15350. auto res = accepting.Get("/test");
  15351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15352. EXPECT_GT(accepting_calls, 0);
  15353. }
  15354. // A verifier replaced while a handshake runs it lives until it returns.
  15355. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15356. using namespace httplib::tls;
  15357. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15358. ASSERT_TRUE(svr.is_valid());
  15359. svr.Get("/test", [](const Request &, Response &res) {
  15360. res.set_content("ok", "text/plain");
  15361. });
  15362. auto port = svr.bind_to_any_port(HOST);
  15363. thread t([&]() { svr.listen_after_bind(); });
  15364. auto se = detail::scope_exit([&] {
  15365. svr.stop();
  15366. t.join();
  15367. });
  15368. svr.wait_until_ready();
  15369. SSLClient cli(HOST, port);
  15370. cli.enable_server_certificate_verification(false);
  15371. std::promise<void> entered;
  15372. std::promise<void> replaced;
  15373. auto replaced_future = replaced.get_future();
  15374. auto first_call = true;
  15375. // Long enough to live on the heap
  15376. std::string expected(64, 'v');
  15377. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15378. if (first_call) {
  15379. first_call = false;
  15380. entered.set_value();
  15381. replaced_future.wait();
  15382. }
  15383. return expected == std::string(64, 'v');
  15384. });
  15385. thread request([&]() {
  15386. auto res = cli.Get("/test");
  15387. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15388. });
  15389. entered.get_future().wait();
  15390. cli.set_server_certificate_verifier(
  15391. [](const VerifyContext &) { return true; });
  15392. replaced.set_value();
  15393. request.join();
  15394. }
  15395. // VerifyContext::session is the same handle the other tls:: functions take.
  15396. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15397. using namespace httplib::tls;
  15398. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15399. ASSERT_TRUE(svr.is_valid());
  15400. svr.Get("/test", [](const Request &, Response &res) {
  15401. res.set_content("ok", "text/plain");
  15402. });
  15403. auto port = svr.bind_to_any_port(HOST);
  15404. thread t([&]() { svr.listen_after_bind(); });
  15405. auto se = detail::scope_exit([&] {
  15406. svr.stop();
  15407. t.join();
  15408. });
  15409. svr.wait_until_ready();
  15410. SSLClient cli(HOST, port);
  15411. cli.enable_server_certificate_verification(false);
  15412. session_t verifier_session = nullptr;
  15413. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15414. verifier_session = ctx.session;
  15415. return true;
  15416. });
  15417. session_t session_verifier_session = nullptr;
  15418. cli.set_session_verifier([&](session_t session) {
  15419. session_verifier_session = session;
  15420. return SSLVerifierResponse::NoDecisionMade;
  15421. });
  15422. auto res = cli.Get("/test");
  15423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15424. EXPECT_NE(nullptr, verifier_session);
  15425. EXPECT_EQ(session_verifier_session, verifier_session);
  15426. }
  15427. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15428. using httplib::tls::TlsError;
  15429. // Test that verify_error_to_string returns empty for success
  15430. std::string success_str = TlsError::verify_error_to_string(0);
  15431. EXPECT_TRUE(success_str.empty());
  15432. // Test that verify_error_to_string returns non-empty for error codes
  15433. // Using a common error code (certificate expired)
  15434. std::string error_str =
  15435. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15436. EXPECT_FALSE(error_str.empty());
  15437. }
  15438. TEST(SessionVerifierTest, CertificateAccepted) {
  15439. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15440. ASSERT_TRUE(svr.is_valid());
  15441. svr.Get("/test", [](const Request &, Response &res) {
  15442. res.set_content("ok", "text/plain");
  15443. });
  15444. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15445. auto se = detail::scope_exit([&] {
  15446. svr.stop();
  15447. t.join();
  15448. });
  15449. svr.wait_until_ready();
  15450. SSLClient cli(HOST, PORT);
  15451. cli.enable_server_certificate_verification(false);
  15452. cli.set_connection_timeout(30);
  15453. bool callback_called = false;
  15454. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15455. EXPECT_NE(session, nullptr);
  15456. callback_called = true;
  15457. return SSLVerifierResponse::CertificateAccepted;
  15458. });
  15459. auto res = cli.Get("/test");
  15460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15461. EXPECT_EQ(200, res->status);
  15462. EXPECT_TRUE(callback_called);
  15463. }
  15464. TEST(SessionVerifierTest, CertificateRejected) {
  15465. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15466. ASSERT_TRUE(svr.is_valid());
  15467. svr.Get("/test", [](const Request &, Response &res) {
  15468. res.set_content("ok", "text/plain");
  15469. });
  15470. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15471. auto se = detail::scope_exit([&] {
  15472. svr.stop();
  15473. t.join();
  15474. });
  15475. svr.wait_until_ready();
  15476. SSLClient cli(HOST, PORT);
  15477. cli.enable_server_certificate_verification(false);
  15478. cli.set_connection_timeout(30);
  15479. bool callback_called = false;
  15480. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15481. EXPECT_NE(session, nullptr);
  15482. callback_called = true;
  15483. return SSLVerifierResponse::CertificateRejected;
  15484. });
  15485. auto res = cli.Get("/test");
  15486. EXPECT_FALSE(res);
  15487. EXPECT_TRUE(callback_called);
  15488. }
  15489. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15491. ASSERT_TRUE(svr.is_valid());
  15492. svr.Get("/test", [](const Request &, Response &res) {
  15493. res.set_content("ok", "text/plain");
  15494. });
  15495. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15496. auto se = detail::scope_exit([&] {
  15497. svr.stop();
  15498. t.join();
  15499. });
  15500. svr.wait_until_ready();
  15501. // NoDecisionMade with verification disabled should succeed (no default check)
  15502. SSLClient cli(HOST, PORT);
  15503. cli.enable_server_certificate_verification(false);
  15504. cli.set_connection_timeout(30);
  15505. bool callback_called = false;
  15506. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15507. EXPECT_NE(session, nullptr);
  15508. callback_called = true;
  15509. return SSLVerifierResponse::NoDecisionMade;
  15510. });
  15511. auto res = cli.Get("/test");
  15512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15513. EXPECT_EQ(200, res->status);
  15514. EXPECT_TRUE(callback_called);
  15515. }
  15516. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15517. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15518. ASSERT_TRUE(svr.is_valid());
  15519. svr.Get("/test", [](const Request &, Response &res) {
  15520. res.set_content("ok", "text/plain");
  15521. });
  15522. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15523. auto se = detail::scope_exit([&] {
  15524. svr.stop();
  15525. t.join();
  15526. });
  15527. svr.wait_until_ready();
  15528. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15529. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15530. // so we only check that the request fails, not whether the callback was
  15531. // called.
  15532. SSLClient cli(HOST, PORT);
  15533. cli.enable_server_certificate_verification(true);
  15534. cli.set_connection_timeout(30);
  15535. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15536. EXPECT_NE(session, nullptr);
  15537. return SSLVerifierResponse::NoDecisionMade;
  15538. });
  15539. auto res = cli.Get("/test");
  15540. EXPECT_FALSE(res);
  15541. }
  15542. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15543. // Test SSL server using PemMemory constructor with client CA certificates
  15544. // Read PEM files
  15545. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15546. read_file(SERVER_CERT_FILE, server_cert_pem);
  15547. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15548. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15549. // Create SSLServer with PemMemory constructor including client CA
  15550. SSLServer::PemMemory server_pem = {
  15551. server_cert_pem.c_str(),
  15552. server_cert_pem.size(),
  15553. server_key_pem.c_str(),
  15554. server_key_pem.size(),
  15555. client_ca_pem.c_str(),
  15556. client_ca_pem.size(),
  15557. nullptr // no password for server key
  15558. };
  15559. SSLServer svr(server_pem);
  15560. ASSERT_TRUE(svr.is_valid());
  15561. // No SSL error should be recorded for valid setup
  15562. EXPECT_EQ(0, svr.ssl_last_error());
  15563. // Set up server endpoints
  15564. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15565. res.set_content("ok", "text/plain");
  15566. });
  15567. // Start server in a thread
  15568. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15569. svr.wait_until_ready();
  15570. // Connect with client certificate (using constructor with paths)
  15571. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15572. cli.enable_server_certificate_verification(false);
  15573. auto res = cli.Get("/test-pem-ca");
  15574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15575. EXPECT_EQ(200, res->status);
  15576. EXPECT_EQ("ok", res->body);
  15577. svr.stop();
  15578. server_thread.join();
  15579. }
  15580. #endif
  15581. #ifdef _WIN32
  15582. TEST(CleanupTest, WSACleanup) {
  15583. int ret = WSACleanup();
  15584. ASSERT_EQ(0, ret);
  15585. }
  15586. #endif
  15587. #ifndef CPPHTTPLIB_SSL_ENABLED
  15588. TEST(NoSSLSupport, SimpleInterface) {
  15589. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15590. }
  15591. #endif
  15592. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15593. TEST(InvalidScheme, SimpleInterface) {
  15594. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15595. }
  15596. #endif
  15597. TEST(NoScheme, SimpleInterface) {
  15598. Client cli("yahoo.com:80");
  15599. ASSERT_TRUE(cli.is_valid());
  15600. }
  15601. TEST(SendAPI, SimpleInterface_Online) {
  15602. Client cli("http://yahoo.com");
  15603. Request req;
  15604. req.method = "GET";
  15605. req.path = "/";
  15606. auto res = cli.send(req);
  15607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15608. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15609. }
  15610. TEST(SendAPI, WithParamsInRequest) {
  15611. Server svr;
  15612. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15613. EXPECT_TRUE(req.has_param("test"));
  15614. EXPECT_EQ("test_value", req.get_param_value("test"));
  15615. });
  15616. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15617. auto se = detail::scope_exit([&] {
  15618. svr.stop();
  15619. t.join();
  15620. ASSERT_FALSE(svr.is_running());
  15621. });
  15622. svr.wait_until_ready();
  15623. Client cli(HOST, PORT);
  15624. {
  15625. Request req;
  15626. req.method = "GET";
  15627. req.path = "/";
  15628. req.params.emplace("test", "test_value");
  15629. auto res = cli.send(req);
  15630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15631. }
  15632. {
  15633. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15635. }
  15636. }
  15637. TEST(ClientImplMethods, GetSocketTest) {
  15638. httplib::Server svr;
  15639. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15640. res.status = StatusCode::OK_200;
  15641. });
  15642. auto port = svr.bind_to_any_port("127.0.0.1");
  15643. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15644. auto se = detail::scope_exit([&] {
  15645. svr.stop();
  15646. thread.join();
  15647. ASSERT_FALSE(svr.is_running());
  15648. });
  15649. svr.wait_until_ready();
  15650. {
  15651. httplib::Client cli("127.0.0.1", port);
  15652. cli.set_keep_alive(true);
  15653. // Use the behavior of cpp-httplib of opening the connection
  15654. // only when the first request happens. If that changes,
  15655. // this test would be obsolete.
  15656. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15657. // This also implicitly tests the server. But other tests would fail much
  15658. // earlier than this one to be considered.
  15659. auto res = cli.Get("/");
  15660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15661. EXPECT_EQ(StatusCode::OK_200, res->status);
  15662. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15663. }
  15664. }
  15665. #ifdef CPPHTTPLIB_SSL_ENABLED
  15666. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15667. Client cli("http://yahoo.com");
  15668. auto res = cli.Get("/");
  15669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15670. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15671. cli.set_follow_location(true);
  15672. res = cli.Get("/");
  15673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15674. EXPECT_EQ(StatusCode::OK_200, res->status);
  15675. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15676. }
  15677. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15678. Client cli("https://yahoo.com");
  15679. auto res = cli.Get("/");
  15680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15681. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15682. cli.set_follow_location(true);
  15683. res = cli.Get("/");
  15684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15685. EXPECT_EQ(StatusCode::OK_200, res->status);
  15686. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15687. }
  15688. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15689. Client cli("https://yahoo.com");
  15690. auto res = cli.Get("/");
  15691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15692. ASSERT_FALSE(!res);
  15693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15694. ASSERT_FALSE(res == nullptr);
  15695. ASSERT_TRUE(res != nullptr);
  15696. EXPECT_EQ(Error::Success, res.error());
  15697. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15698. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15699. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15700. cli.set_follow_location(true);
  15701. res = cli.Get("/");
  15702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15703. EXPECT_EQ(Error::Success, res.error());
  15704. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15705. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15706. EXPECT_EQ(StatusCode::OK_200, res->status);
  15707. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15708. }
  15709. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15710. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15711. Client cli("https://cdnjs.cloudflare.com");
  15712. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15713. Headers{{"Accept-Encoding", "br"}});
  15714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15715. EXPECT_EQ(StatusCode::OK_200, res->status);
  15716. EXPECT_EQ(287630U, res->body.size());
  15717. EXPECT_EQ("application/javascript; charset=utf-8",
  15718. res->get_header_value("Content-Type"));
  15719. }
  15720. #endif
  15721. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15722. #undef REDIR_HOST // Silence compiler warning
  15723. #define REDIR_HOST "https://httpbingo.org"
  15724. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15725. Client cli(REDIR_HOST);
  15726. cli.set_follow_location(true);
  15727. auto res =
  15728. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15730. EXPECT_EQ(StatusCode::OK_200, res->status);
  15731. }
  15732. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15733. Client cli(REDIR_HOST);
  15734. cli.set_follow_location(true);
  15735. Params params;
  15736. params.emplace("url", "http://example.com");
  15737. params.emplace("status_code", "302");
  15738. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15740. EXPECT_EQ(StatusCode::OK_200, res->status);
  15741. }
  15742. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15743. Client cli(REDIR_HOST);
  15744. cli.set_follow_location(true);
  15745. Params params;
  15746. params.emplace("url", "http://example.com");
  15747. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15749. EXPECT_EQ(StatusCode::OK_200, res->status);
  15750. }
  15751. TEST(HttpToHttpsRedirectTest, CertFile) {
  15752. auto ssl_port = PORT + 1;
  15753. Server svr;
  15754. ASSERT_TRUE(svr.is_valid());
  15755. svr.Get("/index", [&](const Request &, Response &res) {
  15756. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15757. "/index");
  15758. svr.stop();
  15759. });
  15760. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15761. ASSERT_TRUE(ssl_svr.is_valid());
  15762. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15763. res.set_content("test", "text/plain");
  15764. ssl_svr.stop();
  15765. });
  15766. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15767. thread t2 =
  15768. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15769. auto se = detail::scope_exit([&] {
  15770. t2.join();
  15771. t.join();
  15772. ASSERT_FALSE(svr.is_running());
  15773. });
  15774. svr.wait_until_ready();
  15775. ssl_svr.wait_until_ready();
  15776. Client cli("127.0.0.1", PORT);
  15777. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15778. cli.enable_server_certificate_verification(true);
  15779. cli.set_follow_location(true);
  15780. cli.set_connection_timeout(30);
  15781. auto res = cli.Get("/index");
  15782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15783. ASSERT_EQ(StatusCode::OK_200, res->status);
  15784. }
  15785. TEST(SSLClientRedirectTest, CertFile) {
  15786. auto ssl_port = PORT + 1;
  15787. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15788. ASSERT_TRUE(ssl_svr1.is_valid());
  15789. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15790. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15791. "/index");
  15792. ssl_svr1.stop();
  15793. });
  15794. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15795. ASSERT_TRUE(ssl_svr2.is_valid());
  15796. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15797. res.set_content("test", "text/plain");
  15798. ssl_svr2.stop();
  15799. });
  15800. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15801. thread t2 =
  15802. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15803. auto se = detail::scope_exit([&] {
  15804. t2.join();
  15805. t.join();
  15806. ASSERT_FALSE(ssl_svr1.is_running());
  15807. });
  15808. ssl_svr1.wait_until_ready();
  15809. ssl_svr2.wait_until_ready();
  15810. SSLClient cli("127.0.0.1", PORT);
  15811. std::string cert;
  15812. read_file(SERVER_CERT2_FILE, cert);
  15813. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15814. cli.enable_server_certificate_verification(true);
  15815. cli.set_follow_location(true);
  15816. cli.set_connection_timeout(30);
  15817. auto res = cli.Get("/index");
  15818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15819. ASSERT_EQ(StatusCode::OK_200, res->status);
  15820. }
  15821. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15822. // another port, so the client follows it with a new client.
  15823. static Result GetThroughTlsRedirectToDifferentPort(
  15824. const std::function<void(SSLClient &)> &setup,
  15825. const char *target_cert = SERVER_CERT2_FILE,
  15826. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15827. auto ssl_port = PORT + 1;
  15828. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15829. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15830. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15831. "/index");
  15832. });
  15833. SSLServer ssl_svr2(target_cert, target_key);
  15834. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15835. res.set_content("test", "text/plain");
  15836. });
  15837. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15838. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15839. auto se = detail::scope_exit([&] {
  15840. ssl_svr2.stop();
  15841. ssl_svr1.stop();
  15842. t2.join();
  15843. t.join();
  15844. });
  15845. ssl_svr1.wait_until_ready();
  15846. ssl_svr2.wait_until_ready();
  15847. SSLClient cli("127.0.0.1", PORT);
  15848. cli.set_follow_location(true);
  15849. cli.set_connection_timeout(30);
  15850. setup(cli);
  15851. return cli.Get("/index");
  15852. }
  15853. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15854. auto calls = 0;
  15855. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15856. cli.enable_server_certificate_verification(false);
  15857. // Accept the first server only.
  15858. cli.set_session_verifier([&](tls::session_t) {
  15859. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15860. : SSLVerifierResponse::CertificateRejected;
  15861. });
  15862. });
  15863. ASSERT_FALSE(res);
  15864. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15865. EXPECT_EQ(2, calls);
  15866. }
  15867. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15868. std::string pinned;
  15869. auto res = GetThroughTlsRedirectToDifferentPort(
  15870. [&](SSLClient &cli) {
  15871. cli.enable_server_certificate_verification(false);
  15872. // Pin the first certificate seen.
  15873. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15874. if (pinned.empty()) { pinned = ctx.serial(); }
  15875. return ctx.serial() == pinned;
  15876. });
  15877. },
  15878. // A certificate other than the first server's.
  15879. SERVER_CERT_FILE);
  15880. EXPECT_FALSE(res);
  15881. EXPECT_FALSE(pinned.empty());
  15882. }
  15883. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15884. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15885. std::string cert;
  15886. read_file(SERVER_CERT2_FILE, cert);
  15887. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15888. });
  15889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15890. EXPECT_EQ(StatusCode::OK_200, res->status);
  15891. }
  15892. // The target's certificate is signed by the root CA, which the first server's
  15893. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15894. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15895. auto res = GetThroughTlsRedirectToDifferentPort(
  15896. [](SSLClient &cli) {
  15897. std::string root_ca, cert;
  15898. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15899. read_file(SERVER_CERT2_FILE, cert);
  15900. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15901. cli.load_ca_cert_store(cert.data(), cert.size());
  15902. cli.enable_server_hostname_verification(false);
  15903. },
  15904. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15906. EXPECT_EQ(StatusCode::OK_200, res->status);
  15907. }
  15908. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15909. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15910. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15911. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15912. auto res = GetThroughTlsRedirectToDifferentPort(
  15913. [](SSLClient &cli) {
  15914. std::string root_ca, cert;
  15915. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15916. read_file(SERVER_CERT2_FILE, cert);
  15917. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15918. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15919. cli.enable_server_hostname_verification(false);
  15920. },
  15921. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15922. ASSERT_FALSE(res);
  15923. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15924. }
  15925. #endif
  15926. #endif
  15927. #ifdef CPPHTTPLIB_SSL_ENABLED
  15928. // Test that set_ca_cert_store() skips system certs (consistent with
  15929. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15930. // should be trusted - system certs should NOT be loaded.
  15931. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15932. // Load a specific cert that is NOT a system CA cert
  15933. std::string cert;
  15934. read_file(SERVER_CERT2_FILE, cert);
  15935. SSLClient cli("google.com");
  15936. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15937. cli.enable_server_certificate_verification(true);
  15938. // This should FAIL because:
  15939. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15940. // 2. System certs should NOT be loaded when custom store is set
  15941. // If system certs WERE loaded, this would succeed
  15942. auto res = cli.Get("/");
  15943. ASSERT_FALSE(res);
  15944. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15945. }
  15946. // Same as above, but through the native store handle path. Regression test:
  15947. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15948. // merged system certs into the user-provided store.
  15949. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15950. std::string cert;
  15951. read_file(SERVER_CERT2_FILE, cert);
  15952. SSLClient cli("google.com");
  15953. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15954. cli.enable_server_certificate_verification(true);
  15955. auto res = cli.Get("/");
  15956. ASSERT_FALSE(res);
  15957. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15958. }
  15959. // A custom store set via the native handle must still verify a server whose
  15960. // cert it does contain.
  15961. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15962. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15963. ASSERT_TRUE(svr.is_valid());
  15964. svr.Get("/test", [&](const Request &, Response &res) {
  15965. res.set_content("test", "text/plain");
  15966. });
  15967. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15968. auto se = detail::scope_exit([&] {
  15969. svr.stop();
  15970. t.join();
  15971. ASSERT_FALSE(svr.is_running());
  15972. });
  15973. svr.wait_until_ready();
  15974. SSLClient cli("127.0.0.1", PORT);
  15975. std::string cert;
  15976. read_file(SERVER_CERT2_FILE, cert);
  15977. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15978. cli.enable_server_certificate_verification(true);
  15979. cli.set_connection_timeout(30);
  15980. auto res = cli.Get("/test");
  15981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15982. ASSERT_EQ(StatusCode::OK_200, res->status);
  15983. }
  15984. // CA certs loaded through the universal Client must be transferred to the
  15985. // client created internally for following an HTTPS redirect. Regression test:
  15986. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15987. // the CA data for redirect transfer.
  15988. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15989. auto ssl_port = PORT + 1;
  15990. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15991. ASSERT_TRUE(ssl_svr1.is_valid());
  15992. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15993. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15994. "/index");
  15995. });
  15996. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15997. ASSERT_TRUE(ssl_svr2.is_valid());
  15998. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15999. res.set_content("test", "text/plain");
  16000. });
  16001. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16002. thread t2 =
  16003. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16004. auto se = detail::scope_exit([&] {
  16005. ssl_svr2.stop();
  16006. ssl_svr1.stop();
  16007. t2.join();
  16008. t.join();
  16009. ASSERT_FALSE(ssl_svr1.is_running());
  16010. });
  16011. ssl_svr1.wait_until_ready();
  16012. ssl_svr2.wait_until_ready();
  16013. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16014. std::string cert;
  16015. read_file(SERVER_CERT2_FILE, cert);
  16016. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16017. cli.enable_server_certificate_verification(true);
  16018. cli.set_follow_location(true);
  16019. cli.set_connection_timeout(30);
  16020. auto res = cli.Get("/index");
  16021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16022. ASSERT_EQ(StatusCode::OK_200, res->status);
  16023. }
  16024. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16025. // so a host signed by a system CA verifies even though a custom CA is set
  16026. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16027. std::string cert;
  16028. read_file(SERVER_CERT2_FILE, cert);
  16029. SSLClient cli("google.com");
  16030. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16031. cli.enable_system_ca(true);
  16032. cli.enable_server_certificate_verification(true);
  16033. auto res = cli.Get("/");
  16034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16035. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16036. }
  16037. // The custom CA remains effective when combined with the system CA
  16038. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16039. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16040. ASSERT_TRUE(svr.is_valid());
  16041. svr.Get("/test", [&](const Request &, Response &res) {
  16042. res.set_content("test", "text/plain");
  16043. });
  16044. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16045. auto se = detail::scope_exit([&] {
  16046. svr.stop();
  16047. t.join();
  16048. ASSERT_FALSE(svr.is_running());
  16049. });
  16050. svr.wait_until_ready();
  16051. SSLClient cli("127.0.0.1", PORT);
  16052. std::string cert;
  16053. read_file(SERVER_CERT2_FILE, cert);
  16054. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16055. cli.enable_system_ca(true);
  16056. cli.enable_server_certificate_verification(true);
  16057. cli.set_connection_timeout(30);
  16058. auto res = cli.Get("/test");
  16059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16060. ASSERT_EQ(StatusCode::OK_200, res->status);
  16061. }
  16062. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16063. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16064. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16065. static CFDictionaryRef
  16066. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16067. const SecTrustSettingsResult *result) {
  16068. auto constraint =
  16069. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16070. &kCFTypeDictionaryValueCallBacks);
  16071. if (policy) {
  16072. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16073. }
  16074. if (policy_string) {
  16075. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16076. kCFStringEncodingUTF8);
  16077. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16078. CFRelease(str);
  16079. }
  16080. if (result) {
  16081. auto number_value = static_cast<SInt32>(*result);
  16082. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16083. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16084. CFRelease(number);
  16085. }
  16086. return constraint;
  16087. }
  16088. static SecTrustSettingsResult
  16089. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16090. auto trust_settings =
  16091. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16092. for (auto constraint : constraints) {
  16093. CFArrayAppendValue(trust_settings, constraint);
  16094. CFRelease(constraint);
  16095. }
  16096. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16097. CFRelease(trust_settings);
  16098. return result;
  16099. }
  16100. // The system CA loader takes a Keychain certificate as a trusted root only
  16101. // when its Trust Settings say so for SSL, not merely because it has some.
  16102. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16103. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16104. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16105. const auto deny = kSecTrustSettingsResultDeny;
  16106. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16107. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16108. auto x509_policy = SecPolicyCreateBasicX509();
  16109. // "Always Trust", which stores no constraint at all
  16110. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16111. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16112. ssl_trust_settings_result(
  16113. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16114. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16115. ssl_trust_settings_result(
  16116. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16117. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16118. ssl_trust_settings_result(
  16119. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16120. // "Never Trust", for everything or for SSL
  16121. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16122. ssl_trust_settings_result(
  16123. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16124. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16125. ssl_trust_settings_result(
  16126. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16127. // Trusted for another policy, for one host, or not at all
  16128. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16129. ssl_trust_settings_result(
  16130. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16131. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16132. ssl_trust_settings_result({make_usage_constraint(
  16133. ssl_policy, "www.example.com", &trust_root)}));
  16134. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16135. ssl_trust_settings_result(
  16136. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16137. // The first constraint that applies to SSL decides
  16138. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16139. ssl_trust_settings_result(
  16140. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16141. make_usage_constraint(nullptr, nullptr, &deny)}));
  16142. CFRelease(x509_policy);
  16143. CFRelease(ssl_policy);
  16144. }
  16145. #endif
  16146. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16147. // skip chain verification entirely (only the certificate identity was
  16148. // checked), so a server presenting an untrusted certificate with a matching
  16149. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16150. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16151. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16152. ASSERT_TRUE(svr.is_valid());
  16153. svr.Get("/test", [&](const Request &, Response &res) {
  16154. res.set_content("test", "text/plain");
  16155. });
  16156. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16157. auto se = detail::scope_exit([&] {
  16158. svr.stop();
  16159. t.join();
  16160. ASSERT_FALSE(svr.is_running());
  16161. });
  16162. svr.wait_until_ready();
  16163. SSLClient cli("127.0.0.1", PORT);
  16164. std::string cert;
  16165. // A trusted CA that did not sign the server certificate. The server cert
  16166. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16167. // this connection.
  16168. read_file(CLIENT_CA_CERT_FILE, cert);
  16169. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16170. cli.enable_server_certificate_verification(true);
  16171. cli.set_connection_timeout(30);
  16172. auto res = cli.Get("/test");
  16173. ASSERT_FALSE(res);
  16174. }
  16175. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16176. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16177. // CA that failed to come through fails verification instead of trusting them.
  16178. // (wolfSSL does not list the system CAs it loaded.)
  16179. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16180. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16181. ASSERT_TRUE(svr.is_valid());
  16182. auto port = svr.bind_to_any_port("127.0.0.1");
  16183. ASSERT_LT(0, port);
  16184. thread t = thread([&] { svr.listen_after_bind(); });
  16185. auto se = detail::scope_exit([&] {
  16186. svr.stop();
  16187. t.join();
  16188. ASSERT_FALSE(svr.is_running());
  16189. });
  16190. svr.wait_until_ready();
  16191. // The CAs a client trusts once its first request has loaded them
  16192. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16193. Client cli("https://127.0.0.1:" + std::to_string(port));
  16194. setup(cli);
  16195. cli.Get("/");
  16196. return tls::get_ca_names(cli.tls_context()).size();
  16197. };
  16198. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16199. EXPECT_EQ(0u,
  16200. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16201. }
  16202. #endif
  16203. // A TLS setting changed between requests applies to the next one, not just to
  16204. // the next connection
  16205. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16206. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16207. ASSERT_TRUE(svr.is_valid());
  16208. svr.Get("/", [](const Request &req, Response &res) {
  16209. res.set_content(std::to_string(req.remote_port), "text/plain");
  16210. });
  16211. auto port = svr.bind_to_any_port("127.0.0.1");
  16212. ASSERT_LT(0, port);
  16213. thread t = thread([&] { svr.listen_after_bind(); });
  16214. auto se = detail::scope_exit([&] {
  16215. svr.stop();
  16216. t.join();
  16217. ASSERT_FALSE(svr.is_running());
  16218. });
  16219. svr.wait_until_ready();
  16220. SSLClient cli("127.0.0.1", port);
  16221. cli.set_keep_alive(true);
  16222. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16223. cli.enable_server_certificate_verification(false);
  16224. // The port the request went out from, so a new one means a new connection
  16225. auto client_port = [&] {
  16226. auto res = cli.Get("/");
  16227. return res ? res->body : std::string();
  16228. };
  16229. auto last = client_port();
  16230. ASSERT_FALSE(last.empty());
  16231. // Setting a value it already has keeps the connection
  16232. cli.enable_server_certificate_verification(false);
  16233. cli.enable_server_hostname_verification(true);
  16234. EXPECT_EQ(last, client_port());
  16235. cli.enable_server_certificate_verification(true);
  16236. auto res = cli.Get("/");
  16237. EXPECT_FALSE(res);
  16238. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16239. std::string ca;
  16240. read_file(SERVER_CERT2_FILE, ca);
  16241. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16242. last = client_port();
  16243. ASSERT_FALSE(last.empty());
  16244. std::vector<std::function<void()>> setters = {
  16245. [&] { cli.enable_server_hostname_verification(false); },
  16246. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16247. [&] {
  16248. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16249. },
  16250. [&] {
  16251. cli.set_server_certificate_verifier(
  16252. [](const tls::VerifyContext &) { return true; });
  16253. },
  16254. [&] {
  16255. cli.set_session_verifier(
  16256. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16257. },
  16258. };
  16259. for (const auto &setter : setters) {
  16260. setter();
  16261. auto next = client_port();
  16262. ASSERT_FALSE(next.empty());
  16263. EXPECT_NE(last, next);
  16264. last = next;
  16265. }
  16266. cli.set_session_verifier(
  16267. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16268. auto handle = cli.open_stream("GET", "/");
  16269. EXPECT_FALSE(handle.is_valid());
  16270. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16271. }
  16272. // A PEM given to create_ca_store() needs no NUL after it
  16273. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16274. std::string pem;
  16275. read_file(SERVER_CERT2_FILE, pem);
  16276. auto buf = pem + "X";
  16277. auto store = tls::create_ca_store(buf.data(), pem.size());
  16278. EXPECT_TRUE(store != nullptr);
  16279. SSLClient cli("localhost");
  16280. cli.set_ca_cert_store(store);
  16281. }
  16282. // enable_system_ca(false) prevents system CA loading entirely
  16283. TEST(SSLClientTest, DisableSystemCa_Online) {
  16284. SSLClient cli("google.com");
  16285. cli.enable_system_ca(false);
  16286. cli.enable_server_certificate_verification(true);
  16287. auto res = cli.Get("/");
  16288. ASSERT_FALSE(res);
  16289. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16290. // itself when the CA chain is empty
  16291. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16292. res.error() == Error::SSLConnection);
  16293. }
  16294. // The universal Client forwards enable_system_ca()
  16295. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16296. std::string cert;
  16297. read_file(SERVER_CERT2_FILE, cert);
  16298. Client cli("https://google.com");
  16299. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16300. cli.enable_system_ca(true);
  16301. cli.enable_server_certificate_verification(true);
  16302. auto res = cli.Get("/");
  16303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16304. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16305. }
  16306. // The system CA policy must carry over to the client created internally for
  16307. // following a cross-host HTTPS redirect
  16308. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16309. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16310. ASSERT_TRUE(svr.is_valid());
  16311. svr.Get("/index", [&](const Request &, Response &res) {
  16312. res.set_redirect("https://www.google.com/");
  16313. });
  16314. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16315. auto se = detail::scope_exit([&] {
  16316. svr.stop();
  16317. t.join();
  16318. ASSERT_FALSE(svr.is_running());
  16319. });
  16320. svr.wait_until_ready();
  16321. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16322. std::string cert;
  16323. read_file(SERVER_CERT2_FILE, cert);
  16324. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16325. cli.enable_system_ca(true);
  16326. cli.enable_server_certificate_verification(true);
  16327. cli.set_follow_location(true);
  16328. cli.set_connection_timeout(30);
  16329. // Receiving any response proves the redirect client completed the TLS
  16330. // handshake with a system-CA-signed host
  16331. auto res = cli.Get("/index");
  16332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16333. }
  16334. TEST(MultipartFormDataTest, LargeData) {
  16335. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16336. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16337. const ContentReader &content_reader) {
  16338. if (req.is_multipart_form_data()) {
  16339. std::vector<FormData> items;
  16340. content_reader(
  16341. [&](const FormData &file) {
  16342. items.push_back(file);
  16343. return true;
  16344. },
  16345. [&](const char *data, size_t data_length) {
  16346. items.back().content.append(data, data_length);
  16347. return true;
  16348. });
  16349. EXPECT_TRUE(std::string(items[0].name) == "document");
  16350. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16351. EXPECT_TRUE(items[0].filename == "2MB_data");
  16352. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16353. EXPECT_TRUE(items[1].name == "hello");
  16354. EXPECT_TRUE(items[1].content == "world");
  16355. EXPECT_TRUE(items[1].filename == "");
  16356. EXPECT_TRUE(items[1].content_type == "");
  16357. } else {
  16358. std::string body;
  16359. content_reader([&](const char *data, size_t data_length) {
  16360. body.append(data, data_length);
  16361. return true;
  16362. });
  16363. }
  16364. });
  16365. auto port = svr.bind_to_any_port(HOST);
  16366. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16367. auto se = detail::scope_exit([&] {
  16368. svr.stop();
  16369. t.join();
  16370. ASSERT_FALSE(svr.is_running());
  16371. });
  16372. svr.wait_until_ready();
  16373. {
  16374. std::string data(1024 * 1024 * 2, '.');
  16375. std::stringstream buffer;
  16376. buffer << data;
  16377. SSLClient cli(HOST, port);
  16378. cli.enable_server_certificate_verification(false);
  16379. UploadFormDataItems items{
  16380. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16381. {"hello", "world", "", ""},
  16382. };
  16383. auto res = cli.Post("/post", items);
  16384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16385. ASSERT_EQ(StatusCode::OK_200, res->status);
  16386. }
  16387. }
  16388. TEST(MultipartFormDataTest, DataProviderItems) {
  16389. std::random_device seed_gen;
  16390. std::mt19937 random(seed_gen());
  16391. std::string rand1;
  16392. rand1.resize(1000);
  16393. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16394. std::string rand2;
  16395. rand2.resize(3000);
  16396. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16397. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16398. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16399. const ContentReader &content_reader) {
  16400. ASSERT_FALSE(req.is_multipart_form_data());
  16401. std::string body;
  16402. content_reader([&](const char *data, size_t data_length) {
  16403. body.append(data, data_length);
  16404. return true;
  16405. });
  16406. EXPECT_EQ(body, "");
  16407. });
  16408. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16409. const ContentReader &content_reader) {
  16410. ASSERT_TRUE(req.is_multipart_form_data());
  16411. std::vector<FormData> items;
  16412. content_reader(
  16413. [&](const FormData &file) {
  16414. items.push_back(file);
  16415. return true;
  16416. },
  16417. [&](const char *data, size_t data_length) {
  16418. items.back().content.append(data, data_length);
  16419. return true;
  16420. });
  16421. ASSERT_TRUE(items.size() == 2);
  16422. EXPECT_EQ(std::string(items[0].name), "name1");
  16423. EXPECT_EQ(items[0].content, "Testing123");
  16424. EXPECT_EQ(items[0].filename, "filename1");
  16425. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16426. EXPECT_EQ(items[1].name, "name2");
  16427. EXPECT_EQ(items[1].content, "Testing456");
  16428. EXPECT_EQ(items[1].filename, "");
  16429. EXPECT_EQ(items[1].content_type, "");
  16430. });
  16431. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16432. const ContentReader &content_reader) {
  16433. ASSERT_TRUE(req.is_multipart_form_data());
  16434. std::vector<FormData> items;
  16435. content_reader(
  16436. [&](const FormData &file) {
  16437. items.push_back(file);
  16438. return true;
  16439. },
  16440. [&](const char *data, size_t data_length) {
  16441. items.back().content.append(data, data_length);
  16442. return true;
  16443. });
  16444. ASSERT_TRUE(items.size() == 2);
  16445. EXPECT_EQ(items[0].name, "name3");
  16446. EXPECT_EQ(items[0].content, rand1);
  16447. EXPECT_EQ(items[0].filename, "filename3");
  16448. EXPECT_EQ(items[0].content_type, "");
  16449. EXPECT_EQ(items[1].name, "name4");
  16450. EXPECT_EQ(items[1].content, rand2);
  16451. EXPECT_EQ(items[1].filename, "filename4");
  16452. EXPECT_EQ(items[1].content_type, "");
  16453. });
  16454. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16455. const ContentReader &content_reader) {
  16456. ASSERT_TRUE(req.is_multipart_form_data());
  16457. std::vector<FormData> items;
  16458. content_reader(
  16459. [&](const FormData &file) {
  16460. items.push_back(file);
  16461. return true;
  16462. },
  16463. [&](const char *data, size_t data_length) {
  16464. items.back().content.append(data, data_length);
  16465. return true;
  16466. });
  16467. ASSERT_TRUE(items.size() == 4);
  16468. EXPECT_EQ(std::string(items[0].name), "name1");
  16469. EXPECT_EQ(items[0].content, "Testing123");
  16470. EXPECT_EQ(items[0].filename, "filename1");
  16471. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16472. EXPECT_EQ(items[1].name, "name2");
  16473. EXPECT_EQ(items[1].content, "Testing456");
  16474. EXPECT_EQ(items[1].filename, "");
  16475. EXPECT_EQ(items[1].content_type, "");
  16476. EXPECT_EQ(items[2].name, "name3");
  16477. EXPECT_EQ(items[2].content, rand1);
  16478. EXPECT_EQ(items[2].filename, "filename3");
  16479. EXPECT_EQ(items[2].content_type, "");
  16480. EXPECT_EQ(items[3].name, "name4");
  16481. EXPECT_EQ(items[3].content, rand2);
  16482. EXPECT_EQ(items[3].filename, "filename4");
  16483. EXPECT_EQ(items[3].content_type, "");
  16484. });
  16485. auto port = svr.bind_to_any_port("localhost");
  16486. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16487. auto se = detail::scope_exit([&] {
  16488. svr.stop();
  16489. t.join();
  16490. ASSERT_FALSE(svr.is_running());
  16491. });
  16492. svr.wait_until_ready();
  16493. {
  16494. SSLClient cli("localhost", port);
  16495. cli.enable_server_certificate_verification(false);
  16496. UploadFormDataItems items{
  16497. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16498. {"name2", "Testing456", "", ""}, // not a file
  16499. };
  16500. {
  16501. auto res = cli.Post("/post-none", {}, {}, {});
  16502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16503. ASSERT_EQ(StatusCode::OK_200, res->status);
  16504. }
  16505. FormDataProviderItems providers;
  16506. {
  16507. auto res =
  16508. cli.Post("/post-items", {}, items, providers); // empty providers
  16509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16510. ASSERT_EQ(StatusCode::OK_200, res->status);
  16511. }
  16512. providers.push_back({"name3",
  16513. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16514. // test the offset is given correctly at each step
  16515. if (!offset)
  16516. sink.os.write(rand1.data(), 30);
  16517. else if (offset == 30)
  16518. sink.os.write(rand1.data() + 30, 300);
  16519. else if (offset == 330)
  16520. sink.os.write(rand1.data() + 330, 670);
  16521. else if (offset == rand1.size())
  16522. sink.done();
  16523. return true;
  16524. },
  16525. "filename3",
  16526. {}});
  16527. providers.push_back({"name4",
  16528. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16529. // test the offset is given correctly at each step
  16530. if (!offset)
  16531. sink.os.write(rand2.data(), 2000);
  16532. else if (offset == 2000)
  16533. sink.os.write(rand2.data() + 2000, 1);
  16534. else if (offset == 2001)
  16535. sink.os.write(rand2.data() + 2001, 999);
  16536. else if (offset == rand2.size())
  16537. sink.done();
  16538. return true;
  16539. },
  16540. "filename4",
  16541. {}});
  16542. {
  16543. auto res = cli.Post("/post-providers", {}, {}, providers);
  16544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16545. ASSERT_EQ(StatusCode::OK_200, res->status);
  16546. }
  16547. {
  16548. auto res = cli.Post("/post-both", {}, items, providers);
  16549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16550. ASSERT_EQ(StatusCode::OK_200, res->status);
  16551. }
  16552. }
  16553. }
  16554. TEST(MultipartFormDataTest, BadHeader) {
  16555. Server svr;
  16556. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16557. res.set_content("ok", "text/plain");
  16558. });
  16559. thread t = thread([&] { svr.listen(HOST, PORT); });
  16560. auto se = detail::scope_exit([&] {
  16561. svr.stop();
  16562. t.join();
  16563. ASSERT_FALSE(svr.is_running());
  16564. });
  16565. svr.wait_until_ready();
  16566. const std::string body =
  16567. "This is the preamble. It is to be ignored, though it\r\n"
  16568. "is a handy place for composition agents to include an\r\n"
  16569. "explanatory note to non-MIME conformant readers.\r\n"
  16570. "\r\n"
  16571. "\r\n"
  16572. "--simple boundary\r\n"
  16573. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16574. ": BAD...\r\n"
  16575. "\r\n"
  16576. "value1\r\n"
  16577. "--simple boundary\r\n"
  16578. "Content-Disposition: form-data; name=\"field2\"; "
  16579. "filename=\"example.txt\"\r\n"
  16580. "\r\n"
  16581. "value2\r\n"
  16582. "--simple boundary--\r\n"
  16583. "This is the epilogue. It is also to be ignored.\r\n";
  16584. std::string content_type =
  16585. R"(multipart/form-data; boundary="simple boundary")";
  16586. Client cli(HOST, PORT);
  16587. auto res = cli.Post("/post", body, content_type.c_str());
  16588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16589. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16590. }
  16591. TEST(MultipartFormDataTest, WithPreamble) {
  16592. Server svr;
  16593. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16594. res.set_content("ok", "text/plain");
  16595. });
  16596. thread t = thread([&] { svr.listen(HOST, PORT); });
  16597. auto se = detail::scope_exit([&] {
  16598. svr.stop();
  16599. t.join();
  16600. ASSERT_FALSE(svr.is_running());
  16601. });
  16602. svr.wait_until_ready();
  16603. const std::string body =
  16604. "This is the preamble. It is to be ignored, though it\r\n"
  16605. "is a handy place for composition agents to include an\r\n"
  16606. "explanatory note to non-MIME conformant readers.\r\n"
  16607. "\r\n"
  16608. "\r\n"
  16609. "--simple boundary\r\n"
  16610. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16611. "\r\n"
  16612. "value1\r\n"
  16613. "--simple boundary\r\n"
  16614. "Content-Disposition: form-data; name=\"field2\"; "
  16615. "filename=\"example.txt\"\r\n"
  16616. "\r\n"
  16617. "value2\r\n"
  16618. "--simple boundary--\r\n"
  16619. "This is the epilogue. It is also to be ignored.\r\n";
  16620. std::string content_type =
  16621. R"(multipart/form-data; boundary="simple boundary")";
  16622. Client cli(HOST, PORT);
  16623. auto res = cli.Post("/post", body, content_type.c_str());
  16624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16625. EXPECT_EQ(StatusCode::OK_200, res->status);
  16626. }
  16627. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16628. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16629. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16630. const ContentReader &content_reader) {
  16631. if (req.is_multipart_form_data()) {
  16632. std::vector<FormData> items;
  16633. content_reader(
  16634. [&](const FormData &file) {
  16635. items.push_back(file);
  16636. return true;
  16637. },
  16638. [&](const char *data, size_t data_length) {
  16639. items.back().content.append(data, data_length);
  16640. return true;
  16641. });
  16642. EXPECT_TRUE(std::string(items[0].name) == "document");
  16643. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16644. EXPECT_TRUE(items[0].filename == "2MB_data");
  16645. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16646. EXPECT_TRUE(items[1].name == "hello");
  16647. EXPECT_TRUE(items[1].content == "world");
  16648. EXPECT_TRUE(items[1].filename == "");
  16649. EXPECT_TRUE(items[1].content_type == "");
  16650. } else {
  16651. std::string body;
  16652. content_reader([&](const char *data, size_t data_length) {
  16653. body.append(data, data_length);
  16654. return true;
  16655. });
  16656. }
  16657. });
  16658. auto port = svr.bind_to_any_port("localhost");
  16659. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16660. auto se = detail::scope_exit([&] {
  16661. svr.stop();
  16662. t.join();
  16663. ASSERT_FALSE(svr.is_running());
  16664. });
  16665. svr.wait_until_ready();
  16666. {
  16667. std::string data(1024 * 1024 * 2, '.');
  16668. std::stringstream buffer;
  16669. buffer << data;
  16670. SSLClient cli("localhost", port);
  16671. cli.enable_server_certificate_verification(false);
  16672. UploadFormDataItems items{
  16673. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16674. {"hello", "world", "", ""},
  16675. };
  16676. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16678. ASSERT_EQ(StatusCode::OK_200, res->status);
  16679. }
  16680. }
  16681. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16682. std::string data(1024 * 1024 * 2, '&');
  16683. std::stringstream buffer;
  16684. buffer << data;
  16685. Client cli("https://localhost:8080");
  16686. UploadFormDataItems items{
  16687. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16688. {"hello", "world", "", ""},
  16689. };
  16690. for (const char &c : " \t\r\n") {
  16691. auto res =
  16692. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16693. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16694. ASSERT_FALSE(res);
  16695. }
  16696. }
  16697. TEST(MultipartFormDataTest, PutFormData) {
  16698. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16699. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16700. const ContentReader &content_reader) {
  16701. if (req.is_multipart_form_data()) {
  16702. std::vector<FormData> items;
  16703. content_reader(
  16704. [&](const FormData &file) {
  16705. items.push_back(file);
  16706. return true;
  16707. },
  16708. [&](const char *data, size_t data_length) {
  16709. items.back().content.append(data, data_length);
  16710. return true;
  16711. });
  16712. EXPECT_TRUE(std::string(items[0].name) == "document");
  16713. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16714. EXPECT_TRUE(items[0].filename == "2MB_data");
  16715. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16716. EXPECT_TRUE(items[1].name == "hello");
  16717. EXPECT_TRUE(items[1].content == "world");
  16718. EXPECT_TRUE(items[1].filename == "");
  16719. EXPECT_TRUE(items[1].content_type == "");
  16720. } else {
  16721. std::string body;
  16722. content_reader([&](const char *data, size_t data_length) {
  16723. body.append(data, data_length);
  16724. return true;
  16725. });
  16726. }
  16727. });
  16728. auto port = svr.bind_to_any_port("localhost");
  16729. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16730. auto se = detail::scope_exit([&] {
  16731. svr.stop();
  16732. t.join();
  16733. ASSERT_FALSE(svr.is_running());
  16734. });
  16735. svr.wait_until_ready();
  16736. {
  16737. std::string data(1024 * 1024 * 2, '&');
  16738. std::stringstream buffer;
  16739. buffer << data;
  16740. SSLClient cli("localhost", port);
  16741. cli.enable_server_certificate_verification(false);
  16742. UploadFormDataItems items{
  16743. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16744. {"hello", "world", "", ""},
  16745. };
  16746. auto res = cli.Put("/put", items);
  16747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16748. ASSERT_EQ(StatusCode::OK_200, res->status);
  16749. }
  16750. }
  16751. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16752. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16753. svr.Put("/put_customboundary",
  16754. [&](const Request &req, const Response & /*res*/,
  16755. const ContentReader &content_reader) {
  16756. if (req.is_multipart_form_data()) {
  16757. std::vector<FormData> items;
  16758. content_reader(
  16759. [&](const FormData &file) {
  16760. items.push_back(file);
  16761. return true;
  16762. },
  16763. [&](const char *data, size_t data_length) {
  16764. items.back().content.append(data, data_length);
  16765. return true;
  16766. });
  16767. EXPECT_TRUE(std::string(items[0].name) == "document");
  16768. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16769. EXPECT_TRUE(items[0].filename == "2MB_data");
  16770. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16771. EXPECT_TRUE(items[1].name == "hello");
  16772. EXPECT_TRUE(items[1].content == "world");
  16773. EXPECT_TRUE(items[1].filename == "");
  16774. EXPECT_TRUE(items[1].content_type == "");
  16775. } else {
  16776. std::string body;
  16777. content_reader([&](const char *data, size_t data_length) {
  16778. body.append(data, data_length);
  16779. return true;
  16780. });
  16781. }
  16782. });
  16783. auto port = svr.bind_to_any_port("localhost");
  16784. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16785. auto se = detail::scope_exit([&] {
  16786. svr.stop();
  16787. t.join();
  16788. ASSERT_FALSE(svr.is_running());
  16789. });
  16790. svr.wait_until_ready();
  16791. {
  16792. std::string data(1024 * 1024 * 2, '&');
  16793. std::stringstream buffer;
  16794. buffer << data;
  16795. SSLClient cli("localhost", port);
  16796. cli.enable_server_certificate_verification(false);
  16797. UploadFormDataItems items{
  16798. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16799. {"hello", "world", "", ""},
  16800. };
  16801. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16803. ASSERT_EQ(StatusCode::OK_200, res->status);
  16804. }
  16805. }
  16806. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16807. std::string data(1024 * 1024 * 2, '&');
  16808. std::stringstream buffer;
  16809. buffer << data;
  16810. Client cli("https://localhost:8080");
  16811. cli.enable_server_certificate_verification(false);
  16812. UploadFormDataItems items{
  16813. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16814. {"hello", "world", "", ""},
  16815. };
  16816. for (const char &c : " \t\r\n") {
  16817. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16818. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16819. ASSERT_FALSE(res);
  16820. }
  16821. }
  16822. TEST(MultipartFormDataTest, AlternateFilename) {
  16823. auto handled = false;
  16824. Server svr;
  16825. svr.Post("/test", [&](const Request &req, Response &res) {
  16826. ASSERT_EQ(2u, req.form.files.size());
  16827. ASSERT_EQ(1u, req.form.fields.size());
  16828. // Test files
  16829. const auto &file1 = req.form.get_file("file1");
  16830. ASSERT_EQ("file1", file1.name);
  16831. ASSERT_EQ("A.txt", file1.filename);
  16832. ASSERT_EQ("text/plain", file1.content_type);
  16833. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16834. const auto &file2 = req.form.get_file("file2");
  16835. ASSERT_EQ("file2", file2.name);
  16836. ASSERT_EQ("a.html", file2.filename);
  16837. ASSERT_EQ("text/html", file2.content_type);
  16838. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16839. file2.content);
  16840. // Test text field
  16841. const auto &text = req.form.get_field("text");
  16842. ASSERT_EQ("text default", text);
  16843. res.set_content("ok", "text/plain");
  16844. handled = true;
  16845. });
  16846. thread t = thread([&] { svr.listen(HOST, PORT); });
  16847. auto se = detail::scope_exit([&] {
  16848. svr.stop();
  16849. t.join();
  16850. ASSERT_FALSE(svr.is_running());
  16851. ASSERT_TRUE(handled);
  16852. });
  16853. svr.wait_until_ready();
  16854. auto req = "POST /test HTTP/1.1\r\n"
  16855. "Host: localhost\r\n"
  16856. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16857. "Content-Length: 399\r\n"
  16858. "\r\n"
  16859. "----------\r\n"
  16860. "Content-Disposition: form-data; name=\"text\"\r\n"
  16861. "\r\n"
  16862. "text default\r\n"
  16863. "----------\r\n"
  16864. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16865. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16866. "Content-Type: text/plain\r\n"
  16867. "\r\n"
  16868. "Content of a.txt.\r\n"
  16869. "\r\n"
  16870. "----------\r\n"
  16871. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16872. "\"a.html\"\r\n"
  16873. "Content-Type: text/html\r\n"
  16874. "\r\n"
  16875. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16876. "\r\n"
  16877. "------------\r\n";
  16878. ASSERT_TRUE(send_request(1, req));
  16879. }
  16880. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16881. auto handled = false;
  16882. Server svr;
  16883. svr.Post("/test", [&](const Request &req, Response &res) {
  16884. // Case-insensitive "utf-8''" prefix with a long value
  16885. const auto &file = req.form.get_file("file1");
  16886. ASSERT_EQ("file1", file.name);
  16887. // 8000 chars exercises both the Content-Disposition parser and the
  16888. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16889. // Prior to the fix, std::regex_match on this header would cause O(N)
  16890. // stack recursion in libstdc++, leading to SIGSEGV.
  16891. std::string expected_filename(8000, 'A');
  16892. ASSERT_EQ(expected_filename, file.filename);
  16893. res.set_content("ok", "text/plain");
  16894. handled = true;
  16895. });
  16896. thread t = thread([&] { svr.listen(HOST, PORT); });
  16897. auto se = detail::scope_exit([&] {
  16898. svr.stop();
  16899. t.join();
  16900. ASSERT_FALSE(svr.is_running());
  16901. ASSERT_TRUE(handled);
  16902. });
  16903. svr.wait_until_ready();
  16904. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16905. // Regression test for GHSA-qq6v-r583-3h69
  16906. std::string long_filename(8000, 'A');
  16907. std::string body = "----------\r\n"
  16908. "Content-Disposition: form-data; name=\"file1\"; "
  16909. "filename*=\"Utf-8''" +
  16910. long_filename +
  16911. "\"\r\n"
  16912. "\r\n"
  16913. "hello\r\n"
  16914. "------------\r\n";
  16915. auto req = "POST /test HTTP/1.1\r\n"
  16916. "Host: localhost\r\n"
  16917. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16918. "Content-Length: " +
  16919. std::to_string(body.size()) + "\r\n\r\n" + body;
  16920. ASSERT_TRUE(send_request(1, req));
  16921. }
  16922. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16923. auto handled = false;
  16924. Server svr;
  16925. svr.Post("/test", [&](const Request &req, Response &) {
  16926. ASSERT_EQ(2u, req.form.fields.size());
  16927. const auto &text1 = req.form.get_field("text1");
  16928. ASSERT_EQ("text1", text1);
  16929. const auto &text2 = req.form.get_field("text2");
  16930. ASSERT_EQ("text2", text2);
  16931. handled = true;
  16932. });
  16933. thread t = thread([&] { svr.listen(HOST, PORT); });
  16934. auto se = detail::scope_exit([&] {
  16935. svr.stop();
  16936. t.join();
  16937. ASSERT_FALSE(svr.is_running());
  16938. ASSERT_TRUE(handled);
  16939. });
  16940. svr.wait_until_ready();
  16941. auto req = "POST /test HTTP/1.1\r\n"
  16942. "Host: localhost\r\n"
  16943. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16944. "Content-Length: 146\r\n"
  16945. "\r\n----------\r\n"
  16946. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16947. "\r\n"
  16948. "text1"
  16949. "\r\n----------\r\n"
  16950. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16951. "\r\n"
  16952. "text2"
  16953. "\r\n------------";
  16954. std::string response;
  16955. ASSERT_TRUE(send_request(1, req, &response));
  16956. ASSERT_EQ("200", response.substr(9, 3));
  16957. }
  16958. TEST(MultipartFormDataTest, ContentLength) {
  16959. auto handled = false;
  16960. Server svr;
  16961. svr.Post("/test", [&](const Request &req, Response &) {
  16962. ASSERT_EQ(2u, req.form.fields.size());
  16963. const auto &text1 = req.form.get_field("text1");
  16964. ASSERT_EQ("text1", text1);
  16965. const auto &text2 = req.form.get_field("text2");
  16966. ASSERT_EQ("text2", text2);
  16967. handled = true;
  16968. });
  16969. thread t = thread([&] { svr.listen(HOST, PORT); });
  16970. auto se = detail::scope_exit([&] {
  16971. svr.stop();
  16972. t.join();
  16973. ASSERT_FALSE(svr.is_running());
  16974. ASSERT_TRUE(handled);
  16975. });
  16976. svr.wait_until_ready();
  16977. auto req = "POST /test HTTP/1.1\r\n"
  16978. "Host: localhost\r\n"
  16979. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16980. "Content-Length: 167\r\n"
  16981. "\r\n----------\r\n"
  16982. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16983. "Content-Length: 5\r\n"
  16984. "\r\n"
  16985. "text1"
  16986. "\r\n----------\r\n"
  16987. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16988. "\r\n"
  16989. "text2"
  16990. "\r\n------------\r\n";
  16991. std::string response;
  16992. ASSERT_TRUE(send_request(1, req, &response));
  16993. ASSERT_EQ("200", response.substr(9, 3));
  16994. }
  16995. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16996. auto handled = false;
  16997. Server svr;
  16998. svr.Post("/test", [&](const Request &req, Response &) {
  16999. ASSERT_EQ(2u, req.form.fields.size());
  17000. const auto &text1 = req.form.get_field("text1");
  17001. ASSERT_EQ("text1", text1);
  17002. // TODO: Add header access for text fields if needed
  17003. const auto &text2 = req.form.get_field("text2");
  17004. ASSERT_EQ("text2", text2);
  17005. // TODO: Header access for text fields needs to be implemented
  17006. // auto &headers = it->second.headers;
  17007. // ASSERT_EQ(3U, headers.size());
  17008. // auto custom_header = headers.find("x-whatever");
  17009. // ASSERT_TRUE(custom_header != headers.end());
  17010. // ASSERT_NE("customvalue", custom_header->second);
  17011. // ASSERT_EQ("CustomValue", custom_header->second);
  17012. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17013. handled = true;
  17014. });
  17015. thread t = thread([&] { svr.listen(HOST, PORT); });
  17016. auto se = detail::scope_exit([&] {
  17017. svr.stop();
  17018. t.join();
  17019. ASSERT_FALSE(svr.is_running());
  17020. ASSERT_TRUE(handled);
  17021. });
  17022. svr.wait_until_ready();
  17023. auto req = "POST /test HTTP/1.1\r\n"
  17024. "Host: localhost\r\n"
  17025. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17026. "Content-Length: 232\r\n"
  17027. "\r\n----------\r\n"
  17028. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17029. "Content-Length: 5\r\n"
  17030. "X-Test: 1\r\n"
  17031. "\r\n"
  17032. "text1"
  17033. "\r\n----------\r\n"
  17034. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17035. "Content-Type: text/plain\r\n"
  17036. "X-Whatever: CustomValue\r\n"
  17037. "\r\n"
  17038. "text2"
  17039. "\r\n------------\r\n"
  17040. "That should be disregarded. Not even read";
  17041. std::string response;
  17042. ASSERT_TRUE(send_request(1, req, &response));
  17043. ASSERT_EQ("200", response.substr(9, 3));
  17044. }
  17045. TEST(MultipartFormDataTest, LargeHeader) {
  17046. auto handled = false;
  17047. Server svr;
  17048. svr.Post("/test", [&](const Request &req, Response &) {
  17049. ASSERT_EQ(1u, req.form.fields.size());
  17050. const auto &text = req.form.get_field("name1");
  17051. ASSERT_EQ("text1", text);
  17052. handled = true;
  17053. });
  17054. thread t = thread([&] { svr.listen(HOST, PORT); });
  17055. auto se = detail::scope_exit([&] {
  17056. svr.stop();
  17057. t.join();
  17058. ASSERT_FALSE(svr.is_running());
  17059. ASSERT_TRUE(handled);
  17060. });
  17061. svr.wait_until_ready();
  17062. auto boundary = std::string("cpp-httplib-multipart-data");
  17063. std::string content = "--" + boundary +
  17064. "\r\n"
  17065. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17066. "\r\n"
  17067. "text1\r\n"
  17068. "--" +
  17069. boundary + "--\r\n";
  17070. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17071. "Host: localhost\r\n"
  17072. "Content-Type: multipart/form-data;boundary=" +
  17073. boundary +
  17074. "\r\n"
  17075. "Content-Length: " +
  17076. std::to_string(content.size()) +
  17077. "\r\n"
  17078. "Dummy-Header: ";
  17079. std::string header_suffix = "\r\n"
  17080. "\r\n";
  17081. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17082. size_t header_dummy_size =
  17083. read_buff_size -
  17084. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17085. auto header_dummy = std::string(header_dummy_size, '@');
  17086. auto req = header_prefix + header_dummy + header_suffix + content;
  17087. std::string response;
  17088. ASSERT_TRUE(send_request(1, req, &response));
  17089. ASSERT_EQ("200", response.substr(9, 3));
  17090. }
  17091. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17092. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17093. // (not chunked Transfer-Encoding) after the streaming refactor.
  17094. auto handled = false;
  17095. Server svr;
  17096. svr.Post("/upload", [&](const Request &req, Response &res) {
  17097. auto cl_it = req.headers.find("Content-Length");
  17098. EXPECT_TRUE(cl_it != req.headers.end());
  17099. auto te_it = req.headers.find("Transfer-Encoding");
  17100. EXPECT_TRUE(te_it == req.headers.end());
  17101. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17102. res.set_content("ok", "text/plain");
  17103. handled = true;
  17104. });
  17105. auto port = svr.bind_to_any_port(HOST);
  17106. auto t = thread([&] { svr.listen_after_bind(); });
  17107. auto se = detail::scope_exit([&] {
  17108. svr.stop();
  17109. t.join();
  17110. ASSERT_FALSE(svr.is_running());
  17111. ASSERT_TRUE(handled);
  17112. });
  17113. svr.wait_until_ready();
  17114. UploadFormDataItems items = {
  17115. {"field1", "hello", "", "text/plain"},
  17116. {"file1", "world", "test.txt", "application/octet-stream"},
  17117. };
  17118. Client cli(HOST, port);
  17119. auto res = cli.Post("/upload", {}, items);
  17120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17121. EXPECT_EQ(StatusCode::OK_200, res->status);
  17122. }
  17123. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17124. // Verify that make_multipart_content_provider coalesces many small segments
  17125. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17126. constexpr size_t kItemCount = 1000;
  17127. UploadFormDataItems items;
  17128. items.reserve(kItemCount);
  17129. for (size_t i = 0; i < kItemCount; i++) {
  17130. items.push_back(
  17131. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17132. }
  17133. const std::string boundary = "----test-boundary";
  17134. auto content_length = detail::get_multipart_content_length(items, boundary);
  17135. auto provider = detail::make_multipart_content_provider(items, boundary);
  17136. // Drive the provider the same way write_content_with_progress does
  17137. size_t write_count = 0;
  17138. size_t total_bytes = 0;
  17139. DataSink sink;
  17140. size_t offset = 0;
  17141. sink.write = [&](const char *d, size_t l) -> bool {
  17142. (void)d;
  17143. write_count++;
  17144. total_bytes += l;
  17145. offset += l;
  17146. return true;
  17147. };
  17148. sink.is_writable = []() -> bool { return true; };
  17149. while (offset < content_length) {
  17150. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17151. }
  17152. EXPECT_EQ(content_length, total_bytes);
  17153. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17154. // With buffering into 64KB blocks, write_count should be much smaller.
  17155. auto segment_count = 3 * kItemCount + 1;
  17156. EXPECT_LT(write_count, segment_count / 10);
  17157. }
  17158. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17159. // Integration test: send many UploadFormDataItems and verify the server
  17160. // receives all of them correctly (#2410).
  17161. constexpr size_t kItemCount = 500;
  17162. auto handled = false;
  17163. Server svr;
  17164. svr.Post("/upload", [&](const Request &req, Response &res) {
  17165. EXPECT_EQ(kItemCount, req.form.fields.size());
  17166. for (size_t i = 0; i < kItemCount; i++) {
  17167. auto key = "field" + std::to_string(i);
  17168. auto val = "value" + std::to_string(i);
  17169. auto it = req.form.fields.find(key);
  17170. if (it != req.form.fields.end()) {
  17171. EXPECT_EQ(val, it->second.content);
  17172. } else {
  17173. ADD_FAILURE() << "Missing field: " << key;
  17174. }
  17175. }
  17176. res.set_content("ok", "text/plain");
  17177. handled = true;
  17178. });
  17179. auto port = svr.bind_to_any_port(HOST);
  17180. auto t = thread([&] { svr.listen_after_bind(); });
  17181. auto se = detail::scope_exit([&] {
  17182. svr.stop();
  17183. t.join();
  17184. ASSERT_FALSE(svr.is_running());
  17185. ASSERT_TRUE(handled);
  17186. });
  17187. svr.wait_until_ready();
  17188. UploadFormDataItems items;
  17189. items.reserve(kItemCount);
  17190. for (size_t i = 0; i < kItemCount; i++) {
  17191. items.push_back(
  17192. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17193. }
  17194. Client cli(HOST, port);
  17195. auto res = cli.Post("/upload", items);
  17196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17197. EXPECT_EQ(StatusCode::OK_200, res->status);
  17198. }
  17199. TEST(MultipartFormDataTest, MakeFileProvider) {
  17200. // Verify make_file_provider sends a file's contents correctly.
  17201. const std::string file_content(4096, 'Z');
  17202. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17203. {
  17204. std::ofstream ofs(tmp_path, std::ios::binary);
  17205. ofs.write(file_content.data(),
  17206. static_cast<std::streamsize>(file_content.size()));
  17207. }
  17208. auto handled = false;
  17209. Server svr;
  17210. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17211. const ContentReader &content_reader) {
  17212. ASSERT_TRUE(req.is_multipart_form_data());
  17213. std::vector<FormData> items;
  17214. content_reader(
  17215. [&](const FormData &file) {
  17216. items.push_back(file);
  17217. return true;
  17218. },
  17219. [&](const char *data, size_t data_length) {
  17220. items.back().content.append(data, data_length);
  17221. return true;
  17222. });
  17223. ASSERT_EQ(1u, items.size());
  17224. EXPECT_EQ("myfile", items[0].name);
  17225. EXPECT_EQ("data.bin", items[0].filename);
  17226. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17227. EXPECT_EQ(file_content, items[0].content);
  17228. handled = true;
  17229. });
  17230. auto port = svr.bind_to_any_port(HOST);
  17231. auto t = thread([&] { svr.listen_after_bind(); });
  17232. auto se = detail::scope_exit([&] {
  17233. svr.stop();
  17234. t.join();
  17235. ASSERT_FALSE(svr.is_running());
  17236. ASSERT_TRUE(handled);
  17237. std::remove(tmp_path.c_str());
  17238. });
  17239. svr.wait_until_ready();
  17240. FormDataProviderItems providers;
  17241. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17242. "application/octet-stream"));
  17243. Client cli(HOST, port);
  17244. auto res = cli.Post("/upload", {}, {}, providers);
  17245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17246. EXPECT_EQ(StatusCode::OK_200, res->status);
  17247. }
  17248. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17249. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17250. // (100) headers is rejected with a 400 Bad Request response.
  17251. Server svr;
  17252. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17253. res.set_content("ok", "text/plain");
  17254. });
  17255. thread t = thread([&] { svr.listen(HOST, PORT); });
  17256. auto se = detail::scope_exit([&] {
  17257. svr.stop();
  17258. t.join();
  17259. ASSERT_FALSE(svr.is_running());
  17260. });
  17261. svr.wait_until_ready();
  17262. // Build a multipart part with 101 custom headers (exceeding
  17263. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17264. std::stringstream body;
  17265. body << "--simpleboundary\r\n"
  17266. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17267. for (int i = 0; i < 101; i++) {
  17268. body << "X-Custom-Header-" << i << ": value\r\n";
  17269. }
  17270. body << "\r\n"
  17271. << "value1\r\n"
  17272. << "--simpleboundary--\r\n";
  17273. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17274. Client cli(HOST, PORT);
  17275. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17277. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17278. }
  17279. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17280. // A body that never contains the declared boundary must not be accumulated
  17281. // while the parser waits for it. Buffering it would also make every read
  17282. // rescan everything seen so far, which is quadratic in the body size.
  17283. Server svr;
  17284. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17285. res.set_content("ok", "text/plain");
  17286. });
  17287. auto port = svr.bind_to_any_port(HOST);
  17288. thread t = thread([&] { svr.listen_after_bind(); });
  17289. auto se = detail::scope_exit([&] {
  17290. svr.stop();
  17291. t.join();
  17292. ASSERT_FALSE(svr.is_running());
  17293. });
  17294. svr.wait_until_ready();
  17295. Client cli(HOST, port);
  17296. cli.set_read_timeout(60, 0);
  17297. cli.set_write_timeout(60, 0);
  17298. // '-' is the worst case: it matches the first character of the boundary, so
  17299. // every position has to be checked against it.
  17300. auto post_dashes = [&](size_t size) {
  17301. const std::string body(size, '-');
  17302. auto start = std::chrono::steady_clock::now();
  17303. auto res =
  17304. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17305. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17306. std::chrono::steady_clock::now() - start)
  17307. .count();
  17308. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17309. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17310. return ms;
  17311. };
  17312. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17313. // Windows.
  17314. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17315. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17316. // Comparing the two sizes rather than checking an absolute duration keeps
  17317. // this meaningful across build types and CI load, both of which move the
  17318. // absolute numbers by more than an order of magnitude. Four times the bytes
  17319. // costs about four times the time when parsing is linear, and about sixteen
  17320. // times when the body is buffered and rescanned.
  17321. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17322. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17323. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17324. << "ms, which suggests the body is being buffered and rescanned";
  17325. }
  17326. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17327. // A boundary can only be followed by CRLF or by "--", so anything else is
  17328. // malformed no matter what comes next. The parser must say so right away
  17329. // instead of buffering the rest of the declared body.
  17330. Server svr;
  17331. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17332. res.set_content("ok", "text/plain");
  17333. });
  17334. auto port = svr.bind_to_any_port(HOST);
  17335. thread t = thread([&] { svr.listen_after_bind(); });
  17336. auto se = detail::scope_exit([&] {
  17337. svr.stop();
  17338. t.join();
  17339. ASSERT_FALSE(svr.is_running());
  17340. });
  17341. svr.wait_until_ready();
  17342. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17343. // buffers instead of failing would still be waiting for the remaining bytes.
  17344. const std::string body = "--zzzz\r\n"
  17345. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17346. "\r\n"
  17347. "text1"
  17348. "\r\n--zzzzXX";
  17349. const std::string req = "POST /post HTTP/1.1\r\n"
  17350. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17351. "Content-Length: 1048576\r\n"
  17352. "\r\n" +
  17353. body;
  17354. std::string response;
  17355. ASSERT_TRUE(send_request(3, req, &response, port));
  17356. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17357. EXPECT_EQ("400", response.substr(9, 3));
  17358. }
  17359. // Posts a multipart body split into two writes, so that the server sees the
  17360. // split at whatever offset the caller chose, and expects the single "text1"
  17361. // field to come through.
  17362. static void expect_split_multipart_ok(const std::string &body1,
  17363. const std::string &body2) {
  17364. auto handled = false;
  17365. Server svr;
  17366. svr.Post("/post", [&](const Request &req, Response &) {
  17367. EXPECT_EQ(1u, req.form.fields.size());
  17368. EXPECT_EQ("text1", req.form.get_field("text1"));
  17369. handled = true;
  17370. });
  17371. auto port = svr.bind_to_any_port(HOST);
  17372. thread t = thread([&] { svr.listen_after_bind(); });
  17373. auto se = detail::scope_exit([&] {
  17374. svr.stop();
  17375. t.join();
  17376. ASSERT_FALSE(svr.is_running());
  17377. ASSERT_TRUE(handled);
  17378. });
  17379. svr.wait_until_ready();
  17380. // "Connection: close" makes the server close once it has answered, so the
  17381. // response drain ends immediately instead of idling until the read timeout.
  17382. const std::string head =
  17383. "POST /post HTTP/1.1\r\n"
  17384. "Host: localhost\r\n"
  17385. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17386. "Connection: close\r\n"
  17387. "Content-Length: " +
  17388. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17389. std::string response;
  17390. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17391. ASSERT_GE(response.size(), 12u) << "no response";
  17392. EXPECT_EQ("200", response.substr(9, 3));
  17393. }
  17394. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17395. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17396. // ignored, including when it does not arrive in the same read as the
  17397. // close-delimiter itself.
  17398. expect_split_multipart_ok("--zzzz\r\n"
  17399. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17400. "\r\n"
  17401. "text1"
  17402. "\r\n--zzzz--",
  17403. "\r\nthis epilogue must be ignored\r\n");
  17404. }
  17405. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17406. // The initial boundary may be preceded by a preamble of any length and may
  17407. // straddle a read boundary. Discarding data while waiting for it must not
  17408. // throw away a partial boundary sitting at the end of the buffer.
  17409. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17410. "zz\r\n"
  17411. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17412. "\r\n"
  17413. "text1"
  17414. "\r\n--zzzz--\r\n");
  17415. }
  17416. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17417. // The received boundary was only checked for being non-empty, so it could be
  17418. // as long as a header is allowed to be. The parser scans the body for
  17419. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17420. // costs a nearly full comparison at nearly every position, making the
  17421. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17422. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17423. Server svr;
  17424. svr.Post("/post", [](const Request &req, Response &res) {
  17425. EXPECT_EQ(1u, req.form.fields.size());
  17426. EXPECT_EQ("text1", req.form.get_field("text1"));
  17427. res.set_content("ok", "text/plain");
  17428. });
  17429. auto port = svr.bind_to_any_port(HOST);
  17430. thread t = thread([&] { svr.listen_after_bind(); });
  17431. auto se = detail::scope_exit([&] {
  17432. svr.stop();
  17433. t.join();
  17434. ASSERT_FALSE(svr.is_running());
  17435. });
  17436. svr.wait_until_ready();
  17437. Client cli(HOST, port);
  17438. auto post_with_boundary_of_length = [&](size_t len) {
  17439. const std::string boundary(len, 'a');
  17440. const std::string body =
  17441. "--" + boundary +
  17442. "\r\n"
  17443. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17444. "\r\n"
  17445. "text1"
  17446. "\r\n--" +
  17447. boundary + "--\r\n";
  17448. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17449. };
  17450. auto res = post_with_boundary_of_length(70);
  17451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17452. EXPECT_EQ(StatusCode::OK_200, res->status);
  17453. res = post_with_boundary_of_length(71);
  17454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17455. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17456. }
  17457. TEST(MakeFileBodyTest, Basic) {
  17458. const std::string file_content(4096, 'Z');
  17459. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17460. {
  17461. std::ofstream ofs(tmp_path, std::ios::binary);
  17462. ofs.write(file_content.data(),
  17463. static_cast<std::streamsize>(file_content.size()));
  17464. }
  17465. auto handled = false;
  17466. Server svr;
  17467. svr.Post("/upload", [&](const Request &req, Response &res) {
  17468. EXPECT_EQ(file_content, req.body);
  17469. handled = true;
  17470. res.status = StatusCode::OK_200;
  17471. });
  17472. auto port = svr.bind_to_any_port(HOST);
  17473. auto t = thread([&] { svr.listen_after_bind(); });
  17474. auto se = detail::scope_exit([&] {
  17475. svr.stop();
  17476. t.join();
  17477. ASSERT_FALSE(svr.is_running());
  17478. ASSERT_TRUE(handled);
  17479. std::remove(tmp_path.c_str());
  17480. });
  17481. svr.wait_until_ready();
  17482. auto fb = make_file_body(tmp_path);
  17483. ASSERT_GT(fb.first, 0u);
  17484. Client cli(HOST, port);
  17485. auto res =
  17486. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17488. EXPECT_EQ(StatusCode::OK_200, res->status);
  17489. }
  17490. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17491. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17492. {
  17493. std::ofstream ofs(path, std::ios::binary);
  17494. const std::string content(100, 'A');
  17495. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17496. }
  17497. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17498. auto body = make_file_body(path);
  17499. ASSERT_EQ(100u, body.first);
  17500. ASSERT_TRUE(static_cast<bool>(body.second));
  17501. // Rewritten shorter after its length was measured - and, on a server, after
  17502. // that length has already gone out as Content-Length.
  17503. {
  17504. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17505. const std::string content(10, 'A');
  17506. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17507. }
  17508. std::string written;
  17509. DataSink sink;
  17510. sink.write = [&](const char *d, size_t l) {
  17511. written.append(d, l);
  17512. return true;
  17513. };
  17514. // The provider has to report failure. write_content_with_progress() advances
  17515. // its offset only by what was written, so a provider that returns true
  17516. // without completing the length it promised is called again straight away,
  17517. // and again.
  17518. EXPECT_FALSE(body.second(0, body.first, sink));
  17519. EXPECT_EQ(std::string(10, 'A'), written);
  17520. }
  17521. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17522. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17523. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17524. {
  17525. std::ofstream ofs(path, std::ios::binary);
  17526. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17527. }
  17528. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17529. auto body = make_file_body(path);
  17530. ASSERT_EQ(content.size(), body.first);
  17531. ASSERT_TRUE(static_cast<bool>(body.second));
  17532. std::string written;
  17533. DataSink sink;
  17534. sink.write = [&](const char *d, size_t l) {
  17535. written.append(d, l);
  17536. return true;
  17537. };
  17538. EXPECT_TRUE(body.second(0, body.first, sink));
  17539. EXPECT_EQ(content, written);
  17540. }
  17541. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17542. static constexpr unsigned int number_of_tasks{1000000};
  17543. std::atomic_uint count{0};
  17544. std::unique_ptr<TaskQueue> task_queue{
  17545. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17546. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17547. auto queued = task_queue->enqueue(
  17548. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17549. EXPECT_TRUE(queued);
  17550. }
  17551. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17552. task_queue->shutdown();
  17553. #else
  17554. EXPECT_NO_THROW(task_queue->shutdown());
  17555. #endif
  17556. EXPECT_EQ(number_of_tasks, count.load());
  17557. }
  17558. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17559. static constexpr unsigned int number_of_tasks{1000000};
  17560. static constexpr unsigned int qlimit{2};
  17561. unsigned int queued_count{0};
  17562. std::atomic_uint count{0};
  17563. std::unique_ptr<TaskQueue> task_queue{
  17564. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17565. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17566. if (task_queue->enqueue(
  17567. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17568. queued_count++;
  17569. }
  17570. }
  17571. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17572. task_queue->shutdown();
  17573. #else
  17574. EXPECT_NO_THROW(task_queue->shutdown());
  17575. #endif
  17576. EXPECT_EQ(queued_count, count.load());
  17577. EXPECT_TRUE(queued_count <= number_of_tasks);
  17578. EXPECT_TRUE(queued_count >= qlimit);
  17579. }
  17580. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17581. // Use a short idle timeout so a dynamic thread spawns, times out and
  17582. // exits during the test, and the pool keeps working afterwards.
  17583. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17584. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17585. /*idle_timeout_sec=*/1}};
  17586. std::atomic_uint count{0};
  17587. std::condition_variable cv;
  17588. std::mutex mtx;
  17589. bool release = false;
  17590. // Block the base thread so the second task spawns a dynamic thread.
  17591. EXPECT_TRUE(task_queue->enqueue([&] {
  17592. std::unique_lock<std::mutex> lock(mtx);
  17593. while (!release) {
  17594. cv.wait(lock);
  17595. }
  17596. count++;
  17597. }));
  17598. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17599. // Let the dynamic thread finish its task and exceed the idle timeout.
  17600. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17601. {
  17602. std::unique_lock<std::mutex> lock(mtx);
  17603. release = true;
  17604. }
  17605. cv.notify_all();
  17606. // The pool must still accept and run tasks after the dynamic thread exited.
  17607. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17608. task_queue->shutdown();
  17609. EXPECT_EQ(3u, count.load());
  17610. }
  17611. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17612. static constexpr size_t number_of_tasks{32};
  17613. std::unique_ptr<TaskQueue> task_queue{
  17614. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17615. // Let the base threads go idle so the burst below finds them waiting.
  17616. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17617. std::mutex mtx;
  17618. std::condition_variable cv;
  17619. size_t running = 0;
  17620. bool release = false;
  17621. for (size_t i = 0; i < number_of_tasks; i++) {
  17622. EXPECT_TRUE(task_queue->enqueue([&] {
  17623. std::unique_lock<std::mutex> lock(mtx);
  17624. running++;
  17625. cv.notify_all();
  17626. cv.wait(lock, [&] { return release; });
  17627. }));
  17628. }
  17629. {
  17630. std::unique_lock<std::mutex> lock(mtx);
  17631. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17632. [&] { return running == number_of_tasks; }));
  17633. release = true;
  17634. }
  17635. cv.notify_all();
  17636. task_queue->shutdown();
  17637. }
  17638. TEST(TaskQueueTest, MaxQueuedRequests) {
  17639. static constexpr unsigned int qlimit{3};
  17640. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17641. std::condition_variable sem_cv;
  17642. std::mutex sem_mtx;
  17643. int credits = 0;
  17644. bool queued;
  17645. /* Fill up the queue with tasks that will block until we give them credits to
  17646. * complete. */
  17647. for (unsigned int n = 0; n <= qlimit;) {
  17648. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17649. std::unique_lock<std::mutex> lock(sem_mtx);
  17650. while (credits <= 0) {
  17651. sem_cv.wait(lock);
  17652. }
  17653. /* Consume the credit and signal the test code if they are all gone. */
  17654. if (--credits == 0) { sem_cv.notify_one(); }
  17655. });
  17656. if (n < qlimit) {
  17657. /* The first qlimit enqueues must succeed. */
  17658. EXPECT_TRUE(queued);
  17659. } else {
  17660. /* The last one will succeed only when the worker thread
  17661. * starts and dequeues the first blocking task. Although
  17662. * not necessary for the correctness of this test, we sleep for
  17663. * a short while to avoid busy waiting. */
  17664. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17665. }
  17666. if (queued) { n++; }
  17667. }
  17668. /* Further enqueues must fail since the queue is full. */
  17669. for (auto i = 0; i < 4; i++) {
  17670. queued = task_queue->enqueue([] {});
  17671. EXPECT_FALSE(queued);
  17672. }
  17673. /* Give the credits to allow the previous tasks to complete. */
  17674. {
  17675. std::unique_lock<std::mutex> lock(sem_mtx);
  17676. credits += qlimit + 1;
  17677. }
  17678. sem_cv.notify_all();
  17679. /* Wait for all the credits to be consumed. */
  17680. {
  17681. std::unique_lock<std::mutex> lock(sem_mtx);
  17682. while (credits > 0) {
  17683. sem_cv.wait(lock);
  17684. }
  17685. }
  17686. /* Check that we are able again to enqueue at least qlimit tasks. */
  17687. for (unsigned int i = 0; i < qlimit; i++) {
  17688. queued = task_queue->enqueue([] {});
  17689. EXPECT_TRUE(queued);
  17690. }
  17691. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17692. task_queue->shutdown();
  17693. #else
  17694. EXPECT_NO_THROW(task_queue->shutdown());
  17695. #endif
  17696. }
  17697. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17698. Server svr;
  17699. std::string method;
  17700. std::string body;
  17701. auto has_content_length = false;
  17702. auto has_transfer_encoding = false;
  17703. std::atomic<int> bad_requests{0};
  17704. // Leftover body bytes get parsed as a malformed request and answered with
  17705. // 400
  17706. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17707. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17708. });
  17709. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17710. res.set_redirect("/down", StatusCode::SeeOther_303);
  17711. });
  17712. svr.Get("/down", [&](const Request &req, Response &res) {
  17713. method = req.method;
  17714. body = req.body;
  17715. has_content_length = req.has_header("Content-Length");
  17716. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17717. res.set_content("ok", "text/plain");
  17718. });
  17719. auto port = svr.bind_to_any_port(HOST);
  17720. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17721. auto se = detail::scope_exit([&] {
  17722. svr.stop();
  17723. thread.join();
  17724. ASSERT_FALSE(svr.is_running());
  17725. });
  17726. svr.wait_until_ready();
  17727. const std::string payload = "SECRET-BODY";
  17728. auto check = [&](Client &cli, const Result &res) {
  17729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17730. EXPECT_EQ(StatusCode::OK_200, res->status);
  17731. EXPECT_EQ("ok", res->body);
  17732. EXPECT_EQ("GET", method);
  17733. EXPECT_TRUE(body.empty());
  17734. EXPECT_FALSE(has_content_length);
  17735. EXPECT_FALSE(has_transfer_encoding);
  17736. // Nothing of the original body may be left on the connection
  17737. auto res2 = cli.Get("/down");
  17738. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17739. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17740. EXPECT_EQ("ok", res2->body);
  17741. EXPECT_EQ(0, bad_requests);
  17742. };
  17743. // With content length
  17744. {
  17745. Client cli(HOST, port);
  17746. cli.set_keep_alive(true);
  17747. cli.set_follow_location(true);
  17748. auto res = cli.Post(
  17749. "/up", payload.size(),
  17750. [&](size_t offset, size_t length, DataSink &sink) {
  17751. return sink.write(payload.data() + offset, length);
  17752. },
  17753. "text/plain");
  17754. check(cli, res);
  17755. }
  17756. // Without content length (chunked)
  17757. {
  17758. Client cli(HOST, port);
  17759. cli.set_keep_alive(true);
  17760. cli.set_follow_location(true);
  17761. auto res = cli.Post(
  17762. "/up",
  17763. [&](size_t /*offset*/, DataSink &sink) {
  17764. sink.write(payload.data(), payload.size());
  17765. sink.done();
  17766. return true;
  17767. },
  17768. "text/plain");
  17769. check(cli, res);
  17770. }
  17771. }
  17772. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17773. Server svr;
  17774. std::string target;
  17775. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17776. // Echo the still-encoded name back in the Location
  17777. const std::string prefix = "/start/";
  17778. res.status = StatusCode::Found_302;
  17779. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17780. });
  17781. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17782. target = req.target;
  17783. res.set_content("ok", "text/plain");
  17784. });
  17785. auto port = svr.bind_to_any_port(HOST);
  17786. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17787. auto se = detail::scope_exit([&] {
  17788. svr.stop();
  17789. thread.join();
  17790. ASSERT_FALSE(svr.is_running());
  17791. });
  17792. svr.wait_until_ready();
  17793. // Decoding the Location path would turn the first four into a path
  17794. // separator, a query delimiter, a fragment delimiter and a different
  17795. // percent-encoded octet. The rest must keep reaching the server as they are.
  17796. const std::vector<std::string> names = {
  17797. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17798. };
  17799. for (auto path_encode : {true, false}) {
  17800. Client cli(HOST, port);
  17801. cli.set_follow_location(true);
  17802. cli.set_path_encode(path_encode);
  17803. for (const auto &name : names) {
  17804. target.clear();
  17805. auto res = cli.Get("/start/" + name);
  17806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17807. EXPECT_EQ(StatusCode::OK_200, res->status);
  17808. EXPECT_EQ("/dest/" + name, target);
  17809. }
  17810. }
  17811. }
  17812. TEST(RedirectTest, NotModifiedIsReturned) {
  17813. Server svr;
  17814. svr.Get("/cached", [](const Request &, Response &res) {
  17815. res.status = StatusCode::NotModified_304;
  17816. });
  17817. auto port = svr.bind_to_any_port(HOST);
  17818. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17819. auto se = detail::scope_exit([&] {
  17820. svr.stop();
  17821. thread.join();
  17822. ASSERT_FALSE(svr.is_running());
  17823. });
  17824. svr.wait_until_ready();
  17825. Client cli(HOST, port);
  17826. cli.set_follow_location(true);
  17827. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17829. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17830. }
  17831. TEST(RedirectTest, NoLocationIsReturned) {
  17832. Server svr;
  17833. svr.Get("/no-location", [](const Request &, Response &res) {
  17834. res.status = StatusCode::Found_302;
  17835. res.set_content("no location", "text/plain");
  17836. });
  17837. auto port = svr.bind_to_any_port(HOST);
  17838. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17839. auto se = detail::scope_exit([&] {
  17840. svr.stop();
  17841. thread.join();
  17842. ASSERT_FALSE(svr.is_running());
  17843. });
  17844. svr.wait_until_ready();
  17845. Client cli(HOST, port);
  17846. cli.set_follow_location(true);
  17847. auto res = cli.Get("/no-location");
  17848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17849. EXPECT_EQ(StatusCode::Found_302, res->status);
  17850. EXPECT_EQ("no location", res->body);
  17851. // The callbacks see the body of the response that is returned
  17852. auto handler_called = false;
  17853. auto progress_called = false;
  17854. std::string body;
  17855. auto res2 = cli.Get(
  17856. "/no-location",
  17857. [&](const Response &) {
  17858. handler_called = true;
  17859. return true;
  17860. },
  17861. [&](const char *data, size_t data_length) {
  17862. body.append(data, data_length);
  17863. return true;
  17864. },
  17865. [&](size_t, size_t) {
  17866. progress_called = true;
  17867. return true;
  17868. });
  17869. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17870. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17871. EXPECT_TRUE(handler_called);
  17872. EXPECT_TRUE(progress_called);
  17873. EXPECT_EQ("no location", body);
  17874. }
  17875. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17876. Server svr;
  17877. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17878. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17879. });
  17880. svr.Get("/hello", [](const Request &req, Response &res) {
  17881. res.set_content(req.get_param_value("key"), "text/plain");
  17882. });
  17883. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17884. auto se = detail::scope_exit([&] {
  17885. svr.stop();
  17886. thread.join();
  17887. ASSERT_FALSE(svr.is_running());
  17888. });
  17889. svr.wait_until_ready();
  17890. {
  17891. Client cli(HOST, PORT);
  17892. cli.set_follow_location(true);
  17893. auto res = cli.Get("/");
  17894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17895. EXPECT_EQ(StatusCode::OK_200, res->status);
  17896. EXPECT_EQ("val&key2=val2", res->body);
  17897. }
  17898. }
  17899. #endif
  17900. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17901. Server svr;
  17902. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17903. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17904. });
  17905. svr.Get("/hello", [](const Request &req, Response &res) {
  17906. res.set_content(req.get_param_value("key"), "text/plain");
  17907. });
  17908. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17909. auto se = detail::scope_exit([&] {
  17910. svr.stop();
  17911. thread.join();
  17912. ASSERT_FALSE(svr.is_running());
  17913. });
  17914. svr.wait_until_ready();
  17915. {
  17916. Client cli(HOST, PORT);
  17917. cli.set_follow_location(true);
  17918. auto res = cli.Get("/");
  17919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17920. EXPECT_EQ(StatusCode::OK_200, res->status);
  17921. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17922. }
  17923. }
  17924. TEST(RedirectTest, RedirectWithPlusInPath) {
  17925. Server svr;
  17926. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17927. res.set_redirect("/a+b");
  17928. });
  17929. // Route pattern uses regex; escape + as \\+
  17930. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17931. res.set_content(req.path, "text/plain");
  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. {
  17941. Client cli(HOST, PORT);
  17942. cli.set_follow_location(true);
  17943. auto res = cli.Get("/");
  17944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17945. EXPECT_EQ(StatusCode::OK_200, res->status);
  17946. EXPECT_EQ("/a+b", res->body);
  17947. }
  17948. }
  17949. TEST(RedirectTest, ResolveRelativeLocation) {
  17950. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17951. const std::vector<std::pair<std::string, std::string>> cases = {
  17952. {"g", "/b/c/g"},
  17953. {"./g", "/b/c/g"},
  17954. {"g/", "/b/c/g/"},
  17955. {"?y", "/b/c/d;p?y"},
  17956. {"g?y", "/b/c/g?y"},
  17957. {"#s", "/b/c/d;p?q#s"},
  17958. {"g#s", "/b/c/g#s"},
  17959. {"g?y#s", "/b/c/g?y#s"},
  17960. {";x", "/b/c/;x"},
  17961. {"g;x", "/b/c/g;x"},
  17962. {".", "/b/c/"},
  17963. {"./", "/b/c/"},
  17964. {"..", "/b/"},
  17965. {"../", "/b/"},
  17966. {"../g", "/b/g"},
  17967. {"../..", "/"},
  17968. {"../../", "/"},
  17969. {"../../g", "/g"},
  17970. {"../../../g", "/g"},
  17971. {"g.", "/b/c/g."},
  17972. {".g", "/b/c/.g"},
  17973. {"g..", "/b/c/g.."},
  17974. {"..g", "/b/c/..g"},
  17975. {"./../g", "/b/g"},
  17976. {"./g/.", "/b/c/g/"},
  17977. {"g/./h", "/b/c/g/h"},
  17978. {"g/../h", "/b/c/h"},
  17979. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17980. {"g;x=1/../y", "/b/c/y"},
  17981. {"g?y/./x", "/b/c/g?y/./x"},
  17982. {"g#s/../x", "/b/c/g#s/../x"},
  17983. // Not relative-path references, so left for parse_url.
  17984. {"/g", "/g"},
  17985. {"//g", "//g"},
  17986. {"http://g/x", "http://g/x"},
  17987. {"g:h", "g:h"},
  17988. };
  17989. for (const auto &c : cases) {
  17990. EXPECT_EQ(c.second,
  17991. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17992. << c.first;
  17993. }
  17994. // A result starting with "//" is still a path, not a network-path reference
  17995. EXPECT_EQ("/.//g",
  17996. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  17997. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  17998. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  17999. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18000. }
  18001. TEST(RedirectTest, RemoveDotSegments) {
  18002. // RFC 3986 section 5.2.4
  18003. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18004. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18005. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18006. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18007. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18008. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18009. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18010. }
  18011. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18012. Server svr;
  18013. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18014. res.set_redirect("/dir/../target?x=1");
  18015. });
  18016. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18017. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18018. "/dir/./../target");
  18019. });
  18020. svr.Get("/target", [](const Request &req, Response &res) {
  18021. res.set_content(req.path, "text/plain");
  18022. });
  18023. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18024. auto se = detail::scope_exit([&] {
  18025. svr.stop();
  18026. th.join();
  18027. ASSERT_FALSE(svr.is_running());
  18028. });
  18029. svr.wait_until_ready();
  18030. Client cli("localhost", PORT);
  18031. cli.set_follow_location(true);
  18032. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18033. auto res = cli.Get(path);
  18034. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18035. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18036. EXPECT_EQ("/target", res->body) << path;
  18037. }
  18038. }
  18039. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18040. Server svr;
  18041. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18042. res.set_redirect(req.get_param_value("to"));
  18043. });
  18044. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18045. res.set_content(req.target, "text/plain");
  18046. });
  18047. svr.Get("/other", [](const Request &req, Response &res) {
  18048. res.set_content(req.target, "text/plain");
  18049. });
  18050. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18051. auto se = detail::scope_exit([&] {
  18052. svr.stop();
  18053. thread.join();
  18054. ASSERT_FALSE(svr.is_running());
  18055. });
  18056. svr.wait_until_ready();
  18057. const std::vector<std::pair<std::string, std::string>> cases = {
  18058. {"next", "/dir/next"},
  18059. {"./next?x=1", "/dir/next?x=1"},
  18060. {"../other", "/other"},
  18061. };
  18062. for (const auto &c : cases) {
  18063. Client cli(HOST, PORT);
  18064. cli.set_follow_location(true);
  18065. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18066. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18067. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18068. EXPECT_EQ(c.second, res->body) << c.first;
  18069. }
  18070. }
  18071. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18072. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18073. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18074. Server other;
  18075. std::atomic<int> other_hits{0};
  18076. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18077. other_hits++;
  18078. res.set_content("other", "text/plain");
  18079. });
  18080. auto other_port = other.bind_to_any_port("127.0.0.1");
  18081. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18082. Server svr;
  18083. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18084. res.set_redirect(req.get_param_value("to"));
  18085. });
  18086. svr.Get(".*", [](const Request &req, Response &res) {
  18087. res.set_content(req.path, "text/plain");
  18088. });
  18089. auto port = svr.bind_to_any_port(HOST);
  18090. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18091. auto se = detail::scope_exit([&] {
  18092. svr.stop();
  18093. thread.join();
  18094. other.stop();
  18095. other_thread.join();
  18096. ASSERT_FALSE(svr.is_running());
  18097. ASSERT_FALSE(other.is_running());
  18098. });
  18099. svr.wait_until_ready();
  18100. other.wait_until_ready();
  18101. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18102. for (const auto &to :
  18103. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18104. Client cli(HOST, port);
  18105. cli.set_follow_location(true);
  18106. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18107. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18108. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18109. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18110. }
  18111. EXPECT_EQ(0, other_hits.load());
  18112. }
  18113. #ifdef CPPHTTPLIB_SSL_ENABLED
  18114. TEST(RedirectTest, Issue2185_Online) {
  18115. SSLClient client("github.com");
  18116. client.set_follow_location(true);
  18117. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18118. "Coollab-Windows.zip");
  18119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18120. EXPECT_EQ(StatusCode::OK_200, res->status);
  18121. EXPECT_EQ(9920427U, res->body.size());
  18122. }
  18123. #endif
  18124. TEST(VulnerabilityTest, CRLFInjection) {
  18125. Server svr;
  18126. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18127. res.set_content("Hello 1", "text/plain");
  18128. });
  18129. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18130. res.set_content("Hello 2", "text/plain");
  18131. });
  18132. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18133. res.set_content("Hello 3", "text/plain");
  18134. });
  18135. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18136. res.set_content("Hello 4", "text/plain");
  18137. });
  18138. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18139. for (const auto &x : req.headers) {
  18140. auto key = x.first;
  18141. EXPECT_STRNE("evil", key.c_str());
  18142. }
  18143. });
  18144. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18145. auto se = detail::scope_exit([&] {
  18146. svr.stop();
  18147. thread.join();
  18148. ASSERT_FALSE(svr.is_running());
  18149. });
  18150. svr.wait_until_ready();
  18151. {
  18152. Client cli(HOST, PORT);
  18153. cli.Post("/test1", "A=B",
  18154. "application/x-www-form-urlencoded\r\nevil: hello1");
  18155. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18156. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18157. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18158. }
  18159. }
  18160. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18161. auto server_thread = std::thread([] {
  18162. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18163. default_socket_options(srv);
  18164. sockaddr_in addr{};
  18165. addr.sin_family = AF_INET;
  18166. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18167. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18168. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18169. ::listen(srv, 1);
  18170. sockaddr_in cli_addr{};
  18171. socklen_t cli_len = sizeof(cli_addr);
  18172. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18173. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18174. std::string buf_all;
  18175. char buf[2048];
  18176. ssize_t n;
  18177. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18178. buf_all.append(buf, static_cast<size_t>(n));
  18179. size_t pos;
  18180. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18181. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18182. auto e = request_block.find("\r\n");
  18183. if (e != std::string::npos) {
  18184. auto request_line = request_block.substr(0, e);
  18185. std::string msg =
  18186. "CRLF injection detected in request line: '" + request_line + "'";
  18187. EXPECT_FALSE(true) << msg;
  18188. }
  18189. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18190. ::send(cli,
  18191. #ifdef _WIN32
  18192. static_cast<const char *>(resp.c_str()),
  18193. static_cast<int>(resp.size()),
  18194. #else
  18195. resp.c_str(), resp.size(),
  18196. #endif
  18197. 0);
  18198. buf_all.erase(0, pos + 4);
  18199. }
  18200. }
  18201. detail::close_socket(cli);
  18202. detail::close_socket(srv);
  18203. });
  18204. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18205. auto cli = Client("127.0.0.1", PORT + 1);
  18206. auto headers = Headers{
  18207. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18208. {"Connection", "keep-alive"}};
  18209. auto res = cli.Get("/hi", headers);
  18210. EXPECT_FALSE(res);
  18211. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18212. server_thread.join();
  18213. }
  18214. // A request rejected before any byte reaches the socket must fail right away
  18215. // instead of waiting for a response the server will never send.
  18216. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18217. // The kernel completes the TCP handshake from the listen backlog, so the
  18218. // client connects, but nothing ever reads, responds or closes.
  18219. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18220. default_socket_options(srv);
  18221. sockaddr_in addr{};
  18222. addr.sin_family = AF_INET;
  18223. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18224. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18225. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18226. ASSERT_EQ(0, ::listen(srv, 8));
  18227. auto cli = Client("127.0.0.1", PORT + 1);
  18228. cli.set_read_timeout(10, 0);
  18229. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18230. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18231. std::chrono::steady_clock::now() - start)
  18232. .count();
  18233. };
  18234. {
  18235. Request req;
  18236. req.method = "GE T";
  18237. req.path = "/";
  18238. auto start = std::chrono::steady_clock::now();
  18239. auto res = cli.send(req);
  18240. EXPECT_FALSE(res);
  18241. EXPECT_EQ(Error::Write, res.error());
  18242. EXPECT_LT(elapsed_ms(start), 1000);
  18243. }
  18244. {
  18245. auto start = std::chrono::steady_clock::now();
  18246. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18247. EXPECT_FALSE(res);
  18248. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18249. EXPECT_LT(elapsed_ms(start), 1000);
  18250. }
  18251. EXPECT_FALSE(cli.is_socket_open());
  18252. detail::close_socket(srv);
  18253. }
  18254. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18255. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18256. default_socket_options(srv);
  18257. sockaddr_in addr{};
  18258. addr.sin_family = AF_INET;
  18259. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18260. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18261. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18262. ASSERT_EQ(0, ::listen(srv, 1));
  18263. std::string received;
  18264. auto server_thread = std::thread([&] {
  18265. auto sock = ::accept(srv, nullptr, nullptr);
  18266. if (sock == INVALID_SOCKET) { return; }
  18267. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18268. char buf[2048];
  18269. ssize_t n;
  18270. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18271. received.append(buf, static_cast<size_t>(n));
  18272. }
  18273. detail::close_socket(sock);
  18274. });
  18275. {
  18276. auto cli = Client("127.0.0.1", PORT + 1);
  18277. // "Z" sorts after the default headers, so writing straight to the socket
  18278. // would have sent the request line and those headers before the rejection.
  18279. auto handle =
  18280. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18281. EXPECT_FALSE(handle.is_valid());
  18282. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18283. }
  18284. server_thread.join();
  18285. detail::close_socket(srv);
  18286. EXPECT_TRUE(received.empty()) << received;
  18287. }
  18288. TEST(PathParamsTest, StaticMatch) {
  18289. const auto pattern = "/users/all";
  18290. detail::PathParamsMatcher matcher(pattern);
  18291. Request request;
  18292. request.path = "/users/all";
  18293. ASSERT_TRUE(matcher.match(request));
  18294. std::unordered_map<std::string, std::string> expected_params = {};
  18295. EXPECT_EQ(request.path_params, expected_params);
  18296. }
  18297. TEST(PathParamsTest, StaticMismatch) {
  18298. const auto pattern = "/users/all";
  18299. detail::PathParamsMatcher matcher(pattern);
  18300. Request request;
  18301. request.path = "/users/1";
  18302. ASSERT_FALSE(matcher.match(request));
  18303. }
  18304. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18305. const auto pattern = "/users/:id/subscriptions";
  18306. detail::PathParamsMatcher matcher(pattern);
  18307. Request request;
  18308. request.path = "/users/42/subscriptions";
  18309. ASSERT_TRUE(matcher.match(request));
  18310. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18311. EXPECT_EQ(request.path_params, expected_params);
  18312. }
  18313. TEST(PathParamsTest, SingleParamInTheEnd) {
  18314. const auto pattern = "/users/:id";
  18315. detail::PathParamsMatcher matcher(pattern);
  18316. Request request;
  18317. request.path = "/users/24";
  18318. ASSERT_TRUE(matcher.match(request));
  18319. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18320. EXPECT_EQ(request.path_params, expected_params);
  18321. }
  18322. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18323. const auto pattern = "/users/:id/";
  18324. detail::PathParamsMatcher matcher(pattern);
  18325. Request request;
  18326. request.path = "/users/42/";
  18327. ASSERT_TRUE(matcher.match(request));
  18328. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18329. EXPECT_EQ(request.path_params, expected_params);
  18330. }
  18331. TEST(PathParamsTest, EmptyParam) {
  18332. const auto pattern = "/users/:id/";
  18333. detail::PathParamsMatcher matcher(pattern);
  18334. Request request;
  18335. request.path = "/users//";
  18336. ASSERT_TRUE(matcher.match(request));
  18337. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18338. EXPECT_EQ(request.path_params, expected_params);
  18339. }
  18340. TEST(PathParamsTest, FragmentMismatch) {
  18341. const auto pattern = "/users/:id/";
  18342. detail::PathParamsMatcher matcher(pattern);
  18343. Request request;
  18344. request.path = "/admins/24/";
  18345. ASSERT_FALSE(matcher.match(request));
  18346. }
  18347. TEST(PathParamsTest, ExtraFragments) {
  18348. const auto pattern = "/users/:id";
  18349. detail::PathParamsMatcher matcher(pattern);
  18350. Request request;
  18351. request.path = "/users/42/subscriptions";
  18352. ASSERT_FALSE(matcher.match(request));
  18353. }
  18354. TEST(PathParamsTest, MissingTrailingParam) {
  18355. const auto pattern = "/users/:id";
  18356. detail::PathParamsMatcher matcher(pattern);
  18357. Request request;
  18358. request.path = "/users";
  18359. ASSERT_FALSE(matcher.match(request));
  18360. }
  18361. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18362. const auto pattern = "/users/:id/subscriptions";
  18363. detail::PathParamsMatcher matcher(pattern);
  18364. Request request;
  18365. request.path = "/users/subscriptions";
  18366. ASSERT_FALSE(matcher.match(request));
  18367. }
  18368. TEST(PathParamsTest, MultipleParams) {
  18369. const auto pattern = "/users/:userid/subscriptions/:subid";
  18370. detail::PathParamsMatcher matcher(pattern);
  18371. Request request;
  18372. request.path = "/users/42/subscriptions/2";
  18373. ASSERT_TRUE(matcher.match(request));
  18374. std::unordered_map<std::string, std::string> expected_params = {
  18375. {"userid", "42"}, {"subid", "2"}};
  18376. EXPECT_EQ(request.path_params, expected_params);
  18377. }
  18378. TEST(PathParamsTest, SequenceOfParams) {
  18379. const auto pattern = "/values/:x/:y/:z";
  18380. detail::PathParamsMatcher matcher(pattern);
  18381. Request request;
  18382. request.path = "/values/1/2/3";
  18383. ASSERT_TRUE(matcher.match(request));
  18384. std::unordered_map<std::string, std::string> expected_params = {
  18385. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18386. EXPECT_EQ(request.path_params, expected_params);
  18387. }
  18388. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18389. const auto pattern = "/prefix:suffix";
  18390. detail::PathParamsMatcher matcher(pattern);
  18391. Request request;
  18392. request.path = "/prefix:suffix";
  18393. ASSERT_TRUE(matcher.match(request));
  18394. const std::unordered_map<std::string, std::string> expected_params = {};
  18395. EXPECT_EQ(request.path_params, expected_params);
  18396. }
  18397. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18398. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18399. // calling thread's stack on a long enough path for a quantified pattern;
  18400. // RegexMatcher must refuse to run regex matching on paths beyond
  18401. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18402. detail::RegexMatcher matcher("/files/(.*)");
  18403. Request within_limit;
  18404. within_limit.path = "/files/" + std::string(10, 'A');
  18405. EXPECT_TRUE(matcher.match(within_limit));
  18406. Request over_limit;
  18407. over_limit.path =
  18408. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18409. EXPECT_FALSE(matcher.match(over_limit));
  18410. }
  18411. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18412. Server svr;
  18413. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18414. res.set_content("ok", "text/plain");
  18415. });
  18416. auto port = svr.bind_to_any_port(HOST);
  18417. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18418. auto se = detail::scope_exit([&] {
  18419. svr.stop();
  18420. thread.join();
  18421. ASSERT_FALSE(svr.is_running());
  18422. });
  18423. svr.wait_until_ready();
  18424. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18425. // request URI limit; this used to be able to crash the process.
  18426. std::string path =
  18427. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18428. std::string req = "GET " + path +
  18429. " HTTP/1.1\r\n"
  18430. "Host: " +
  18431. std::string(HOST) + ":" + std::to_string(port) +
  18432. "\r\n"
  18433. "Connection: close\r\n"
  18434. "\r\n";
  18435. std::string response;
  18436. ASSERT_TRUE(send_request(5, req, &response, port));
  18437. EXPECT_NE(std::string::npos, response.find("404"));
  18438. }
  18439. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18440. Server svr;
  18441. auto handler = [](const Request & /*req*/, Response &res) {
  18442. res.set_content("hit", "text/plain");
  18443. };
  18444. // No regex metacharacter, so this one is compared literally
  18445. svr.Get("/literal/route", handler);
  18446. // '.' is a regex metacharacter, so this one must keep regex semantics
  18447. svr.Get("/a.c", handler);
  18448. auto port = svr.bind_to_any_port(HOST);
  18449. std::thread t([&]() { svr.listen_after_bind(); });
  18450. auto se = detail::scope_exit([&] {
  18451. svr.stop();
  18452. t.join();
  18453. ASSERT_FALSE(svr.is_running());
  18454. });
  18455. svr.wait_until_ready();
  18456. Client cli(HOST, port);
  18457. struct {
  18458. const char *path;
  18459. int status;
  18460. } cases[] = {
  18461. {"/literal/route", StatusCode::OK_200},
  18462. {"/literal/routes", StatusCode::NotFound_404},
  18463. {"/literal/rout", StatusCode::NotFound_404},
  18464. {"/abc", StatusCode::OK_200},
  18465. {"/a.c", StatusCode::OK_200},
  18466. };
  18467. for (const auto &x : cases) {
  18468. auto res = cli.Get(x.path);
  18469. ASSERT_TRUE(res) << x.path;
  18470. EXPECT_EQ(x.status, res->status) << x.path;
  18471. }
  18472. }
  18473. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18474. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18475. // from exhausting the stack, so it must only constrain routes that actually
  18476. // run a regular expression. A literal route is matched by comparison and
  18477. // stays usable at any length.
  18478. Server svr;
  18479. const std::string pattern =
  18480. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18481. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18482. res.set_content("hit", "text/plain");
  18483. });
  18484. auto port = svr.bind_to_any_port(HOST);
  18485. std::thread t([&]() { svr.listen_after_bind(); });
  18486. auto se = detail::scope_exit([&] {
  18487. svr.stop();
  18488. t.join();
  18489. ASSERT_FALSE(svr.is_running());
  18490. });
  18491. svr.wait_until_ready();
  18492. Client cli(HOST, port);
  18493. auto res = cli.Get(pattern);
  18494. ASSERT_TRUE(res);
  18495. EXPECT_EQ(StatusCode::OK_200, res->status);
  18496. }
  18497. TEST(ParseUrlTest, VariousPatterns) {
  18498. {
  18499. detail::UrlComponents uc;
  18500. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18501. EXPECT_EQ("http", uc.scheme);
  18502. EXPECT_EQ("example.com", uc.host);
  18503. EXPECT_EQ("8080", uc.port);
  18504. EXPECT_EQ("/path", uc.path);
  18505. EXPECT_EQ("?q=1", uc.query);
  18506. }
  18507. {
  18508. detail::UrlComponents uc;
  18509. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18510. EXPECT_EQ("https", uc.scheme);
  18511. EXPECT_EQ("example.com", uc.host);
  18512. EXPECT_TRUE(uc.port.empty());
  18513. EXPECT_EQ("/path", uc.path);
  18514. }
  18515. {
  18516. detail::UrlComponents uc;
  18517. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18518. EXPECT_EQ("::1", uc.host);
  18519. EXPECT_EQ("8080", uc.port);
  18520. EXPECT_EQ("/path", uc.path);
  18521. }
  18522. {
  18523. detail::UrlComponents uc;
  18524. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18525. }
  18526. {
  18527. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18528. // the path while the connection still targets the bracketed host.
  18529. detail::UrlComponents uc;
  18530. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18531. }
  18532. {
  18533. detail::UrlComponents uc;
  18534. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18535. }
  18536. {
  18537. detail::UrlComponents uc;
  18538. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18539. EXPECT_EQ("::1", uc.host);
  18540. EXPECT_TRUE(uc.port.empty());
  18541. EXPECT_EQ("/path", uc.path);
  18542. }
  18543. {
  18544. detail::UrlComponents uc;
  18545. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18546. EXPECT_TRUE(uc.scheme.empty());
  18547. EXPECT_EQ("example.com", uc.host);
  18548. EXPECT_EQ("/path", uc.path);
  18549. EXPECT_EQ("?q=1", uc.query);
  18550. }
  18551. {
  18552. detail::UrlComponents uc;
  18553. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18554. EXPECT_TRUE(uc.host.empty());
  18555. EXPECT_EQ("/path", uc.path);
  18556. EXPECT_EQ("?q=1", uc.query);
  18557. }
  18558. {
  18559. detail::UrlComponents uc;
  18560. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18561. EXPECT_EQ("example.com", uc.host);
  18562. EXPECT_EQ("8080", uc.port);
  18563. }
  18564. {
  18565. // Unix socket path — must not be parsed as host
  18566. detail::UrlComponents uc;
  18567. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18568. EXPECT_TRUE(uc.host.empty());
  18569. }
  18570. {
  18571. detail::UrlComponents uc;
  18572. ASSERT_TRUE(detail::parse_url("", uc));
  18573. EXPECT_TRUE(uc.host.empty());
  18574. EXPECT_TRUE(uc.path.empty());
  18575. }
  18576. {
  18577. detail::UrlComponents uc;
  18578. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18579. }
  18580. {
  18581. detail::UrlComponents uc;
  18582. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18583. }
  18584. {
  18585. // Accepted by parse_url; callers restrict to http/https
  18586. detail::UrlComponents uc;
  18587. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18588. EXPECT_EQ("ftp", uc.scheme);
  18589. }
  18590. {
  18591. detail::UrlComponents uc;
  18592. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18593. }
  18594. {
  18595. detail::UrlComponents uc;
  18596. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18597. }
  18598. }
  18599. TEST(ParseUrlTest, FragmentHandling) {
  18600. {
  18601. detail::UrlComponents uc;
  18602. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18603. EXPECT_EQ("/path", uc.path);
  18604. EXPECT_TRUE(uc.query.empty());
  18605. }
  18606. {
  18607. detail::UrlComponents uc;
  18608. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18609. EXPECT_TRUE(uc.path.empty());
  18610. EXPECT_TRUE(uc.query.empty());
  18611. }
  18612. }
  18613. TEST(ParseUrlTest, UserinfoHandling) {
  18614. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18615. // parsers would see evil.com as the host.
  18616. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18617. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18618. for (auto url : urls) {
  18619. detail::UrlComponents uc;
  18620. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18621. }
  18622. }
  18623. TEST(ParseUrlTest, IPv6EdgeCases) {
  18624. {
  18625. detail::UrlComponents uc;
  18626. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18627. EXPECT_TRUE(uc.scheme.empty());
  18628. EXPECT_EQ("::1", uc.host);
  18629. EXPECT_EQ("8080", uc.port);
  18630. }
  18631. {
  18632. // Zone ID '%25' is not in [a-fA-F0-9:]
  18633. detail::UrlComponents uc;
  18634. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18635. }
  18636. }
  18637. TEST(ParseUrlTest, SchemeEdgeCases) {
  18638. {
  18639. detail::UrlComponents uc;
  18640. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18641. }
  18642. {
  18643. detail::UrlComponents uc;
  18644. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18645. }
  18646. {
  18647. detail::UrlComponents uc;
  18648. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18649. }
  18650. }
  18651. TEST(ParseUrlTest, PortEdgeCases) {
  18652. {
  18653. detail::UrlComponents uc;
  18654. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18655. EXPECT_TRUE(uc.port.empty());
  18656. EXPECT_EQ("/path", uc.path);
  18657. }
  18658. {
  18659. // parse_url accepts any port string; validation is done by parse_port
  18660. detail::UrlComponents uc;
  18661. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18662. EXPECT_EQ("abc", uc.port);
  18663. }
  18664. }
  18665. TEST(ParseUrlTest, WebSocketPatterns) {
  18666. {
  18667. detail::UrlComponents uc;
  18668. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18669. EXPECT_EQ("ws", uc.scheme);
  18670. EXPECT_EQ("echo.example.com", uc.host);
  18671. EXPECT_EQ("8080", uc.port);
  18672. EXPECT_EQ("/ws", uc.path);
  18673. }
  18674. {
  18675. detail::UrlComponents uc;
  18676. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18677. EXPECT_EQ("wss", uc.scheme);
  18678. EXPECT_EQ("echo.example.com", uc.host);
  18679. EXPECT_TRUE(uc.port.empty());
  18680. EXPECT_EQ("/ws", uc.path);
  18681. }
  18682. }
  18683. TEST(ParseUrlTest, QueryOnly) {
  18684. detail::UrlComponents uc;
  18685. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18686. EXPECT_TRUE(uc.host.empty());
  18687. EXPECT_TRUE(uc.path.empty());
  18688. EXPECT_EQ("?q=1&r=2", uc.query);
  18689. }
  18690. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18691. detail::UrlComponents uc;
  18692. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18693. EXPECT_TRUE(uc.scheme.empty());
  18694. EXPECT_EQ("example.com", uc.host);
  18695. EXPECT_EQ("443", uc.port);
  18696. EXPECT_EQ("/path", uc.path);
  18697. }
  18698. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18699. // If ipv6 regex working, regex match codepath is taken.
  18700. // else port will default to 80 in Client impl
  18701. int clientImplMagicPort = 80;
  18702. int port = 4321;
  18703. // above ports must be different to avoid false negative
  18704. EXPECT_NE(clientImplMagicPort, port);
  18705. std::string ipV6TestURL = "http://[ff06::c3]";
  18706. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18707. CLIENT_PRIVATE_KEY_FILE);
  18708. EXPECT_EQ(cli.port(), port);
  18709. }
  18710. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18711. auto file_path = "./www/dir/index.html";
  18712. auto dir_path = "./www/dir";
  18713. detail::FileStat stat_file(file_path);
  18714. EXPECT_TRUE(stat_file.is_file());
  18715. EXPECT_FALSE(stat_file.is_dir());
  18716. detail::FileStat stat_dir(dir_path);
  18717. EXPECT_FALSE(stat_dir.is_file());
  18718. EXPECT_TRUE(stat_dir.is_dir());
  18719. }
  18720. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18721. // IPv4 with default HTTP port (80)
  18722. EXPECT_EQ("example.com",
  18723. detail::make_host_and_port_string("example.com", 80, false));
  18724. // IPv4 with default HTTPS port (443)
  18725. EXPECT_EQ("example.com",
  18726. detail::make_host_and_port_string("example.com", 443, true));
  18727. // IPv4 with non-default HTTP port
  18728. EXPECT_EQ("example.com:8080",
  18729. detail::make_host_and_port_string("example.com", 8080, false));
  18730. // IPv4 with non-default HTTPS port
  18731. EXPECT_EQ("example.com:8443",
  18732. detail::make_host_and_port_string("example.com", 8443, true));
  18733. // IPv6 with default HTTP port (80)
  18734. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18735. // IPv6 with default HTTPS port (443)
  18736. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18737. // IPv6 with non-default HTTP port
  18738. EXPECT_EQ("[::1]:8080",
  18739. detail::make_host_and_port_string("::1", 8080, false));
  18740. // IPv6 with non-default HTTPS port
  18741. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18742. // IPv6 full address with default port
  18743. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18744. detail::make_host_and_port_string(
  18745. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18746. // IPv6 full address with non-default port
  18747. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18748. detail::make_host_and_port_string(
  18749. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18750. // IPv6 localhost with non-default port
  18751. EXPECT_EQ("[::1]:3000",
  18752. detail::make_host_and_port_string("::1", 3000, false));
  18753. // IPv6 with zone ID (link-local address) with default port
  18754. EXPECT_EQ("[fe80::1%eth0]",
  18755. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18756. // IPv6 with zone ID (link-local address) with non-default port
  18757. EXPECT_EQ("[fe80::1%eth0]:8080",
  18758. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18759. // Edge case: Port 443 with is_ssl=false (should add port)
  18760. EXPECT_EQ("example.com:443",
  18761. detail::make_host_and_port_string("example.com", 443, false));
  18762. // Edge case: Port 80 with is_ssl=true (should add port)
  18763. EXPECT_EQ("example.com:80",
  18764. detail::make_host_and_port_string("example.com", 80, true));
  18765. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18766. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18767. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18768. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18769. // Security fix: Already bracketed IPv6 should not get double brackets
  18770. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18771. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18772. EXPECT_EQ("[::1]:8080",
  18773. detail::make_host_and_port_string("[::1]", 8080, false));
  18774. EXPECT_EQ("[2001:db8::1]:8080",
  18775. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18776. EXPECT_EQ("[fe80::1%eth0]",
  18777. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18778. EXPECT_EQ("[fe80::1%eth0]:8080",
  18779. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18780. // Edge case: Empty host (should return as-is)
  18781. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18782. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18783. // This is a known limitation but shouldn't crash
  18784. EXPECT_EQ("[host:name]",
  18785. detail::make_host_and_port_string("host:name", 80, false));
  18786. // Port number edge cases (no validation, but should not crash)
  18787. EXPECT_EQ("example.com:0",
  18788. detail::make_host_and_port_string("example.com", 0, false));
  18789. EXPECT_EQ("example.com:-1",
  18790. detail::make_host_and_port_string("example.com", -1, false));
  18791. EXPECT_EQ("example.com:65535",
  18792. detail::make_host_and_port_string("example.com", 65535, false));
  18793. EXPECT_EQ("example.com:65536",
  18794. detail::make_host_and_port_string("example.com", 65536, false));
  18795. }
  18796. namespace httplib {
  18797. namespace detail {
  18798. std::string
  18799. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18800. const std::string &host, int port);
  18801. } // namespace detail
  18802. } // namespace httplib
  18803. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18804. std::map<std::string, std::string> addr_map = {
  18805. {"ipv4.example", "192.0.2.10"},
  18806. {"ipv6.example", "2001:db8::1"},
  18807. {"name.example", "internal.example.lan"},
  18808. {"empty.example", ""}};
  18809. EXPECT_EQ("192.0.2.10:443",
  18810. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18811. EXPECT_EQ("[2001:db8::1]:443",
  18812. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18813. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18814. addr_map, "name.example", 8443));
  18815. // An empty or absent mapping keeps the hostname as the target
  18816. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18817. addr_map, "empty.example", 443));
  18818. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18819. addr_map, "other.example", 443));
  18820. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18821. }
  18822. #ifdef CPPHTTPLIB_SSL_ENABLED
  18823. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18824. httplib::SSLClient cli("roblox.com", 443);
  18825. cli.set_follow_location(true);
  18826. auto res = cli.Get("/");
  18827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18828. EXPECT_EQ(StatusCode::OK_200, res->status);
  18829. }
  18830. #endif
  18831. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18832. Server svr;
  18833. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18834. EXPECT_EQ(res.status, 400);
  18835. });
  18836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18837. auto se = detail::scope_exit([&] {
  18838. svr.stop();
  18839. thread.join();
  18840. ASSERT_FALSE(svr.is_running());
  18841. });
  18842. svr.wait_until_ready();
  18843. Client cli(HOST, PORT);
  18844. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18845. }
  18846. TEST(InvalidHeaderCharsTest, is_field_name) {
  18847. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18848. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18849. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18850. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18851. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18852. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18853. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18854. EXPECT_FALSE(detail::fields::is_field_name(""));
  18855. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18856. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18857. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18858. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18859. }
  18860. TEST(InvalidHeaderCharsTest, is_field_value) {
  18861. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18862. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18863. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18864. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18865. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18866. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18867. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18868. EXPECT_TRUE(detail::fields::is_field_value(""));
  18869. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18870. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18871. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18872. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18873. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18874. }
  18875. TEST(InvalidHeaderCharsTest, OnServer) {
  18876. Server svr;
  18877. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18878. std::string header = "Not Set";
  18879. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18880. res.set_header(header, "value");
  18881. res.set_content("Page Content Page Content", "text/plain");
  18882. });
  18883. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18884. std::string header = "Not Set";
  18885. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18886. res.set_header("X-Test", header);
  18887. res.set_content("Page Content Page Content", "text/plain");
  18888. });
  18889. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18890. auto se = detail::scope_exit([&] {
  18891. svr.stop();
  18892. thread.join();
  18893. ASSERT_FALSE(svr.is_running());
  18894. });
  18895. svr.wait_until_ready();
  18896. Client cli(HOST, PORT);
  18897. {
  18898. auto res = cli.Get(
  18899. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18901. EXPECT_EQ("Page Content Page Content", res->body);
  18902. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18903. }
  18904. {
  18905. auto res = cli.Get(
  18906. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18908. EXPECT_EQ("Page Content Page Content", res->body);
  18909. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18910. }
  18911. }
  18912. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18913. auto handled = false;
  18914. Server svr;
  18915. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18916. thread t = thread([&] { svr.listen(HOST, PORT); });
  18917. auto se = detail::scope_exit([&] {
  18918. svr.stop();
  18919. t.join();
  18920. ASSERT_FALSE(svr.is_running());
  18921. ASSERT_FALSE(handled);
  18922. });
  18923. svr.wait_until_ready();
  18924. auto req = "POST /test HTTP/1.1\r\n"
  18925. "Content-Length: x\r\n"
  18926. "\r\n";
  18927. std::string response;
  18928. ASSERT_TRUE(send_request(1, req, &response));
  18929. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18930. response.substr(0, response.find("\r\n")));
  18931. }
  18932. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18933. // case-insensitive, and a server that receives a 100-continue expectation in
  18934. // an HTTP/1.0 request MUST ignore it.
  18935. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18936. std::string response;
  18937. ASSERT_TRUE(send_request(1, req, &response, port));
  18938. *got_100 = response.find("100 Continue") != std::string::npos;
  18939. }
  18940. class ExpectTokenTest : public ::testing::Test {
  18941. protected:
  18942. void SetUp() override {
  18943. svr_.Post("/p", [](const Request &, Response &res) {
  18944. res.set_content("ok", "text/plain");
  18945. });
  18946. port_ = svr_.bind_to_any_port(HOST);
  18947. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18948. svr_.wait_until_ready();
  18949. }
  18950. void TearDown() override {
  18951. svr_.stop();
  18952. if (thread_.joinable()) { thread_.join(); }
  18953. }
  18954. std::string request(const char *version, const char *expect_value) const {
  18955. return std::string("POST /p ") + version +
  18956. "\r\n"
  18957. "Host: localhost\r\n"
  18958. "Content-Length: 2\r\n"
  18959. "Connection: close\r\n"
  18960. "Expect: " +
  18961. expect_value +
  18962. "\r\n"
  18963. "\r\n"
  18964. "hi";
  18965. }
  18966. Server svr_;
  18967. int port_ = 0;
  18968. thread thread_;
  18969. };
  18970. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18971. bool got_100 = false;
  18972. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18973. EXPECT_TRUE(got_100);
  18974. }
  18975. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18976. bool got_100 = true;
  18977. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18978. EXPECT_FALSE(got_100);
  18979. }
  18980. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18981. bool got_100 = false;
  18982. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18983. EXPECT_TRUE(got_100);
  18984. }
  18985. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18986. bool got_100 = false;
  18987. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18988. EXPECT_TRUE(got_100);
  18989. }
  18990. // `100 Continue` is sent only when the server starts reading the body, so a
  18991. // request rejected before that never invites the client to send it. The
  18992. // requests below carry the expectation but withhold the body, as a client
  18993. // waiting for `100 Continue` would.
  18994. // A POST that expects `100 Continue` and withholds its two-byte body.
  18995. static std::string expect_headers_only(const std::string &path) {
  18996. return "POST " + path +
  18997. " HTTP/1.1\r\n"
  18998. "Host: localhost\r\n"
  18999. "Content-Length: 2\r\n"
  19000. "Expect: 100-continue\r\n"
  19001. "\r\n";
  19002. }
  19003. class ExpectLazyContinueTest : public ::testing::Test {
  19004. protected:
  19005. void SetUp() override {
  19006. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19007. if (req.path == "/pre-routing") {
  19008. res.status = StatusCode::Unauthorized_401;
  19009. return Server::HandlerResponse::Handled;
  19010. }
  19011. return Server::HandlerResponse::Unhandled;
  19012. });
  19013. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19014. if (req.matched_route == "/pre-request") {
  19015. res.status = StatusCode::Forbidden_403;
  19016. return Server::HandlerResponse::Handled;
  19017. }
  19018. return Server::HandlerResponse::Unhandled;
  19019. });
  19020. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19021. res.set_content("ok", "text/plain");
  19022. });
  19023. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19024. res.set_content("ok", "text/plain");
  19025. });
  19026. svr_.Post("/reader-used", [](const Request &, Response &res,
  19027. const ContentReader &content_reader) {
  19028. std::string body;
  19029. content_reader([&](const char *data, size_t len) {
  19030. body.append(data, len);
  19031. return true;
  19032. });
  19033. res.set_content(body, "text/plain");
  19034. });
  19035. svr_.Post("/reader-unused",
  19036. [](const Request &, Response &res, const ContentReader &) {
  19037. res.set_content("ignored", "text/plain");
  19038. });
  19039. port_ = svr_.bind_to_any_port(HOST);
  19040. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19041. svr_.wait_until_ready();
  19042. }
  19043. void TearDown() override {
  19044. svr_.stop();
  19045. if (thread_.joinable()) { thread_.join(); }
  19046. }
  19047. // Sends `req` and reads until the server closes the connection. Returns
  19048. // false if the read had to wait for the client-side timeout instead.
  19049. bool send_until_closed(const std::string &req, std::string *resp) const {
  19050. auto start = std::chrono::steady_clock::now();
  19051. if (!send_request(3, req, resp, port_)) { return false; }
  19052. auto elapsed = std::chrono::steady_clock::now() - start;
  19053. return elapsed < std::chrono::seconds(2);
  19054. }
  19055. // The final response comes without `100 Continue`, and the server closes
  19056. // the connection since the body may or may not follow.
  19057. void expect_final_without_interim(const std::string &path,
  19058. const char *status_line) const {
  19059. std::string resp;
  19060. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19061. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19062. EXPECT_EQ(0u, resp.find(status_line));
  19063. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19064. }
  19065. Server svr_;
  19066. int port_ = 0;
  19067. thread thread_;
  19068. };
  19069. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19070. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19071. }
  19072. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19073. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19074. }
  19075. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19076. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19077. }
  19078. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19079. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19080. }
  19081. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19082. // The body follows once `100 Continue` has had time to arrive.
  19083. auto req = expect_headers_only("/reader-used");
  19084. req.insert(req.size() - 2, "Connection: close\r\n");
  19085. std::string resp;
  19086. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19087. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19088. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19089. EXPECT_NE(std::string::npos, resp.find("hi"));
  19090. }
  19091. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19092. // Large enough for the client to add `Expect: 100-continue` itself.
  19093. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19094. std::atomic<bool> body_sent{false};
  19095. Client cli(HOST, port_);
  19096. auto res = cli.Post(
  19097. "/pre-request", length,
  19098. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19099. body_sent = true;
  19100. std::string chunk(len, 'x');
  19101. sink.write(chunk.data(), chunk.size());
  19102. return true;
  19103. },
  19104. "application/octet-stream");
  19105. ASSERT_TRUE(res);
  19106. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19107. EXPECT_FALSE(body_sent);
  19108. }
  19109. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19110. Server svr;
  19111. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19112. return StatusCode::ExpectationFailed_417;
  19113. });
  19114. svr.Post("/p", [](const Request &, Response &res) {
  19115. res.set_content("ok", "text/plain");
  19116. });
  19117. auto port = svr.bind_to_any_port(HOST);
  19118. thread t = thread([&] { svr.listen_after_bind(); });
  19119. auto se = detail::scope_exit([&] {
  19120. svr.stop();
  19121. t.join();
  19122. });
  19123. svr.wait_until_ready();
  19124. std::string resp;
  19125. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19126. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19127. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19128. // Exactly one response: the route handler must not run after the 417.
  19129. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19130. }
  19131. #ifndef _WIN32
  19132. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19133. static constexpr char reject[] = "Unauthorized";
  19134. static constexpr char accept[] = "Upload accepted";
  19135. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19136. Server svr;
  19137. svr.set_expect_100_continue_handler(
  19138. [](const Request & /*req*/, Response &res) {
  19139. res.status = StatusCode::Unauthorized_401;
  19140. res.set_content(reject, "text/plain");
  19141. return res.status;
  19142. });
  19143. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19144. res.set_content(accept, "text/plain");
  19145. });
  19146. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19147. auto se = detail::scope_exit([&] {
  19148. svr.stop();
  19149. thread.join();
  19150. ASSERT_FALSE(svr.is_running());
  19151. });
  19152. svr.wait_until_ready();
  19153. {
  19154. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19155. curl_easy_init(), &curl_easy_cleanup};
  19156. ASSERT_NE(curl, nullptr);
  19157. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19158. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19159. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19160. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19161. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19162. &curl_slist_free_all};
  19163. ASSERT_NE(list, nullptr);
  19164. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19165. struct read_data {
  19166. uint64_t read_size;
  19167. uint64_t total_size;
  19168. } data = {0, total_size};
  19169. using read_callback_t =
  19170. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19171. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19172. void *userdata) -> size_t {
  19173. read_data *d = (read_data *)userdata;
  19174. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19175. std::fill_n(ptr, size * nmemb, 'A');
  19176. d->read_size += size * nmemb;
  19177. return size * nmemb;
  19178. };
  19179. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19180. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19181. std::vector<char> buffer;
  19182. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19183. using write_callback_t =
  19184. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19185. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19186. void *userdata) -> size_t {
  19187. std::vector<char> *buf = (std::vector<char> *)userdata;
  19188. buf->reserve(buf->size() + size * nmemb + 1);
  19189. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19190. return size * nmemb;
  19191. };
  19192. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19193. {
  19194. const auto res = curl_easy_perform(curl.get());
  19195. ASSERT_EQ(res, CURLE_OK);
  19196. }
  19197. {
  19198. auto response_code = long{};
  19199. const auto res =
  19200. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19201. ASSERT_EQ(res, CURLE_OK);
  19202. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19203. }
  19204. {
  19205. auto dl = curl_off_t{};
  19206. const auto res =
  19207. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19208. ASSERT_EQ(res, CURLE_OK);
  19209. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19210. }
  19211. {
  19212. buffer.push_back('\0');
  19213. ASSERT_STRCASEEQ(buffer.data(), reject);
  19214. }
  19215. }
  19216. }
  19217. #endif
  19218. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19219. // Regression test for #2458.
  19220. //
  19221. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19222. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19223. // ticket can make the client socket spuriously readable during the
  19224. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19225. // the client withholds the body and then blocks reading a response that never
  19226. // comes, failing with `Failed to read connection`.
  19227. //
  19228. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19229. // within the timeout. This raw OpenSSL server deliberately never sends
  19230. // `100 Continue`; the client must still deliver the body and receive 200.
  19231. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19232. signal(SIGPIPE, SIG_IGN);
  19233. const auto port = PORT + 4;
  19234. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19235. ASSERT_NE(srv, INVALID_SOCKET);
  19236. int opt = 1;
  19237. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19238. sockaddr_in addr{};
  19239. addr.sin_family = AF_INET;
  19240. addr.sin_port = htons(static_cast<uint16_t>(port));
  19241. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19242. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19243. ASSERT_EQ(0, ::listen(srv, 1));
  19244. std::atomic<size_t> server_body_bytes{0};
  19245. auto server_thread = std::thread([&] {
  19246. sockaddr_in cli_addr{};
  19247. socklen_t cli_len = sizeof(cli_addr);
  19248. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19249. if (cli == INVALID_SOCKET) { return; }
  19250. // Bound the lifetime of the server side so a buggy client (which never
  19251. // sends the body) cannot make this thread block forever on join.
  19252. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19253. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19254. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19255. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19256. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19257. SSL *ssl = SSL_new(ctx);
  19258. SSL_set_fd(ssl, static_cast<int>(cli));
  19259. if (SSL_accept(ssl) > 0) {
  19260. // Read the request headers. Reading here also flushes the TLS 1.3
  19261. // session tickets to the client. Deliberately do NOT send
  19262. // `100 Continue`.
  19263. std::string buf;
  19264. char tmp[1024];
  19265. while (buf.find("\r\n\r\n") == std::string::npos) {
  19266. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19267. if (n <= 0) { break; }
  19268. buf.append(tmp, static_cast<size_t>(n));
  19269. }
  19270. // A correct client sends the body now; count what arrives.
  19271. auto pos = buf.find("\r\n\r\n");
  19272. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19273. while (body < 4096) {
  19274. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19275. if (n <= 0) { break; }
  19276. body += static_cast<size_t>(n);
  19277. }
  19278. server_body_bytes = body;
  19279. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19280. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19281. SSL_shutdown(ssl);
  19282. }
  19283. SSL_free(ssl);
  19284. detail::close_socket(cli);
  19285. SSL_CTX_free(ctx);
  19286. });
  19287. auto se = detail::scope_exit([&] {
  19288. server_thread.join();
  19289. detail::close_socket(srv);
  19290. });
  19291. SSLClient cli("127.0.0.1", port);
  19292. cli.enable_server_certificate_verification(false);
  19293. cli.set_connection_timeout(5, 0);
  19294. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19295. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19296. std::string body(4096, 'A');
  19297. auto res = cli.Put("/api/test", body, "application/json");
  19298. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19299. EXPECT_EQ(StatusCode::OK_200, res->status);
  19300. EXPECT_EQ(body.size(), server_body_bytes.load());
  19301. }
  19302. #endif
  19303. template <typename S, typename C>
  19304. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19305. svr.Get("/stream", [&](const Request &, Response &res) {
  19306. auto data = new std::string("01234567890123456789");
  19307. res.set_content_provider(
  19308. data->size(), "text/plain",
  19309. [&, data](size_t offset, size_t length, DataSink &sink) {
  19310. const size_t DATA_CHUNK_SIZE = 4;
  19311. const auto &d = *data;
  19312. std::this_thread::sleep_for(std::chrono::seconds(1));
  19313. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19314. return true;
  19315. },
  19316. [data](bool success) {
  19317. EXPECT_FALSE(success);
  19318. delete data;
  19319. });
  19320. });
  19321. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19322. auto i = new size_t(0);
  19323. res.set_content_provider(
  19324. "text/plain",
  19325. [i](size_t, DataSink &sink) {
  19326. if (*i < 5) {
  19327. std::this_thread::sleep_for(std::chrono::seconds(1));
  19328. sink.write("abcd", 4);
  19329. (*i)++;
  19330. } else {
  19331. sink.done();
  19332. }
  19333. return true;
  19334. },
  19335. [i](bool success) {
  19336. EXPECT_FALSE(success);
  19337. delete i;
  19338. });
  19339. });
  19340. svr.Get("/chunked", [&](const Request &, Response &res) {
  19341. auto i = new size_t(0);
  19342. res.set_chunked_content_provider(
  19343. "text/plain",
  19344. [i](size_t, DataSink &sink) {
  19345. if (*i < 5) {
  19346. std::this_thread::sleep_for(std::chrono::seconds(1));
  19347. sink.os << "abcd";
  19348. (*i)++;
  19349. } else {
  19350. sink.done();
  19351. }
  19352. return true;
  19353. },
  19354. [i](bool success) {
  19355. EXPECT_FALSE(success);
  19356. delete i;
  19357. });
  19358. });
  19359. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19360. auto se = detail::scope_exit([&] {
  19361. svr.stop();
  19362. listen_thread.join();
  19363. ASSERT_FALSE(svr.is_running());
  19364. });
  19365. svr.wait_until_ready();
  19366. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19367. {
  19368. auto start = std::chrono::steady_clock::now();
  19369. auto res = cli.Get("/stream");
  19370. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19371. std::chrono::steady_clock::now() - start)
  19372. .count();
  19373. ASSERT_FALSE(res);
  19374. EXPECT_EQ(Error::Read, res.error());
  19375. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19376. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19377. }
  19378. {
  19379. auto start = std::chrono::steady_clock::now();
  19380. auto res = cli.Get("/stream_without_length");
  19381. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19382. std::chrono::steady_clock::now() - start)
  19383. .count();
  19384. ASSERT_FALSE(res);
  19385. EXPECT_EQ(Error::Read, res.error());
  19386. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19387. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19388. }
  19389. {
  19390. auto start = std::chrono::steady_clock::now();
  19391. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19392. EXPECT_EQ("abcd", string(data, data_length));
  19393. return true;
  19394. });
  19395. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19396. std::chrono::steady_clock::now() - start)
  19397. .count();
  19398. ASSERT_FALSE(res);
  19399. EXPECT_EQ(Error::Read, res.error());
  19400. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19401. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19402. }
  19403. }
  19404. TEST(MaxTimeoutTest, ContentStream) {
  19405. time_t timeout = 2000;
  19406. time_t threshold = 200;
  19407. Server svr;
  19408. Client cli("localhost", PORT);
  19409. max_timeout_test(svr, cli, timeout, threshold);
  19410. }
  19411. #ifdef CPPHTTPLIB_SSL_ENABLED
  19412. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19413. time_t timeout = 2000;
  19414. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19416. SSLClient cli("localhost", PORT);
  19417. cli.enable_server_certificate_verification(false);
  19418. max_timeout_test(svr, cli, timeout, threshold);
  19419. }
  19420. #endif
  19421. class EventDispatcher {
  19422. public:
  19423. EventDispatcher() {}
  19424. bool wait_event(DataSink *sink) {
  19425. unique_lock<mutex> lk(m_);
  19426. int id = id_;
  19427. // Wait with timeout to prevent hanging if client disconnects
  19428. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19429. [&] { return cid_ == id; })) {
  19430. return false; // Timeout occurred
  19431. }
  19432. sink->write(message_.data(), message_.size());
  19433. return true;
  19434. }
  19435. void send_event(const string &message) {
  19436. lock_guard<mutex> lk(m_);
  19437. cid_ = id_++;
  19438. message_ = message;
  19439. cv_.notify_all();
  19440. }
  19441. private:
  19442. mutex m_;
  19443. condition_variable cv_;
  19444. atomic_int id_{0};
  19445. atomic_int cid_{-1};
  19446. string message_;
  19447. };
  19448. TEST(ClientInThreadTest, Issue2068) {
  19449. EventDispatcher ed;
  19450. Server svr;
  19451. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19452. res.set_chunked_content_provider("text/event-stream",
  19453. [&](size_t /*offset*/, DataSink &sink) {
  19454. return ed.wait_event(&sink);
  19455. });
  19456. });
  19457. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19458. svr.wait_until_ready();
  19459. thread event_thread([&] {
  19460. int id = 0;
  19461. while (svr.is_running()) {
  19462. this_thread::sleep_for(chrono::milliseconds(500));
  19463. std::stringstream ss;
  19464. ss << "data: " << id << "\n\n";
  19465. ed.send_event(ss.str());
  19466. id++;
  19467. }
  19468. });
  19469. auto se = detail::scope_exit([&] {
  19470. svr.stop();
  19471. listen_thread.join();
  19472. event_thread.join();
  19473. ASSERT_FALSE(svr.is_running());
  19474. });
  19475. {
  19476. auto client = detail::make_unique<Client>(HOST, PORT);
  19477. client->set_read_timeout(std::chrono::minutes(10));
  19478. std::atomic<bool> stop{false};
  19479. std::thread t([&] {
  19480. client->Get("/event1",
  19481. [&](const char *, size_t) -> bool { return !stop; });
  19482. });
  19483. std::this_thread::sleep_for(std::chrono::seconds(2));
  19484. stop = true;
  19485. client->stop();
  19486. t.join();
  19487. // Reset client after thread has finished
  19488. client.reset();
  19489. }
  19490. }
  19491. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19492. auto handled = false;
  19493. Server svr;
  19494. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  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. ASSERT_FALSE(handled);
  19501. });
  19502. svr.wait_until_ready();
  19503. // Two Content-Length headers with different values — must be rejected
  19504. auto req = "POST /test HTTP/1.1\r\n"
  19505. "Content-Length: 5\r\n"
  19506. "Content-Length: 10\r\n"
  19507. "\r\n"
  19508. "hello";
  19509. std::string response;
  19510. ASSERT_TRUE(send_request(1, req, &response));
  19511. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19512. response.substr(0, response.find("\r\n")));
  19513. }
  19514. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19515. auto handled = false;
  19516. Server svr;
  19517. svr.Post("/test", [&](const Request &, Response &res) {
  19518. handled = true;
  19519. res.set_content("ok", "text/plain");
  19520. });
  19521. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19522. auto se = detail::scope_exit([&] {
  19523. svr.stop();
  19524. t.join();
  19525. ASSERT_FALSE(svr.is_running());
  19526. ASSERT_TRUE(handled);
  19527. });
  19528. svr.wait_until_ready();
  19529. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19530. auto req = "POST /test HTTP/1.1\r\n"
  19531. "Host: localhost\r\n"
  19532. "Content-Length: 5\r\n"
  19533. "Content-Length: 5\r\n"
  19534. "\r\n"
  19535. "hello";
  19536. std::string response;
  19537. ASSERT_TRUE(send_request(1, req, &response));
  19538. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19539. }
  19540. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19541. Server svr;
  19542. svr.Get("/test", [](const Request &, Response &res) {
  19543. res.set_content("ok", "text/plain");
  19544. });
  19545. auto port = svr.bind_to_any_port(HOST);
  19546. thread t = thread([&] { svr.listen_after_bind(); });
  19547. auto se = detail::scope_exit([&] {
  19548. svr.stop();
  19549. t.join();
  19550. ASSERT_FALSE(svr.is_running());
  19551. });
  19552. svr.wait_until_ready();
  19553. auto status_line = [&](const std::string &host_lines) {
  19554. std::string res;
  19555. send_request(
  19556. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19557. &res, port);
  19558. return res.substr(0, res.find("\r\n"));
  19559. };
  19560. const char *accepted[] = {
  19561. "Host: localhost\r\n",
  19562. "Host: a.example:8080\r\n",
  19563. "Host: my_service\r\n",
  19564. "Host: [::1]:8080\r\n",
  19565. "Host: [fe80::1%25eth0]\r\n",
  19566. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19567. };
  19568. for (auto host_lines : accepted) {
  19569. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19570. }
  19571. const char *rejected[] = {
  19572. "Host: a.example\r\nHost: b.example\r\n",
  19573. "Host: a.example\r\nHost: a.example\r\n",
  19574. "Host: a@b.example\r\n",
  19575. "Host: a.example/b\r\n",
  19576. "Host: a.example\\b\r\n",
  19577. "Host: a.example?b\r\n",
  19578. "Host: a.example#b\r\n",
  19579. "Host: a.example b.example\r\n",
  19580. };
  19581. for (auto host_lines : rejected) {
  19582. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19583. << host_lines;
  19584. }
  19585. }
  19586. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19587. Server svr;
  19588. svr.Get("/", [](const Request &req, Response &res) {
  19589. EXPECT_EQ(2U, req.trailers.size());
  19590. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19591. // Denied
  19592. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19593. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19594. // Accepted
  19595. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19596. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19597. EXPECT_TRUE(req.has_trailer("X-World"));
  19598. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19599. res.set_content("ok", "text/plain");
  19600. });
  19601. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19602. auto se = detail::scope_exit([&] {
  19603. svr.stop();
  19604. t.join();
  19605. ASSERT_FALSE(svr.is_running());
  19606. });
  19607. svr.wait_until_ready();
  19608. const std::string req = "GET / HTTP/1.1\r\n"
  19609. "Transfer-Encoding: chunked\r\n"
  19610. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19611. "\r\n"
  19612. "0\r\n"
  19613. "Content-Length: 10\r\n"
  19614. "Host: internal.local\r\n"
  19615. "Content-Type: malicious/content\r\n"
  19616. "Cookie: any\r\n"
  19617. "Set-Cookie: any\r\n"
  19618. "X-Forwarded-For: attacker.com\r\n"
  19619. "X-Real-Ip: 1.1.1.1\r\n"
  19620. "X-Hello: hello\r\n"
  19621. "X-World: world\r\n"
  19622. "\r\n";
  19623. std::string res;
  19624. ASSERT_TRUE(send_request(1, req, &res));
  19625. }
  19626. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19627. // several field lines, and the combined value is what has to be parsed. A
  19628. // Trailer field split across lines therefore declares every name it lists;
  19629. // reading only the first line silently drops the trailers the later lines
  19630. // declare. The prohibited-trailer filter still applies to every line.
  19631. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19632. Server svr;
  19633. size_t observed_trailer_count = 0;
  19634. std::string observed_hello;
  19635. std::string observed_world;
  19636. bool observed_content_length = true;
  19637. svr.Get("/", [&](const Request &req, Response &res) {
  19638. observed_trailer_count = req.trailers.size();
  19639. observed_hello = req.get_trailer_value("X-Hello");
  19640. observed_world = req.get_trailer_value("X-World");
  19641. observed_content_length = req.has_trailer("Content-Length");
  19642. res.set_content("ok", "text/plain");
  19643. });
  19644. auto port = svr.bind_to_any_port(HOST);
  19645. thread t = thread([&]() { svr.listen_after_bind(); });
  19646. auto se = detail::scope_exit([&] {
  19647. svr.stop();
  19648. t.join();
  19649. ASSERT_FALSE(svr.is_running());
  19650. });
  19651. svr.wait_until_ready();
  19652. const std::string req = "GET / HTTP/1.1\r\n"
  19653. "Host: localhost\r\n"
  19654. "Transfer-Encoding: chunked\r\n"
  19655. "Trailer: X-Hello\r\n"
  19656. "Trailer: X-World, Content-Length\r\n"
  19657. "\r\n"
  19658. "0\r\n"
  19659. "X-Hello: hello\r\n"
  19660. "X-World: world\r\n"
  19661. "Content-Length: 10\r\n"
  19662. "\r\n";
  19663. std::string res;
  19664. ASSERT_TRUE(send_request(1, req, &res, port));
  19665. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19666. // Accepted: both field lines contribute to the declared set
  19667. EXPECT_EQ(2U, observed_trailer_count);
  19668. EXPECT_EQ(observed_hello, "hello");
  19669. EXPECT_EQ(observed_world, "world");
  19670. // Denied: a prohibited name stays prohibited on a later field line
  19671. EXPECT_FALSE(observed_content_length);
  19672. }
  19673. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19674. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19675. // unbounded run of fields that are never declared, because the counter would
  19676. // only advance for declared fields.
  19677. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19678. Server svr;
  19679. bool handler_called = false;
  19680. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19681. handler_called = true;
  19682. res.set_content("ok", "text/plain");
  19683. });
  19684. auto port = svr.bind_to_any_port(HOST);
  19685. thread t = thread([&]() { svr.listen_after_bind(); });
  19686. auto se = detail::scope_exit([&] {
  19687. svr.stop();
  19688. t.join();
  19689. ASSERT_FALSE(svr.is_running());
  19690. });
  19691. svr.wait_until_ready();
  19692. // Declare nothing, then send far more undeclared trailer fields than the
  19693. // header-count limit. Parsing must stop and reject the request rather than
  19694. // read every line.
  19695. std::string req = "GET / HTTP/1.1\r\n"
  19696. "Transfer-Encoding: chunked\r\n"
  19697. "\r\n"
  19698. "0\r\n";
  19699. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19700. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19701. }
  19702. req += "\r\n";
  19703. std::string res;
  19704. ASSERT_TRUE(send_request(1, req, &res, port));
  19705. // The request is rejected before the handler runs.
  19706. EXPECT_FALSE(handler_called);
  19707. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19708. }
  19709. // The set of declared trailer names is capped so a peer cannot grow it without
  19710. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19711. // declared past the cap is not honored, even if the field is actually sent.
  19712. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19713. Server svr;
  19714. // One name inside the cap and one past it, so the test tracks the cap rather
  19715. // than a fixed count.
  19716. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19717. const std::string within_cap_name = "X-T-0";
  19718. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19719. bool observed_within_cap = false;
  19720. bool observed_past_cap = false;
  19721. svr.Get("/", [&](const Request &req, Response &res) {
  19722. observed_within_cap = req.has_trailer(within_cap_name);
  19723. observed_past_cap = req.has_trailer(past_cap_name);
  19724. res.set_content("ok", "text/plain");
  19725. });
  19726. auto port = svr.bind_to_any_port(HOST);
  19727. thread t = thread([&]() { svr.listen_after_bind(); });
  19728. auto se = detail::scope_exit([&] {
  19729. svr.stop();
  19730. t.join();
  19731. ASSERT_FALSE(svr.is_running());
  19732. });
  19733. svr.wait_until_ready();
  19734. // Declare more trailer names than the cap in a single Trailer field, then
  19735. // actually send the first (within the cap) and the last (past it).
  19736. std::string trailer_decl = "Trailer: ";
  19737. for (int i = 0; i < declared_count; i++) {
  19738. if (i != 0) { trailer_decl += ", "; }
  19739. trailer_decl += "X-T-" + std::to_string(i);
  19740. }
  19741. trailer_decl += "\r\n";
  19742. const std::string req = "GET / HTTP/1.1\r\n"
  19743. "Host: localhost\r\n"
  19744. "Transfer-Encoding: chunked\r\n" +
  19745. trailer_decl +
  19746. "\r\n"
  19747. "0\r\n" +
  19748. within_cap_name + ": a\r\n" + past_cap_name +
  19749. ": b\r\n"
  19750. "\r\n";
  19751. std::string res;
  19752. ASSERT_TRUE(send_request(1, req, &res, port));
  19753. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19754. // A name within the cap is honored; one declared past the cap is dropped.
  19755. EXPECT_TRUE(observed_within_cap);
  19756. EXPECT_FALSE(observed_past_cap);
  19757. }
  19758. // A direct client that is not listed in trusted_proxies must not be able to
  19759. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19760. // the peer address on the actual TCP connection determines whether the
  19761. // header is honored.
  19762. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19763. Server svr;
  19764. // Deliberately does NOT include the loopback address the test client
  19765. // actually connects from, so the direct connection is not a trusted proxy.
  19766. svr.set_trusted_proxies({"203.0.113.66"});
  19767. std::string observed_remote_addr;
  19768. svr.Get("/ip", [&](const Request &req, Response &res) {
  19769. observed_remote_addr = req.remote_addr;
  19770. res.set_content("ok", "text/plain");
  19771. });
  19772. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19773. auto se = detail::scope_exit([&] {
  19774. svr.stop();
  19775. t.join();
  19776. ASSERT_FALSE(svr.is_running());
  19777. });
  19778. svr.wait_until_ready();
  19779. Client cli(HOST, PORT);
  19780. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19782. EXPECT_EQ(StatusCode::OK_200, res->status);
  19783. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19784. // ignored entirely and the real connection-level address retained.
  19785. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19786. observed_remote_addr == "127.0.0.1");
  19787. }
  19788. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19789. Server svr;
  19790. std::string observed_remote_addr;
  19791. std::string observed_xff;
  19792. svr.Get("/ip", [&](const Request &req, Response &res) {
  19793. observed_remote_addr = req.remote_addr;
  19794. observed_xff = req.get_header_value("X-Forwarded-For");
  19795. res.set_content("ok", "text/plain");
  19796. });
  19797. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19798. auto se = detail::scope_exit([&] {
  19799. svr.stop();
  19800. t.join();
  19801. ASSERT_FALSE(svr.is_running());
  19802. });
  19803. svr.wait_until_ready();
  19804. Client cli(HOST, PORT);
  19805. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19807. EXPECT_EQ(StatusCode::OK_200, res->status);
  19808. EXPECT_EQ(observed_xff, "203.0.113.66");
  19809. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19810. observed_remote_addr == "127.0.0.1");
  19811. }
  19812. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19813. Server svr;
  19814. svr.set_trusted_proxies({"203.0.113.66"});
  19815. std::string observed_remote_addr;
  19816. std::string observed_xff;
  19817. svr.Get("/ip", [&](const Request &req, Response &res) {
  19818. observed_remote_addr = req.remote_addr;
  19819. observed_xff = req.get_header_value("X-Forwarded-For");
  19820. res.set_content("ok", "text/plain");
  19821. });
  19822. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19823. auto se = detail::scope_exit([&] {
  19824. svr.stop();
  19825. t.join();
  19826. ASSERT_FALSE(svr.is_running());
  19827. });
  19828. svr.wait_until_ready();
  19829. Client cli(HOST, PORT);
  19830. auto res = cli.Get("/ip");
  19831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19832. EXPECT_EQ(StatusCode::OK_200, res->status);
  19833. EXPECT_EQ(observed_xff, "");
  19834. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19835. observed_remote_addr == "127.0.0.1");
  19836. }
  19837. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19838. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19839. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19840. Server svr;
  19841. svr.set_trusted_proxies({"127.0.0.1"});
  19842. svr.Get("/ip", [](const Request &req, Response &res) {
  19843. res.set_content(req.remote_addr, "text/plain");
  19844. });
  19845. auto port = svr.bind_to_any_port("::");
  19846. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19847. thread t = thread([&] { svr.listen_after_bind(); });
  19848. auto se = detail::scope_exit([&] {
  19849. svr.stop();
  19850. t.join();
  19851. ASSERT_FALSE(svr.is_running());
  19852. });
  19853. svr.wait_until_ready();
  19854. Client cli("127.0.0.1", port);
  19855. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19857. EXPECT_EQ("198.51.100.23", res->body);
  19858. }
  19859. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19860. Server svr;
  19861. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19862. svr.Get("/ip", [](const Request &req, Response &res) {
  19863. res.set_content(req.remote_addr, "text/plain");
  19864. });
  19865. auto port = svr.bind_to_any_port(HOST);
  19866. ASSERT_GT(port, 0);
  19867. thread t = thread([&] { svr.listen_after_bind(); });
  19868. auto se = detail::scope_exit([&] {
  19869. svr.stop();
  19870. t.join();
  19871. ASSERT_FALSE(svr.is_running());
  19872. });
  19873. svr.wait_until_ready();
  19874. Client cli(HOST, port);
  19875. auto res = cli.Get(
  19876. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19878. EXPECT_EQ("198.51.100.23", res->body);
  19879. }
  19880. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19881. Server svr;
  19882. // Include the loopback address the test client actually connects from, so
  19883. // the direct connection itself is recognized as the trusted proxy hop.
  19884. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19885. std::string observed_remote_addr;
  19886. std::string observed_xff;
  19887. svr.Get("/ip", [&](const Request &req, Response &res) {
  19888. observed_remote_addr = req.remote_addr;
  19889. observed_xff = req.get_header_value("X-Forwarded-For");
  19890. res.set_content("ok", "text/plain");
  19891. });
  19892. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19893. auto se = detail::scope_exit([&] {
  19894. svr.stop();
  19895. t.join();
  19896. ASSERT_FALSE(svr.is_running());
  19897. });
  19898. svr.wait_until_ready();
  19899. Client cli(HOST, PORT);
  19900. auto res = cli.Get(
  19901. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19903. EXPECT_EQ(StatusCode::OK_200, res->status);
  19904. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19905. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19906. }
  19907. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19908. Server svr;
  19909. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19910. std::string observed_remote_addr;
  19911. std::string observed_xff;
  19912. svr.Get("/ip", [&](const Request &req, Response &res) {
  19913. observed_remote_addr = req.remote_addr;
  19914. observed_xff = req.get_header_value("X-Forwarded-For");
  19915. res.set_content("ok", "text/plain");
  19916. });
  19917. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19918. auto se = detail::scope_exit([&] {
  19919. svr.stop();
  19920. t.join();
  19921. ASSERT_FALSE(svr.is_running());
  19922. });
  19923. svr.wait_until_ready();
  19924. Client cli(HOST, PORT);
  19925. auto res = cli.Get(
  19926. "/ip",
  19927. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19929. EXPECT_EQ(StatusCode::OK_200, res->status);
  19930. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19931. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19932. }
  19933. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19934. Server svr;
  19935. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19936. std::string observed_remote_addr;
  19937. std::string observed_xff;
  19938. svr.Get("/ip", [&](const Request &req, Response &res) {
  19939. observed_remote_addr = req.remote_addr;
  19940. observed_xff = req.get_header_value("X-Forwarded-For");
  19941. res.set_content("ok", "text/plain");
  19942. });
  19943. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19944. auto se = detail::scope_exit([&] {
  19945. svr.stop();
  19946. t.join();
  19947. ASSERT_FALSE(svr.is_running());
  19948. });
  19949. svr.wait_until_ready();
  19950. Client cli(HOST, PORT);
  19951. auto res = cli.Get(
  19952. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19954. EXPECT_EQ(StatusCode::OK_200, res->status);
  19955. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19956. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19957. // and must not be selected.
  19958. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19959. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19960. }
  19961. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19962. Server svr;
  19963. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19964. std::string observed_remote_addr;
  19965. svr.Get("/ip", [&](const Request &req, Response &res) {
  19966. observed_remote_addr = req.remote_addr;
  19967. res.set_content("ok", "text/plain");
  19968. });
  19969. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19970. auto se = detail::scope_exit([&] {
  19971. svr.stop();
  19972. t.join();
  19973. ASSERT_FALSE(svr.is_running());
  19974. });
  19975. svr.wait_until_ready();
  19976. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19977. // a forged address and the trusted proxy's own address; the forged value must
  19978. // not win over the address the trusted proxy actually recorded.
  19979. Client cli(HOST, PORT);
  19980. auto res = cli.Get(
  19981. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19983. EXPECT_EQ(StatusCode::OK_200, res->status);
  19984. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19985. }
  19986. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19987. Server svr;
  19988. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19989. std::string observed_remote_addr;
  19990. std::string observed_xff;
  19991. svr.Get("/ip", [&](const Request &req, Response &res) {
  19992. observed_remote_addr = req.remote_addr;
  19993. observed_xff = req.get_header_value("X-Forwarded-For");
  19994. res.set_content("ok", "text/plain");
  19995. });
  19996. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19997. auto se = detail::scope_exit([&] {
  19998. svr.stop();
  19999. t.join();
  20000. ASSERT_FALSE(svr.is_running());
  20001. });
  20002. svr.wait_until_ready();
  20003. Client cli(HOST, PORT);
  20004. auto res = cli.Get(
  20005. "/ip",
  20006. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20008. EXPECT_EQ(StatusCode::OK_200, res->status);
  20009. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20010. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20011. }
  20012. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20013. Server svr;
  20014. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20015. std::string observed_remote_addr;
  20016. std::string observed_xff;
  20017. svr.Get("/ip", [&](const Request &req, Response &res) {
  20018. observed_remote_addr = req.remote_addr;
  20019. observed_xff = req.get_header_value("X-Forwarded-For");
  20020. res.set_content("ok", "text/plain");
  20021. });
  20022. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20023. auto se = detail::scope_exit([&] {
  20024. svr.stop();
  20025. t.join();
  20026. ASSERT_FALSE(svr.is_running());
  20027. });
  20028. svr.wait_until_ready();
  20029. std::string raw_req =
  20030. "GET /ip HTTP/1.1\r\n"
  20031. "Host: localhost\r\n"
  20032. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20033. "Connection: close\r\n"
  20034. "\r\n";
  20035. std::string out;
  20036. ASSERT_TRUE(send_request(5, raw_req, &out));
  20037. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20038. // Header parser trims surrounding whitespace of the header value
  20039. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20040. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20041. }
  20042. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20043. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20044. // their own X-Forwarded-For as a separate field line rather than extending the
  20045. // one the client sent, so every occurrence has to be taken into account.
  20046. // Reading only the first one hands back the address the client chose.
  20047. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20048. Server svr;
  20049. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20050. std::string observed_remote_addr;
  20051. size_t observed_xff_count = 0;
  20052. svr.Get("/ip", [&](const Request &req, Response &res) {
  20053. observed_remote_addr = req.remote_addr;
  20054. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20055. res.set_content("ok", "text/plain");
  20056. });
  20057. auto port = svr.bind_to_any_port(HOST);
  20058. thread t = thread([&]() { svr.listen_after_bind(); });
  20059. auto se = detail::scope_exit([&] {
  20060. svr.stop();
  20061. t.join();
  20062. ASSERT_FALSE(svr.is_running());
  20063. });
  20064. svr.wait_until_ready();
  20065. // The client supplies the first field line; the trusted proxy appends the
  20066. // address it observed as a second one.
  20067. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20068. "Host: localhost\r\n"
  20069. "X-Forwarded-For: 1.2.3.4\r\n"
  20070. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20071. "Connection: close\r\n"
  20072. "\r\n";
  20073. std::string out;
  20074. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20075. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20076. EXPECT_EQ(observed_xff_count, 2U);
  20077. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20078. // The same chain spread over one field line per hop derives the same client
  20079. // address, i.e. the split and the comma-joined representations agree.
  20080. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20081. "Host: localhost\r\n"
  20082. "X-Forwarded-For: 1.2.3.4\r\n"
  20083. "X-Forwarded-For: 198.51.100.23\r\n"
  20084. "X-Forwarded-For: 192.0.2.45\r\n"
  20085. "Connection: close\r\n"
  20086. "\r\n";
  20087. out.clear();
  20088. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20089. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20090. EXPECT_EQ(observed_xff_count, 3U);
  20091. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20092. }
  20093. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20094. // crash the server (it used to call front() on an empty vector inside
  20095. // get_client_ip). The connection-level remote address must be retained instead.
  20096. static void run_malformed_xff_test(const std::string &xff_value) {
  20097. Server svr;
  20098. svr.set_trusted_proxies({"192.0.2.45"});
  20099. std::string observed_remote_addr;
  20100. svr.Get("/ip", [&](const Request &req, Response &res) {
  20101. observed_remote_addr = req.remote_addr;
  20102. res.set_content("ok", "text/plain");
  20103. });
  20104. int port = 0;
  20105. thread t = thread([&]() {
  20106. port = svr.bind_to_any_port(HOST);
  20107. svr.listen_after_bind();
  20108. });
  20109. auto se = detail::scope_exit([&] {
  20110. svr.stop();
  20111. t.join();
  20112. ASSERT_FALSE(svr.is_running());
  20113. });
  20114. svr.wait_until_ready();
  20115. Client cli(HOST, port);
  20116. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20118. EXPECT_EQ(StatusCode::OK_200, res->status);
  20119. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20120. observed_remote_addr == "127.0.0.1");
  20121. }
  20122. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20123. run_malformed_xff_test("");
  20124. }
  20125. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20126. run_malformed_xff_test(",");
  20127. }
  20128. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20129. run_malformed_xff_test(", , ,");
  20130. }
  20131. // The same rule applies to Accept: a request whose acceptable types are spread
  20132. // over several field lines must be negotiated against all of them.
  20133. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20134. // case-insensitive connection options. Comparing the whole field value against
  20135. // one option misses a client that sends several of them, and misses every
  20136. // casing but the one written in the comparison.
  20137. //
  20138. // Sends req, reads the response, then reuses the same socket for a second
  20139. // request to find out whether the server kept the connection.
  20140. static void probe_connection_reuse(int port, const std::string &req,
  20141. bool *announced_close, bool *reusable) {
  20142. auto error = Error::Success;
  20143. auto sock = detail::create_client_socket(
  20144. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20145. /*connection_timeout_sec=*/5, 0,
  20146. /*read_timeout_sec=*/1, 0,
  20147. /*write_timeout_sec=*/5, 0, std::string(), error);
  20148. ASSERT_NE(sock, INVALID_SOCKET);
  20149. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20150. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20151. "Host: localhost\r\n"
  20152. "Connection: close\r\n"
  20153. "\r\n";
  20154. std::string first_response;
  20155. std::string second_response;
  20156. detail::process_client_socket(
  20157. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20158. [&](Stream &strm) {
  20159. if (strm.write(req.data(), req.size()) !=
  20160. static_cast<ssize_t>(req.size())) {
  20161. return false;
  20162. }
  20163. char buf[512];
  20164. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20165. // Headers plus the two-byte body of the handler below
  20166. while (reader.getline()) {
  20167. first_response += reader.ptr();
  20168. if (first_response.find("ok") != std::string::npos) { break; }
  20169. }
  20170. if (strm.write(second.data(), second.size()) !=
  20171. static_cast<ssize_t>(second.size())) {
  20172. return true;
  20173. }
  20174. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20175. while (reader2.getline()) {
  20176. second_response += reader2.ptr();
  20177. if (second_response.find("ok") != std::string::npos) { break; }
  20178. }
  20179. return true;
  20180. });
  20181. *announced_close =
  20182. first_response.find("Connection: close") != std::string::npos;
  20183. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20184. }
  20185. class ConnectionTokenTest : public ::testing::Test {
  20186. protected:
  20187. void SetUp() override {
  20188. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20189. res.set_content("ok", "text/plain");
  20190. });
  20191. port_ = svr_.bind_to_any_port(HOST);
  20192. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20193. svr_.wait_until_ready();
  20194. }
  20195. void TearDown() override {
  20196. svr_.stop();
  20197. if (thread_.joinable()) { thread_.join(); }
  20198. }
  20199. Server svr_;
  20200. int port_ = 0;
  20201. thread thread_;
  20202. };
  20203. // "close" alongside another option still closes the connection, and the
  20204. // response says so rather than leaving the peer to discover it.
  20205. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20206. bool announced_close = false;
  20207. bool reusable = true;
  20208. probe_connection_reuse(port_,
  20209. "GET /keepalive HTTP/1.1\r\n"
  20210. "Host: localhost\r\n"
  20211. "Connection: keep-alive, close\r\n"
  20212. "\r\n",
  20213. &announced_close, &reusable);
  20214. EXPECT_TRUE(announced_close);
  20215. EXPECT_FALSE(reusable);
  20216. }
  20217. // "close" split over two field lines is the same list, so it is honored too.
  20218. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20219. bool announced_close = false;
  20220. bool reusable = true;
  20221. probe_connection_reuse(port_,
  20222. "GET /keepalive HTTP/1.1\r\n"
  20223. "Host: localhost\r\n"
  20224. "Connection: keep-alive\r\n"
  20225. "Connection: close\r\n"
  20226. "\r\n",
  20227. &announced_close, &reusable);
  20228. EXPECT_TRUE(announced_close);
  20229. EXPECT_FALSE(reusable);
  20230. }
  20231. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20232. // keep-alive in the spelling everyone actually sends keeps its connection.
  20233. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20234. bool announced_close = false;
  20235. bool reusable = false;
  20236. probe_connection_reuse(port_,
  20237. "GET /keepalive HTTP/1.0\r\n"
  20238. "Host: localhost\r\n"
  20239. "Connection: keep-alive\r\n"
  20240. "\r\n",
  20241. &announced_close, &reusable);
  20242. EXPECT_FALSE(announced_close);
  20243. EXPECT_TRUE(reusable);
  20244. }
  20245. // A token the value merely contains is not the token itself.
  20246. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20247. bool announced_close = false;
  20248. bool reusable = false;
  20249. probe_connection_reuse(port_,
  20250. "GET /keepalive HTTP/1.1\r\n"
  20251. "Host: localhost\r\n"
  20252. "Connection: notclose\r\n"
  20253. "\r\n",
  20254. &announced_close, &reusable);
  20255. EXPECT_FALSE(announced_close);
  20256. EXPECT_TRUE(reusable);
  20257. }
  20258. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20259. Server svr;
  20260. std::vector<std::string> observed_types;
  20261. svr.Get("/", [&](const Request &req, Response &res) {
  20262. observed_types = req.accept_content_types;
  20263. res.set_content("ok", "text/plain");
  20264. });
  20265. auto port = svr.bind_to_any_port(HOST);
  20266. thread t = thread([&]() { svr.listen_after_bind(); });
  20267. auto se = detail::scope_exit([&] {
  20268. svr.stop();
  20269. t.join();
  20270. ASSERT_FALSE(svr.is_running());
  20271. });
  20272. svr.wait_until_ready();
  20273. Client cli(HOST, port);
  20274. Headers headers;
  20275. headers.emplace("Accept", "text/plain;q=0.5");
  20276. headers.emplace("Accept", "application/json");
  20277. auto res = cli.Get("/", headers);
  20278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20279. EXPECT_EQ(StatusCode::OK_200, res->status);
  20280. // Sorted by q-value, so the second field line's type comes first
  20281. ASSERT_EQ(2U, observed_types.size());
  20282. EXPECT_EQ("application/json", observed_types[0]);
  20283. EXPECT_EQ("text/plain", observed_types[1]);
  20284. }
  20285. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20286. // empty field line must not contribute a bare comma to the combined value.
  20287. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20288. Server svr;
  20289. std::vector<std::string> observed_types;
  20290. svr.Get("/", [&](const Request &req, Response &res) {
  20291. observed_types = req.accept_content_types;
  20292. res.set_content("ok", "text/plain");
  20293. });
  20294. auto port = svr.bind_to_any_port(HOST);
  20295. thread t = thread([&]() { svr.listen_after_bind(); });
  20296. auto se = detail::scope_exit([&] {
  20297. svr.stop();
  20298. t.join();
  20299. ASSERT_FALSE(svr.is_running());
  20300. });
  20301. svr.wait_until_ready();
  20302. // Empty first field line, then a real one
  20303. std::string raw_req = "GET / HTTP/1.1\r\n"
  20304. "Host: localhost\r\n"
  20305. "Accept:\r\n"
  20306. "Accept: application/json\r\n"
  20307. "Connection: close\r\n"
  20308. "\r\n";
  20309. std::string out;
  20310. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20311. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20312. ASSERT_EQ(1U, observed_types.size());
  20313. EXPECT_EQ("application/json", observed_types[0]);
  20314. }
  20315. // The skip in get_combined_header_value() is what keeps an empty field line
  20316. // from contributing a bare comma. Only a trailing empty field line exercises
  20317. // it: a leading one is already covered by the "combined is still empty" check,
  20318. // and parse_accept_header() now ignores the empty element either way, so the
  20319. // request-level test above can no longer tell the two apart.
  20320. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20321. Headers headers;
  20322. headers.emplace("Accept", "text/html");
  20323. headers.emplace("Accept", "");
  20324. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20325. headers.clear();
  20326. headers.emplace("Accept", "");
  20327. headers.emplace("Accept", "application/json");
  20328. EXPECT_EQ("application/json",
  20329. detail::get_combined_header_value(headers, "Accept"));
  20330. }
  20331. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20332. // An encoding offered on a later Accept-Encoding field line is still offered.
  20333. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20334. Server svr;
  20335. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20336. res.set_content(std::string(1024, 'x'), "text/plain");
  20337. });
  20338. auto port = svr.bind_to_any_port(HOST);
  20339. thread t = thread([&]() { svr.listen_after_bind(); });
  20340. auto se = detail::scope_exit([&] {
  20341. svr.stop();
  20342. t.join();
  20343. ASSERT_FALSE(svr.is_running());
  20344. });
  20345. svr.wait_until_ready();
  20346. Client cli(HOST, port);
  20347. cli.set_decompress(false);
  20348. Headers headers;
  20349. headers.emplace("Accept-Encoding", "identity");
  20350. headers.emplace("Accept-Encoding", "gzip");
  20351. auto res = cli.Get("/", headers);
  20352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20353. EXPECT_EQ(StatusCode::OK_200, res->status);
  20354. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20355. }
  20356. #endif
  20357. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20358. // Transfer-Encoding is not its body.
  20359. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20360. Server svr;
  20361. svr.set_payload_max_length(8);
  20362. svr.Post("/test", [](const Request &, Response &res) {
  20363. res.set_content("ok", "text/plain");
  20364. });
  20365. auto port = svr.bind_to_any_port(HOST);
  20366. ASSERT_GT(port, 0);
  20367. thread t = thread([&] { svr.listen_after_bind(); });
  20368. auto se = detail::scope_exit([&] {
  20369. svr.stop();
  20370. t.join();
  20371. ASSERT_FALSE(svr.is_running());
  20372. });
  20373. svr.wait_until_ready();
  20374. std::string resp;
  20375. ASSERT_TRUE(send_request(1,
  20376. "POST /test HTTP/1.1\r\n"
  20377. "Host: localhost\r\n"
  20378. "Connection: close\r\n"
  20379. "\r\n" +
  20380. std::string(16, 'X'),
  20381. &resp, port));
  20382. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20383. }
  20384. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20385. Server svr;
  20386. svr.Post("/post", [&](const Request &req, Response &res) {
  20387. res.set_content(req.body, "text/plain");
  20388. });
  20389. svr.Put("/put", [&](const Request &req, Response &res) {
  20390. res.set_content(req.body, "text/plain");
  20391. });
  20392. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20393. res.set_content(req.body, "text/plain");
  20394. });
  20395. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20396. res.set_content(req.body, "text/plain");
  20397. });
  20398. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20399. auto se = detail::scope_exit([&] {
  20400. svr.stop();
  20401. t.join();
  20402. ASSERT_FALSE(svr.is_running());
  20403. });
  20404. svr.wait_until_ready();
  20405. std::string resp;
  20406. // POST without Content-Length
  20407. ASSERT_TRUE(send_request(5,
  20408. "POST /post HTTP/1.1\r\n"
  20409. "Host: localhost\r\n"
  20410. "Connection: close\r\n"
  20411. "\r\n",
  20412. &resp));
  20413. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20414. // PUT without Content-Length
  20415. resp.clear();
  20416. ASSERT_TRUE(send_request(5,
  20417. "PUT /put HTTP/1.1\r\n"
  20418. "Host: localhost\r\n"
  20419. "Connection: close\r\n"
  20420. "\r\n",
  20421. &resp));
  20422. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20423. // PATCH without Content-Length
  20424. resp.clear();
  20425. ASSERT_TRUE(send_request(5,
  20426. "PATCH /patch HTTP/1.1\r\n"
  20427. "Host: localhost\r\n"
  20428. "Connection: close\r\n"
  20429. "\r\n",
  20430. &resp));
  20431. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20432. // DELETE without Content-Length
  20433. resp.clear();
  20434. ASSERT_TRUE(send_request(5,
  20435. "DELETE /delete HTTP/1.1\r\n"
  20436. "Host: localhost\r\n"
  20437. "Connection: close\r\n"
  20438. "\r\n",
  20439. &resp));
  20440. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20441. }
  20442. //==============================================================================
  20443. // open_stream() Tests
  20444. //==============================================================================
  20445. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20446. std::string result;
  20447. char buf[8192];
  20448. ssize_t n;
  20449. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20450. result.append(buf, static_cast<size_t>(n));
  20451. }
  20452. return result;
  20453. }
  20454. // Mock stream for unit tests
  20455. class MockStream : public Stream {
  20456. public:
  20457. std::string data;
  20458. size_t pos = 0;
  20459. ssize_t error_after = -1; // -1 = no error
  20460. explicit MockStream(const std::string &d, ssize_t err = -1)
  20461. : data(d), error_after(err) {}
  20462. bool is_readable() const override { return true; }
  20463. bool wait_readable() const override { return true; }
  20464. bool wait_writable() const override { return true; }
  20465. ssize_t read(char *ptr, size_t size) override {
  20466. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20467. if (pos >= data.size()) return 0;
  20468. size_t limit =
  20469. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20470. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20471. std::memcpy(ptr, data.data() + pos, to_read);
  20472. pos += to_read;
  20473. return static_cast<ssize_t>(to_read);
  20474. }
  20475. ssize_t write(const char *, size_t) override { return -1; }
  20476. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20477. ip = "127.0.0.1";
  20478. port = 0;
  20479. }
  20480. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20481. ip = "127.0.0.1";
  20482. port = 0;
  20483. }
  20484. socket_t socket() const override { return INVALID_SOCKET; }
  20485. time_t duration() const override { return 0; }
  20486. };
  20487. TEST(StreamHandleTest, Basic) {
  20488. ClientImpl::StreamHandle handle;
  20489. EXPECT_FALSE(handle.is_valid());
  20490. handle.response = detail::make_unique<Response>();
  20491. handle.error = Error::Connection;
  20492. EXPECT_FALSE(handle.is_valid());
  20493. handle.error = Error::Success;
  20494. EXPECT_TRUE(handle.is_valid());
  20495. }
  20496. TEST(BodyReaderTest, Basic) {
  20497. MockStream stream("Hello, World!");
  20498. detail::BodyReader reader;
  20499. reader.stream = &stream;
  20500. reader.content_length = 13;
  20501. char buf[32];
  20502. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20503. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20504. EXPECT_TRUE(reader.eof);
  20505. }
  20506. TEST(BodyReaderTest, NoStream) {
  20507. detail::BodyReader reader;
  20508. char buf[32];
  20509. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20510. EXPECT_EQ(Error::Connection, reader.last_error);
  20511. }
  20512. TEST(BodyReaderTest, Error) {
  20513. MockStream stream("Hello, World!", 5);
  20514. detail::BodyReader reader;
  20515. reader.stream = &stream;
  20516. reader.content_length = 13;
  20517. char buf[32];
  20518. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20519. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20520. EXPECT_EQ(Error::Read, reader.last_error);
  20521. }
  20522. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20523. // Mock-based StreamHandle tests relying on private internals are removed.
  20524. class OpenStreamTest : public ::testing::Test {
  20525. protected:
  20526. void SetUp() override {
  20527. svr_.Get("/hello", [](const Request &, Response &res) {
  20528. res.set_content("Hello World!", "text/plain");
  20529. });
  20530. svr_.Get("/large", [](const Request &, Response &res) {
  20531. res.set_content(std::string(10000, 'X'), "text/plain");
  20532. });
  20533. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20534. res.set_content("Hello World!", "image/jpeg");
  20535. res.set_header("Content-Encoding", "UTF-8");
  20536. });
  20537. svr_.Get("/chunked", [](const Request &, Response &res) {
  20538. res.set_chunked_content_provider("text/plain",
  20539. [](size_t offset, DataSink &sink) {
  20540. if (offset < 15) {
  20541. sink.write("chunk", 5);
  20542. return true;
  20543. }
  20544. sink.done();
  20545. return true;
  20546. });
  20547. });
  20548. svr_.Get("/compressible", [](const Request &, Response &res) {
  20549. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20550. DataSink &sink) {
  20551. if (offset < 100 * 1024) {
  20552. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20553. sink.write(chunk.data(), chunk.size());
  20554. return true;
  20555. }
  20556. sink.done();
  20557. return true;
  20558. });
  20559. });
  20560. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20561. [](const Request & /*req*/, Response &res) {
  20562. auto i = new int(0);
  20563. res.set_header("Trailer", "Content-Length, X-Allowed");
  20564. res.set_chunked_content_provider(
  20565. "text/plain",
  20566. [i](size_t /*offset*/, DataSink &sink) {
  20567. switch (*i) {
  20568. case 0: sink.os << "123"; break;
  20569. case 1: sink.os << "456"; break;
  20570. case 2: sink.os << "789"; break;
  20571. case 3: {
  20572. sink.done_with_trailer(
  20573. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20574. } break;
  20575. }
  20576. (*i)++;
  20577. return true;
  20578. },
  20579. [i](bool success) {
  20580. EXPECT_TRUE(success);
  20581. delete i;
  20582. });
  20583. });
  20584. // Echo headers endpoint for header-related tests
  20585. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20586. std::string body;
  20587. for (const auto &h : req.headers) {
  20588. body.append(h.first);
  20589. body.push_back(':');
  20590. body.append(h.second);
  20591. body.push_back('\n');
  20592. }
  20593. res.set_content(body, "text/plain");
  20594. });
  20595. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20596. std::string body;
  20597. for (const auto &h : req.headers) {
  20598. body.append(h.first);
  20599. body.push_back(':');
  20600. body.append(h.second);
  20601. body.push_back('\n');
  20602. }
  20603. res.set_content(body, "text/plain");
  20604. });
  20605. port_ = svr_.bind_to_any_port("127.0.0.1");
  20606. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20607. svr_.wait_until_ready();
  20608. }
  20609. void TearDown() override {
  20610. svr_.stop();
  20611. if (thread_.joinable()) thread_.join();
  20612. }
  20613. Server svr_;
  20614. std::thread thread_;
  20615. int port_ = 0;
  20616. };
  20617. TEST_F(OpenStreamTest, Basic) {
  20618. Client cli("127.0.0.1", port_);
  20619. auto handle = cli.open_stream("GET", "/hello");
  20620. EXPECT_TRUE(handle.is_valid());
  20621. EXPECT_EQ("Hello World!", read_all(handle));
  20622. }
  20623. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20624. Client cli("127.0.0.1", port_);
  20625. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20626. ASSERT_TRUE(handle.is_valid());
  20627. EXPECT_EQ("Hello World!", read_all(handle));
  20628. }
  20629. TEST_F(OpenStreamTest, SmallBuffer) {
  20630. Client cli("127.0.0.1", port_);
  20631. auto handle = cli.open_stream("GET", "/hello");
  20632. std::string result;
  20633. char buf[4];
  20634. ssize_t n;
  20635. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20636. result.append(buf, static_cast<size_t>(n));
  20637. EXPECT_EQ("Hello World!", result);
  20638. }
  20639. TEST_F(OpenStreamTest, DefaultHeaders) {
  20640. Client cli("127.0.0.1", port_);
  20641. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20642. {
  20643. auto handle = cli.open_stream("GET", "/echo-headers");
  20644. ASSERT_TRUE(handle.is_valid());
  20645. auto body = read_all(handle);
  20646. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20647. std::string::npos);
  20648. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20649. std::string::npos);
  20650. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20651. }
  20652. // open_stream POST with body and no explicit content_type should NOT add
  20653. // text/plain Content-Type (behavior differs from non-streaming path), but
  20654. // should include Content-Length
  20655. {
  20656. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20657. ASSERT_TRUE(handle.is_valid());
  20658. auto body = read_all(handle);
  20659. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20660. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20661. }
  20662. // open_stream POST with explicit Content-Type should preserve it
  20663. {
  20664. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20665. {{"Content-Type", "application/custom"}},
  20666. "{}", "application/custom");
  20667. ASSERT_TRUE(handle.is_valid());
  20668. auto body = read_all(handle);
  20669. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20670. }
  20671. // User-specified User-Agent must not be overwritten for stream API
  20672. {
  20673. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20674. {{"User-Agent", "MyAgent/1.2"}});
  20675. ASSERT_TRUE(handle.is_valid());
  20676. auto body = read_all(handle);
  20677. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20678. }
  20679. }
  20680. TEST_F(OpenStreamTest, Large) {
  20681. Client cli("127.0.0.1", port_);
  20682. auto handle = cli.open_stream("GET", "/large");
  20683. EXPECT_EQ(10000u, read_all(handle).size());
  20684. }
  20685. TEST_F(OpenStreamTest, ConnectionError) {
  20686. Client cli("127.0.0.1", 9999);
  20687. auto handle = cli.open_stream("GET", "/hello");
  20688. EXPECT_FALSE(handle.is_valid());
  20689. }
  20690. TEST_F(OpenStreamTest, Chunked) {
  20691. Client cli("127.0.0.1", port_);
  20692. auto handle = cli.open_stream("GET", "/chunked");
  20693. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20694. "Transfer-Encoding") == "chunked");
  20695. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20696. }
  20697. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20698. Client cli("127.0.0.1", port_);
  20699. auto handle =
  20700. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20701. ASSERT_TRUE(handle.is_valid());
  20702. // Consume body to allow trailers to be received/parsed
  20703. auto body = read_all(handle);
  20704. // Explicitly parse trailers (ensure trailers are available for assertion)
  20705. handle.parse_trailers_if_needed();
  20706. EXPECT_EQ(std::string("123456789"), body);
  20707. // The response should include a Trailer header declaring both names
  20708. ASSERT_TRUE(handle.response);
  20709. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20710. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20711. handle.response->get_header_value("Trailer"));
  20712. // Prohibited trailer must not be present
  20713. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20714. // Allowed trailer should be present
  20715. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20716. EXPECT_EQ(std::string("yes"),
  20717. handle.response->get_trailer_value("X-Allowed"));
  20718. // Verify trailers are NOT present as regular headers
  20719. EXPECT_EQ(std::string(""),
  20720. handle.response->get_header_value("Content-Length"));
  20721. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20722. }
  20723. // Accepts one connection on an OS-assigned port, which it hands over through
  20724. // port_promise, reads the request head and sends back response. after_send,
  20725. // if given, runs on the connection before it is closed.
  20726. static std::thread
  20727. serve_single_response(std::promise<int> &port_promise,
  20728. const std::string &response,
  20729. std::function<void(socket_t)> after_send = nullptr) {
  20730. return std::thread([&port_promise, response, after_send] {
  20731. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20732. default_socket_options(srv);
  20733. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20734. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20735. sockaddr_in addr{};
  20736. addr.sin_family = AF_INET;
  20737. addr.sin_port = htons(0); // Let OS assign a free port
  20738. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20739. int opt = 1;
  20740. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20741. #ifdef _WIN32
  20742. reinterpret_cast<const char *>(&opt),
  20743. #else
  20744. &opt,
  20745. #endif
  20746. sizeof(opt));
  20747. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20748. ::listen(srv, 1) != 0) {
  20749. port_promise.set_value(-1);
  20750. detail::close_socket(srv);
  20751. return;
  20752. }
  20753. socklen_t addr_len = sizeof(addr);
  20754. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20755. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20756. sockaddr_in cli_addr{};
  20757. socklen_t cli_len = sizeof(cli_addr);
  20758. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20759. if (cli != INVALID_SOCKET) {
  20760. // Read the complete HTTP request (until the blank line that terminates
  20761. // headers) before sending the response. If the server closes the socket
  20762. // while the client's request data is still unread in the kernel receive
  20763. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20764. // connection on both sides: it discards the client's receive buffer
  20765. // (which already holds our response) and causes any in-progress write on
  20766. // the client to fail with ECONNRESET. Reading all request data first
  20767. // ensures close() emits a graceful FIN.
  20768. {
  20769. char rbuf[256];
  20770. std::string req;
  20771. while (req.find("\r\n\r\n") == std::string::npos) {
  20772. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20773. if (n <= 0) { break; }
  20774. req.append(rbuf, static_cast<size_t>(n));
  20775. }
  20776. }
  20777. ::send(cli,
  20778. #ifdef _WIN32
  20779. static_cast<const char *>(response.c_str()),
  20780. static_cast<int>(response.size()),
  20781. #else
  20782. response.c_str(), response.size(),
  20783. #endif
  20784. 0);
  20785. if (after_send) { after_send(cli); }
  20786. detail::close_socket(cli);
  20787. }
  20788. detail::close_socket(srv);
  20789. });
  20790. }
  20791. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20792. #ifndef _WIN32
  20793. signal(SIGPIPE, SIG_IGN);
  20794. #endif
  20795. std::promise<int> port_promise;
  20796. auto port_future = port_promise.get_future();
  20797. auto server_thread =
  20798. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20799. "Content-Type: text/plain\r\n"
  20800. "Content-Length: not-a-number\r\n"
  20801. "Connection: close\r\n"
  20802. "\r\n"
  20803. "hello");
  20804. auto port = port_future.get();
  20805. ASSERT_GT(port, 0);
  20806. Client cli("127.0.0.1", port);
  20807. auto handle = cli.open_stream("GET", "/");
  20808. EXPECT_FALSE(handle.is_valid());
  20809. server_thread.join();
  20810. }
  20811. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20812. #ifndef _WIN32
  20813. signal(SIGPIPE, SIG_IGN);
  20814. #endif
  20815. std::promise<int> port_promise;
  20816. auto port_future = port_promise.get_future();
  20817. auto server_thread = serve_single_response(
  20818. port_promise, "HTTP/1.1 200 OK\r\n"
  20819. "Content-Type: text/plain\r\n"
  20820. "Content-Length: 99999999999999999999999999\r\n"
  20821. "Connection: close\r\n"
  20822. "\r\n"
  20823. "hello");
  20824. auto port = port_future.get();
  20825. ASSERT_GT(port, 0);
  20826. // Historically std::stoull would throw std::out_of_range here and crash
  20827. // the process, then parsing silently clamped to a bogus framing length and
  20828. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20829. // so the stream fails to open, matching the not-a-number case above. The
  20830. // process still must NOT terminate.
  20831. Client cli("127.0.0.1", port);
  20832. auto handle = cli.open_stream("GET", "/");
  20833. EXPECT_FALSE(handle.is_valid());
  20834. server_thread.join();
  20835. }
  20836. #ifndef _WIN32
  20837. // As above for the body of a streamed request: a send() cut short by the write
  20838. // timeout must not leave the rest of the body unsent.
  20839. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20840. signal(SIGPIPE, SIG_IGN);
  20841. Server svr;
  20842. svr.set_socket_options([](socket_t sock) {
  20843. int size = 8192;
  20844. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20845. reinterpret_cast<const char *>(&size), sizeof(size));
  20846. });
  20847. svr.Post("/size", [](const Request &, Response &res,
  20848. const ContentReader &content_reader) {
  20849. // Outlast the client's write timeout before reading the body.
  20850. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20851. size_t received = 0;
  20852. content_reader([&](const char *, size_t len) {
  20853. received += len;
  20854. return true;
  20855. });
  20856. res.set_content(std::to_string(received), "text/plain");
  20857. });
  20858. auto port = svr.bind_to_any_port(HOST);
  20859. std::thread t([&]() { svr.listen_after_bind(); });
  20860. auto se = detail::scope_exit([&] {
  20861. svr.stop();
  20862. t.join();
  20863. });
  20864. svr.wait_until_ready();
  20865. Client cli(HOST, port);
  20866. cli.set_write_timeout(0, 500000);
  20867. cli.set_socket_options([](socket_t sock) {
  20868. int size = 8192;
  20869. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20870. reinterpret_cast<const char *>(&size), sizeof(size));
  20871. });
  20872. const std::string body(4 * 1024 * 1024, 'A');
  20873. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20874. "application/octet-stream");
  20875. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20876. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20877. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20878. }
  20879. #endif
  20880. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  20881. std::promise<void> slow_started;
  20882. auto slow_started_future = slow_started.get_future();
  20883. Server svr;
  20884. svr.Get("/slow", [&](const Request &, Response &res) {
  20885. slow_started.set_value();
  20886. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20887. res.set_content("slow", "text/plain");
  20888. });
  20889. svr.Get("/fast", [](const Request &, Response &res) {
  20890. res.set_content("fast", "text/plain");
  20891. });
  20892. auto port = svr.bind_to_any_port(HOST);
  20893. std::thread t([&]() { svr.listen_after_bind(); });
  20894. auto se = detail::scope_exit([&] {
  20895. svr.stop();
  20896. t.join();
  20897. });
  20898. svr.wait_until_ready();
  20899. Client cli(HOST, port);
  20900. std::string slow_body;
  20901. std::thread slow_thread([&] {
  20902. auto res = cli.Get("/slow");
  20903. if (res) { slow_body = res->body; }
  20904. });
  20905. slow_started_future.wait();
  20906. auto result = stream::Get(cli, "/fast");
  20907. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  20908. slow_thread.join();
  20909. EXPECT_EQ("slow", slow_body);
  20910. EXPECT_EQ("fast", fast_body);
  20911. }
  20912. // Serves `response` to the single request `fn` makes with a fresh client.
  20913. template <typename Fn>
  20914. static void with_single_response(const std::string &response, Fn fn) {
  20915. #ifndef _WIN32
  20916. signal(SIGPIPE, SIG_IGN);
  20917. #endif
  20918. std::promise<int> port_promise;
  20919. auto port_future = port_promise.get_future();
  20920. auto server_thread = serve_single_response(port_promise, response);
  20921. auto se = detail::scope_exit([&] { server_thread.join(); });
  20922. auto port = port_future.get();
  20923. ASSERT_GT(port, 0);
  20924. Client cli("127.0.0.1", port);
  20925. fn(cli);
  20926. }
  20927. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20928. // too, also in a build without the decoder for the advertised coding.
  20929. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20930. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20931. const auto response = "HTTP/1.1 200 OK\r\n"
  20932. "Content-Encoding: gzip\r\n"
  20933. "Content-Length: " +
  20934. std::to_string(gzipped.size()) +
  20935. "\r\n"
  20936. "Connection: close\r\n\r\n" +
  20937. gzipped;
  20938. with_single_response(response, [&](Client &cli) {
  20939. cli.set_decompress(false);
  20940. auto handle = cli.open_stream("GET", "/");
  20941. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20942. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20943. EXPECT_EQ(gzipped, read_all(handle));
  20944. EXPECT_FALSE(handle.has_read_error());
  20945. });
  20946. with_single_response(response, [&](Client &cli) {
  20947. cli.set_decompress(false);
  20948. auto res = stream::Get(cli, "/", 7);
  20949. ASSERT_TRUE(res) << to_string(res.error());
  20950. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20951. EXPECT_EQ(gzipped, res.read_all());
  20952. EXPECT_FALSE(res.has_read_error());
  20953. });
  20954. }
  20955. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20956. // Neither Content-Length nor chunked: the body ends at the close
  20957. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20958. "Connection: close\r\n"
  20959. "\r\n"
  20960. "hello";
  20961. with_single_response(close_delimited, [](Client &cli) {
  20962. auto handle = cli.open_stream("GET", "/");
  20963. ASSERT_TRUE(handle.is_valid());
  20964. EXPECT_EQ("hello", read_all(handle));
  20965. EXPECT_FALSE(handle.has_read_error());
  20966. });
  20967. // A close before the end of the Content-Length is still an error
  20968. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20969. "Content-Length: 10\r\n"
  20970. "\r\n"
  20971. "hello";
  20972. with_single_response(short_content_length, [](Client &cli) {
  20973. auto handle = cli.open_stream("GET", "/");
  20974. ASSERT_TRUE(handle.is_valid());
  20975. read_all(handle);
  20976. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20977. });
  20978. // So is a close before the last chunk
  20979. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20980. "Transfer-Encoding: chunked\r\n"
  20981. "\r\n"
  20982. "5\r\nhello\r\n";
  20983. with_single_response(short_chunked, [](Client &cli) {
  20984. auto handle = cli.open_stream("GET", "/");
  20985. ASSERT_TRUE(handle.is_valid());
  20986. read_all(handle);
  20987. EXPECT_TRUE(handle.has_read_error());
  20988. });
  20989. }
  20990. #ifdef CPPHTTPLIB_SSL_ENABLED
  20991. // Serves `response` to one request, then closes with or without a close_notify
  20992. template <typename Fn>
  20993. static void with_single_tls_response(const std::string &response,
  20994. bool close_notify, Fn fn) {
  20995. #ifndef _WIN32
  20996. signal(SIGPIPE, SIG_IGN);
  20997. #endif
  20998. std::promise<int> port_promise;
  20999. auto port_future = port_promise.get_future();
  21000. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21001. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21002. default_socket_options(srv);
  21003. sockaddr_in addr{};
  21004. addr.sin_family = AF_INET;
  21005. addr.sin_port = htons(0);
  21006. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21007. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21008. ::listen(srv, 1) != 0) {
  21009. port_promise.set_value(-1);
  21010. detail::close_socket(srv);
  21011. return;
  21012. }
  21013. socklen_t addr_len = sizeof(addr);
  21014. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21015. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21016. auto cli = ::accept(srv, nullptr, nullptr);
  21017. if (cli != INVALID_SOCKET) {
  21018. auto ctx = tls::create_server_context();
  21019. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21020. nullptr);
  21021. auto session = tls::create_session(ctx, cli);
  21022. tls::TlsError err;
  21023. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  21024. // The request head first, so that closing the socket sends a FIN
  21025. // rather than an RST for the unread bytes.
  21026. std::string req;
  21027. char buf[256];
  21028. while (req.find("\r\n\r\n") == std::string::npos) {
  21029. auto n = tls::read(session, buf, sizeof(buf), err);
  21030. if (n <= 0) { break; }
  21031. req.append(buf, static_cast<size_t>(n));
  21032. }
  21033. size_t sent = 0;
  21034. while (sent < response.size()) {
  21035. auto n = tls::write(session, response.data() + sent,
  21036. response.size() - sent, err);
  21037. if (n <= 0) { break; }
  21038. sent += static_cast<size_t>(n);
  21039. }
  21040. if (close_notify) { tls::shutdown(session, true); }
  21041. }
  21042. tls::free_session(session);
  21043. detail::close_socket(cli);
  21044. tls::free_context(ctx);
  21045. }
  21046. detail::close_socket(srv);
  21047. });
  21048. auto se = detail::scope_exit([&] { server_thread.join(); });
  21049. auto port = port_future.get();
  21050. ASSERT_GT(port, 0);
  21051. SSLClient cli("127.0.0.1", port);
  21052. cli.enable_server_certificate_verification(false);
  21053. fn(cli);
  21054. }
  21055. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21056. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21057. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21058. "Connection: close\r\n"
  21059. "\r\n"
  21060. "hello";
  21061. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21062. auto res = cli.Get("/");
  21063. ASSERT_TRUE(res) << to_string(res.error());
  21064. EXPECT_EQ("hello", res->body);
  21065. });
  21066. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21067. auto res = cli.Get("/");
  21068. ASSERT_FALSE(res);
  21069. EXPECT_EQ(Error::Read, res.error());
  21070. });
  21071. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21072. auto handle = cli.open_stream("GET", "/");
  21073. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21074. read_all(handle);
  21075. EXPECT_TRUE(handle.has_read_error());
  21076. });
  21077. // A framed body ends where its framing says, with or without the alert
  21078. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21079. "Content-Length: 5\r\n"
  21080. "Connection: close\r\n"
  21081. "\r\n"
  21082. "hello";
  21083. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21084. auto res = cli.Get("/");
  21085. ASSERT_TRUE(res) << to_string(res.error());
  21086. EXPECT_EQ("hello", res->body);
  21087. });
  21088. }
  21089. #endif
  21090. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21091. const char *responses[] = {
  21092. "HTTP/1.1 103 Early Hints\r\n"
  21093. "Link: </style.css>; rel=preload\r\n"
  21094. "\r\n"
  21095. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21096. "HTTP/1.1 100 Continue\r\n"
  21097. "X-Note: interim\r\n"
  21098. "\r\n"
  21099. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21100. };
  21101. for (auto response : responses) {
  21102. with_single_response(response, [](Client &cli) {
  21103. auto res = cli.Get("/");
  21104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21105. EXPECT_EQ(StatusCode::OK_200, res->status);
  21106. EXPECT_EQ("ok", res->body);
  21107. });
  21108. }
  21109. }
  21110. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21111. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21112. const std::string final_response =
  21113. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21114. std::string interims;
  21115. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21116. interims += interim;
  21117. }
  21118. with_single_response(interims + final_response, [](Client &cli) {
  21119. auto res = cli.Get("/");
  21120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21121. EXPECT_EQ("ok", res->body);
  21122. });
  21123. with_single_response(interims + interim + final_response, [](Client &cli) {
  21124. auto res = cli.Get("/");
  21125. ASSERT_FALSE(res);
  21126. EXPECT_EQ(Error::Read, res.error());
  21127. });
  21128. }
  21129. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21130. #ifndef _WIN32
  21131. signal(SIGPIPE, SIG_IGN);
  21132. #endif
  21133. // The server answers the head without asking for the body. Bytes it then
  21134. // reads on the connection would be taken for the body the request declared.
  21135. auto closed_by_client = false;
  21136. std::promise<int> port_promise;
  21137. auto server_thread = serve_single_response(
  21138. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21139. [&](socket_t sock) {
  21140. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21141. char buf[256];
  21142. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21143. });
  21144. Client cli("127.0.0.1", port_promise.get_future().get());
  21145. cli.set_keep_alive(true);
  21146. cli.set_read_timeout(1, 0);
  21147. // Long enough for the client to send Expect: 100-continue.
  21148. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21150. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21151. cli.Get("/second");
  21152. server_thread.join();
  21153. EXPECT_TRUE(closed_by_client);
  21154. }
  21155. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21156. // Long enough for the client to send Expect: 100-continue
  21157. with_single_response(
  21158. "HTTP/1.1 103 Early Hints\r\n"
  21159. "Link: </style.css>; rel=preload\r\n"
  21160. "\r\n"
  21161. "HTTP/1.1 401 Unauthorized\r\n"
  21162. "Content-Length: 0\r\n\r\n",
  21163. [](Client &cli) {
  21164. cli.set_read_timeout(2, 0);
  21165. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21167. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21168. });
  21169. }
  21170. #ifdef CPPHTTPLIB_SSL_ENABLED
  21171. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21172. #ifndef _WIN32
  21173. signal(SIGPIPE, SIG_IGN);
  21174. #endif
  21175. auto reused = false;
  21176. std::promise<int> port_promise;
  21177. auto server_thread = serve_single_response(
  21178. port_promise,
  21179. "HTTP/1.1 401 Unauthorized\r\n"
  21180. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21181. "Content-Length: 0\r\n\r\n",
  21182. [&](socket_t sock) {
  21183. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21184. char buf[256];
  21185. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21186. });
  21187. Client cli("127.0.0.1", port_promise.get_future().get());
  21188. cli.set_keep_alive(true);
  21189. cli.set_digest_auth("user", "pass");
  21190. cli.set_read_timeout(1, 0);
  21191. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21192. server_thread.join();
  21193. EXPECT_FALSE(reused);
  21194. }
  21195. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21196. // Any other answer to CONNECT would read as the origin's response.
  21197. struct {
  21198. const char *response;
  21199. bool passed_on;
  21200. } cases[] = {
  21201. {"HTTP/1.1 201 Created\r\n"
  21202. "Set-Cookie: session=from-proxy\r\n"
  21203. "Content-Length: 0\r\n\r\n",
  21204. false},
  21205. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21206. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21207. "Content-Length: 0\r\n\r\n",
  21208. true},
  21209. };
  21210. for (const auto &c : cases) {
  21211. std::promise<int> port_promise;
  21212. auto server_thread = serve_single_response(port_promise, c.response);
  21213. SSLClient cli("example.com", 443);
  21214. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21215. auto res = cli.Get("/");
  21216. server_thread.join();
  21217. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21218. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21219. if (res) {
  21220. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21221. }
  21222. }
  21223. }
  21224. #endif
  21225. // Records the client's error logger calls as "error METHOD path", or
  21226. // "error null" for a call without a request
  21227. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21228. return [&log](const Error &err, const Request *req) {
  21229. log.push_back(to_string(err) + " " +
  21230. (req ? req->method + " " + req->path : "null"));
  21231. };
  21232. }
  21233. // A failed request is reported once, with the request the caller made
  21234. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21235. Server svr;
  21236. svr.Get("/big", [](const Request &, Response &res) {
  21237. res.set_content(std::string(100000, 'b'), "text/plain");
  21238. });
  21239. auto port = svr.bind_to_any_port(HOST);
  21240. std::thread t([&]() { svr.listen_after_bind(); });
  21241. auto se = detail::scope_exit([&] {
  21242. svr.stop();
  21243. t.join();
  21244. });
  21245. svr.wait_until_ready();
  21246. Client cli(HOST, port);
  21247. std::vector<std::string> log;
  21248. cli.set_error_logger(record_errors(log));
  21249. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21250. cli.Get("/big", [](const char *, size_t) { return false; });
  21251. EXPECT_EQ(expected, log);
  21252. log.clear();
  21253. cli.Get("/big", [](size_t, size_t) { return false; });
  21254. EXPECT_EQ(expected, log);
  21255. }
  21256. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21257. // Fails while the body is read
  21258. auto broken = [](const Request &, Response &res) {
  21259. res.set_content_provider(10, "text/plain",
  21260. [](size_t, size_t, DataSink &) { return false; });
  21261. };
  21262. Server other;
  21263. other.Get("/broken", broken);
  21264. auto other_port = other.bind_to_any_port(HOST);
  21265. std::thread other_t([&]() { other.listen_after_bind(); });
  21266. auto other_se = detail::scope_exit([&] {
  21267. other.stop();
  21268. other_t.join();
  21269. });
  21270. other.wait_until_ready();
  21271. Server svr;
  21272. svr.Get("/broken", broken);
  21273. svr.Get("/same-origin",
  21274. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21275. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21276. res.set_redirect("http://" + std::string(HOST) + ":" +
  21277. std::to_string(other_port) + "/broken");
  21278. });
  21279. auto port = svr.bind_to_any_port(HOST);
  21280. std::thread t([&]() { svr.listen_after_bind(); });
  21281. auto se = detail::scope_exit([&] {
  21282. svr.stop();
  21283. t.join();
  21284. });
  21285. svr.wait_until_ready();
  21286. Client cli(HOST, port);
  21287. cli.set_follow_location(true);
  21288. std::vector<std::string> log;
  21289. cli.set_error_logger(record_errors(log));
  21290. for (auto path : {"/same-origin", "/cross-origin"}) {
  21291. log.clear();
  21292. auto res = cli.Get(path);
  21293. ASSERT_FALSE(res);
  21294. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21295. log);
  21296. }
  21297. }
  21298. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21299. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21300. std::vector<std::string> log;
  21301. cli.set_error_logger(record_errors(log));
  21302. auto handle = cli.open_stream("GET", "/x");
  21303. EXPECT_FALSE(handle.is_valid());
  21304. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21305. log);
  21306. });
  21307. }
  21308. #ifdef CPPHTTPLIB_SSL_ENABLED
  21309. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21310. // Not a TLS server, so the handshake fails. It waits for a request line in
  21311. // the handshake bytes, so a short read timeout lets it close quickly.
  21312. Server svr;
  21313. svr.set_read_timeout(0, 100000);
  21314. svr.Get("/x", [](const Request &, Response &res) {
  21315. res.set_content("x", "text/plain");
  21316. });
  21317. auto port = svr.bind_to_any_port(HOST);
  21318. std::thread t([&]() { svr.listen_after_bind(); });
  21319. auto se = detail::scope_exit([&] {
  21320. svr.stop();
  21321. t.join();
  21322. });
  21323. svr.wait_until_ready();
  21324. std::vector<std::string> log;
  21325. SSLClient cli(HOST, port);
  21326. cli.enable_server_certificate_verification(false);
  21327. cli.set_error_logger(record_errors(log));
  21328. auto res = cli.Get("/x");
  21329. ASSERT_FALSE(res);
  21330. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21331. log.clear();
  21332. auto handle = cli.open_stream("GET", "/x");
  21333. EXPECT_FALSE(handle.is_valid());
  21334. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21335. log.clear();
  21336. SSLClient no_ca(HOST, port);
  21337. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21338. no_ca.set_error_logger(record_errors(log));
  21339. res = no_ca.Get("/x");
  21340. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21341. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21342. }
  21343. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21344. #ifndef _WIN32
  21345. signal(SIGPIPE, SIG_IGN);
  21346. #endif
  21347. // Refused, answered with a challenge, or closed without an answer
  21348. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21349. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21350. "Content-Length: 0\r\n\r\n",
  21351. ""}) {
  21352. std::promise<int> port_promise;
  21353. auto server_thread = serve_single_response(port_promise, response);
  21354. SSLClient cli("example.com", 443);
  21355. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21356. std::vector<std::string> log;
  21357. cli.set_error_logger(record_errors(log));
  21358. auto res = cli.Get("/");
  21359. server_thread.join();
  21360. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21361. << response;
  21362. }
  21363. }
  21364. #endif
  21365. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21366. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21367. // the chunked coding and drop Content-Length, so a front-end that trusts
  21368. // Content-Length would disagree about where the body ends (response
  21369. // smuggling). The client must reject such a response.
  21370. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21371. for (const char *te : {"chunked", "gzip, chunked"}) {
  21372. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21373. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21374. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21375. "5\r\nhello\r\n0\r\n\r\n";
  21376. with_single_response(response, [&](Client &cli) {
  21377. auto res = cli.Get("/");
  21378. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21379. EXPECT_EQ(Error::Read, res.error()) << te;
  21380. });
  21381. with_single_response(response, [&](Client &cli) {
  21382. auto handle = cli.open_stream("GET", "/");
  21383. EXPECT_FALSE(handle.is_valid()) << te;
  21384. EXPECT_EQ(Error::Read, handle.error) << te;
  21385. });
  21386. }
  21387. }
  21388. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21389. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21390. // closing the connection (unlike a request, which must be rejected).
  21391. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21392. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21393. "Transfer-Encoding: chunked\r\n"
  21394. "Connection: close\r\n"
  21395. "\r\n"
  21396. "5\r\nhello\r\n0\r\n\r\n",
  21397. "HTTP/1.1 200 OK\r\n"
  21398. "Transfer-Encoding: gzip\r\n"
  21399. "Connection: close\r\n"
  21400. "\r\n"
  21401. "hello"}) {
  21402. with_single_response(response, [&](Client &cli) {
  21403. auto res = cli.Get("/");
  21404. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21405. EXPECT_EQ("hello", res->body);
  21406. });
  21407. with_single_response(response, [&](Client &cli) {
  21408. auto handle = cli.open_stream("GET", "/");
  21409. ASSERT_TRUE(handle.is_valid()) << response;
  21410. EXPECT_EQ("hello", read_all(handle));
  21411. });
  21412. }
  21413. }
  21414. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21415. // framing headers describe nothing to read and must not be rejected.
  21416. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21417. const std::string framing = "Content-Length: 5\r\n"
  21418. "Transfer-Encoding: chunked\r\n"
  21419. "Connection: close\r\n"
  21420. "\r\n";
  21421. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21422. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21423. });
  21424. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21425. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21426. });
  21427. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21428. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21429. with_single_response(response, [&](Client &cli) {
  21430. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21431. });
  21432. with_single_response(response, [&](Client &cli) {
  21433. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21434. });
  21435. }
  21436. }
  21437. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21438. // header section, so a stream opened on one has nothing to read, whatever
  21439. // framing or coding headers it carries.
  21440. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21441. struct Case {
  21442. const char *method;
  21443. const char *status;
  21444. };
  21445. // A reader of the declared body reports an early close when nothing
  21446. // follows, and hands back what does.
  21447. struct Framing {
  21448. const char *headers;
  21449. const char *after;
  21450. };
  21451. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21452. Case{"GET", "304 Not Modified"}}) {
  21453. for (const auto &f :
  21454. {Framing{"Content-Length: 5\r\n", ""},
  21455. Framing{"Content-Length: 5\r\n", "hello"},
  21456. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21457. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21458. // Not decoded, so a build without Brotli opens it too
  21459. Framing{"Content-Encoding: br\r\n", ""}}) {
  21460. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21461. "Connection: close\r\n"
  21462. "\r\n" +
  21463. f.after;
  21464. with_single_response(response, [&](Client &cli) {
  21465. auto handle = cli.open_stream(c.method, "/");
  21466. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21467. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21468. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21469. });
  21470. }
  21471. }
  21472. }
  21473. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21474. // response, is faulty framing, so the connection is not reused after it.
  21475. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21476. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21477. "Content-Length: 0\r\n"
  21478. "Transfer-Encoding: chunked\r\n"
  21479. "\r\n"
  21480. "5\r\nhello\r\n0\r\n\r\n",
  21481. "HTTP/1.0 200 Connection established\r\n"
  21482. "Connection: keep-alive\r\n"
  21483. "Transfer-Encoding: chunked\r\n"
  21484. "\r\n"
  21485. "5\r\nhello\r\n0\r\n\r\n"}) {
  21486. with_single_response(response, [&](Client &cli) {
  21487. cli.set_keep_alive(true);
  21488. auto res = cli.Get("/");
  21489. ASSERT_TRUE(res) << response;
  21490. EXPECT_EQ("hello", res->body);
  21491. EXPECT_FALSE(cli.is_socket_open()) << response;
  21492. });
  21493. }
  21494. }
  21495. // A payload max length of 0 means no limit, however the body is framed.
  21496. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21497. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21498. "Transfer-Encoding: chunked\r\n"
  21499. "\r\n"
  21500. "5\r\nhello\r\n0\r\n\r\n",
  21501. "HTTP/1.1 200 OK\r\n"
  21502. "Connection: close\r\n"
  21503. "\r\n"
  21504. "hello"}) {
  21505. with_single_response(response, [&](Client &cli) {
  21506. cli.set_payload_max_length(0);
  21507. auto res = cli.Get("/");
  21508. ASSERT_TRUE(res) << response;
  21509. EXPECT_EQ("hello", res->body) << response;
  21510. });
  21511. }
  21512. }
  21513. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21514. Server svr;
  21515. svr.set_payload_max_length(0);
  21516. svr.Post("/echo", [](const Request &req, Response &res) {
  21517. res.set_content(req.body, "text/plain");
  21518. });
  21519. auto port = svr.bind_to_any_port(HOST);
  21520. thread t = thread([&] { svr.listen_after_bind(); });
  21521. auto se = detail::scope_exit([&] {
  21522. svr.stop();
  21523. t.join();
  21524. ASSERT_FALSE(svr.is_running());
  21525. });
  21526. svr.wait_until_ready();
  21527. Client cli(HOST, port);
  21528. auto res = cli.Post(
  21529. "/echo",
  21530. [](size_t /*offset*/, DataSink &sink) {
  21531. sink.write("hello", 5);
  21532. sink.done();
  21533. return true;
  21534. },
  21535. "text/plain");
  21536. ASSERT_TRUE(res);
  21537. EXPECT_EQ(StatusCode::OK_200, res->status);
  21538. EXPECT_EQ("hello", res->body);
  21539. }
  21540. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21541. TEST_F(OpenStreamTest, Gzip) {
  21542. Client cli("127.0.0.1", port_);
  21543. auto handle = cli.open_stream("GET", "/compressible", {},
  21544. {{"Accept-Encoding", "gzip"}});
  21545. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21546. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21547. }
  21548. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21549. Client cli("127.0.0.1", port_);
  21550. auto handle =
  21551. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21552. {{"Accept-Encoding", "gzip"}});
  21553. ASSERT_TRUE(handle.is_valid());
  21554. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21555. EXPECT_EQ("123456789", read_all(handle));
  21556. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21557. }
  21558. #endif
  21559. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21560. TEST_F(OpenStreamTest, Brotli) {
  21561. Client cli("127.0.0.1", port_);
  21562. auto handle =
  21563. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21564. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21565. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21566. }
  21567. #endif
  21568. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21569. TEST_F(OpenStreamTest, Zstd) {
  21570. Client cli("127.0.0.1", port_);
  21571. auto handle = cli.open_stream("GET", "/compressible", {},
  21572. {{"Accept-Encoding", "zstd"}});
  21573. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21574. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21575. }
  21576. #endif
  21577. #ifdef CPPHTTPLIB_SSL_ENABLED
  21578. class SSLOpenStreamTest : public ::testing::Test {
  21579. protected:
  21580. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21581. void SetUp() override {
  21582. svr_.Get("/hello", [](const Request &, Response &res) {
  21583. res.set_content("Hello SSL World!", "text/plain");
  21584. });
  21585. svr_.Get("/chunked", [](const Request &, Response &res) {
  21586. res.set_chunked_content_provider("text/plain",
  21587. [](size_t offset, DataSink &sink) {
  21588. if (offset < 15) {
  21589. sink.write("chunk", 5);
  21590. return true;
  21591. }
  21592. sink.done();
  21593. return true;
  21594. });
  21595. });
  21596. svr_.Post("/echo", [](const Request &req, Response &res) {
  21597. res.set_content(req.body, req.get_header_value("Content-Type"));
  21598. });
  21599. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21600. std::string body = req.body;
  21601. res.set_chunked_content_provider(
  21602. "text/plain", [body](size_t offset, DataSink &sink) {
  21603. if (offset < body.size()) {
  21604. sink.write(body.data() + offset, body.size() - offset);
  21605. }
  21606. sink.done();
  21607. return true;
  21608. });
  21609. });
  21610. port_ = svr_.bind_to_any_port("127.0.0.1");
  21611. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21612. svr_.wait_until_ready();
  21613. }
  21614. void TearDown() override {
  21615. svr_.stop();
  21616. if (thread_.joinable()) thread_.join();
  21617. }
  21618. SSLServer svr_;
  21619. std::thread thread_;
  21620. int port_ = 0;
  21621. };
  21622. TEST_F(SSLOpenStreamTest, Basic) {
  21623. SSLClient cli("127.0.0.1", port_);
  21624. cli.enable_server_certificate_verification(false);
  21625. auto handle = cli.open_stream("GET", "/hello");
  21626. ASSERT_TRUE(handle.is_valid());
  21627. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21628. }
  21629. TEST_F(SSLOpenStreamTest, Chunked) {
  21630. SSLClient cli("127.0.0.1", port_);
  21631. cli.enable_server_certificate_verification(false);
  21632. auto handle = cli.open_stream("GET", "/chunked");
  21633. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21634. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21635. "Transfer-Encoding") == "chunked");
  21636. auto body = read_all(handle);
  21637. EXPECT_EQ("chunkchunkchunk", body);
  21638. }
  21639. TEST_F(SSLOpenStreamTest, Post) {
  21640. SSLClient cli("127.0.0.1", port_);
  21641. cli.enable_server_certificate_verification(false);
  21642. auto handle =
  21643. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21644. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21645. EXPECT_EQ(200, handle.response->status);
  21646. auto body = read_all(handle);
  21647. EXPECT_EQ("Hello SSL POST", body);
  21648. }
  21649. TEST_F(SSLOpenStreamTest, PostChunked) {
  21650. SSLClient cli("127.0.0.1", port_);
  21651. cli.enable_server_certificate_verification(false);
  21652. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21653. "Chunked SSL Data", "text/plain");
  21654. ASSERT_TRUE(handle.is_valid());
  21655. EXPECT_EQ(200, handle.response->status);
  21656. auto body = read_all(handle);
  21657. EXPECT_EQ("Chunked SSL Data", body);
  21658. }
  21659. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21660. // Content-Length is terminated by the server closing the connection. When the
  21661. // SSL peer sends a close_notify after the body, the client must treat it as a
  21662. // clean EOF and return a successful response rather than an error.
  21663. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21665. ASSERT_TRUE(svr.is_valid());
  21666. svr.set_keep_alive_max_count(1);
  21667. const std::string expected_body = "Hello from connection-close response!";
  21668. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21669. res.set_content_provider("text/plain",
  21670. [&](size_t offset, DataSink &sink) -> bool {
  21671. if (offset < expected_body.size()) {
  21672. sink.write(expected_body.data() + offset,
  21673. expected_body.size() - offset);
  21674. }
  21675. sink.done();
  21676. return true;
  21677. });
  21678. });
  21679. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21680. auto se = detail::scope_exit([&] {
  21681. svr.stop();
  21682. listen_thread.join();
  21683. ASSERT_FALSE(svr.is_running());
  21684. });
  21685. svr.wait_until_ready();
  21686. SSLClient cli(HOST, PORT);
  21687. cli.enable_server_certificate_verification(false);
  21688. auto res = cli.Get("/no-content-length");
  21689. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21690. EXPECT_EQ(StatusCode::OK_200, res->status);
  21691. EXPECT_EQ(expected_body, res->body);
  21692. }
  21693. // Without Content-Length, the full buffer size reaches tls::read().
  21694. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21695. if (sizeof(size_t) <= sizeof(int)) {
  21696. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21697. }
  21698. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21699. ASSERT_TRUE(svr.is_valid());
  21700. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21701. res.set_content_provider("text/plain",
  21702. [&](size_t offset, DataSink &sink) -> bool {
  21703. if (offset == 0) { sink.write("Hello", 5); }
  21704. sink.done();
  21705. return true;
  21706. });
  21707. });
  21708. auto port = svr.bind_to_any_port(HOST);
  21709. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21710. auto se = detail::scope_exit([&] {
  21711. svr.stop();
  21712. listen_thread.join();
  21713. });
  21714. svr.wait_until_ready();
  21715. SSLClient cli(HOST, port);
  21716. cli.enable_server_certificate_verification(false);
  21717. auto handle = cli.open_stream("GET", "/no-content-length");
  21718. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21719. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21720. std::unique_ptr<char[]> buf(new char[len]);
  21721. std::string body;
  21722. ssize_t n;
  21723. while ((n = handle.read(buf.get(), len)) > 0) {
  21724. body.append(buf.get(), static_cast<size_t>(n));
  21725. }
  21726. EXPECT_EQ(0, n);
  21727. EXPECT_EQ("Hello", body);
  21728. }
  21729. #endif // CPPHTTPLIB_SSL_ENABLED
  21730. //==============================================================================
  21731. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21732. // results for various scenarios.
  21733. //==============================================================================
  21734. TEST(ParityTest, GetVsOpenStream) {
  21735. Server svr;
  21736. const std::string path = "/parity";
  21737. const std::string content = "Parity test content: hello world";
  21738. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21739. res.set_content(content, "text/plain");
  21740. });
  21741. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21742. auto se = detail::scope_exit([&] {
  21743. svr.stop();
  21744. t.join();
  21745. ASSERT_FALSE(svr.is_running());
  21746. });
  21747. svr.wait_until_ready();
  21748. Client cli(HOST, PORT);
  21749. // Non-stream path
  21750. auto r1 = cli.Get(path);
  21751. ASSERT_TRUE(r1);
  21752. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21753. // Stream path
  21754. auto h = cli.open_stream("GET", path);
  21755. ASSERT_TRUE(h.is_valid());
  21756. EXPECT_EQ(r1->body, read_all(h));
  21757. }
  21758. // Helper to compress data with provided compressor type T
  21759. template <typename Compressor>
  21760. static std::string compress_payload_for_parity(const std::string &in) {
  21761. std::string out;
  21762. Compressor compressor;
  21763. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21764. [&](const char *data, size_t n) {
  21765. out.append(data, n);
  21766. return true;
  21767. });
  21768. EXPECT_TRUE(ok);
  21769. return out;
  21770. }
  21771. // Helper function for compression parity tests
  21772. template <typename Compressor>
  21773. static void test_compression_parity(const std::string &original,
  21774. const std::string &path,
  21775. const std::string &encoding) {
  21776. const std::string compressed =
  21777. compress_payload_for_parity<Compressor>(original);
  21778. Server svr;
  21779. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21780. res.set_content(compressed, "application/octet-stream");
  21781. res.set_header("Content-Encoding", encoding);
  21782. });
  21783. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21784. auto se = detail::scope_exit([&] {
  21785. svr.stop();
  21786. t.join();
  21787. ASSERT_FALSE(svr.is_running());
  21788. });
  21789. svr.wait_until_ready();
  21790. Client cli(HOST, PORT);
  21791. // Non-streaming
  21792. {
  21793. auto res = cli.Get(path);
  21794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21795. EXPECT_EQ(StatusCode::OK_200, res->status);
  21796. EXPECT_EQ(original, res->body);
  21797. }
  21798. // Streaming
  21799. {
  21800. auto h = cli.open_stream("GET", path);
  21801. ASSERT_TRUE(h.is_valid());
  21802. EXPECT_EQ(original, read_all(h));
  21803. }
  21804. }
  21805. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21806. TEST(ParityTest, Gzip) {
  21807. test_compression_parity<detail::gzip_compressor>(
  21808. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21809. }
  21810. #endif
  21811. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21812. TEST(ParityTest, Brotli) {
  21813. test_compression_parity<detail::brotli_compressor>(
  21814. "Hello, brotli parity test payload", "/parity-br", "br");
  21815. }
  21816. #endif
  21817. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21818. TEST(ParityTest, Zstd) {
  21819. test_compression_parity<detail::zstd_compressor>(
  21820. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21821. }
  21822. #endif
  21823. //==============================================================================
  21824. // New Stream API Tests
  21825. //==============================================================================
  21826. inline std::string read_body(httplib::stream::Result &result) {
  21827. std::string body;
  21828. while (result.next()) {
  21829. body.append(result.data(), result.size());
  21830. }
  21831. return body;
  21832. }
  21833. TEST(ClientConnectionTest, Basic) {
  21834. httplib::ClientConnection conn;
  21835. EXPECT_FALSE(conn.is_open());
  21836. conn.sock = 1;
  21837. EXPECT_TRUE(conn.is_open());
  21838. httplib::ClientConnection conn2(std::move(conn));
  21839. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21840. conn2.sock = INVALID_SOCKET;
  21841. }
  21842. // Unified test server for all stream::* tests
  21843. class StreamApiTest : public ::testing::Test {
  21844. protected:
  21845. void SetUp() override {
  21846. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21847. res.set_content("Hello World!", "text/plain");
  21848. });
  21849. svr_.Get("/echo-params",
  21850. [](const httplib::Request &req, httplib::Response &res) {
  21851. std::string r;
  21852. for (const auto &p : req.params) {
  21853. if (!r.empty()) r += "&";
  21854. r += p.first + "=" + p.second;
  21855. }
  21856. res.set_content(r, "text/plain");
  21857. });
  21858. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21859. res.set_content(req.body, req.get_header_value("Content-Type"));
  21860. });
  21861. svr_.Post("/echo-headers",
  21862. [](const httplib::Request &req, httplib::Response &res) {
  21863. std::string r;
  21864. for (const auto &h : req.headers)
  21865. r += h.first + ": " + h.second + "\n";
  21866. res.set_content(r, "text/plain");
  21867. });
  21868. svr_.Post("/echo-params",
  21869. [](const httplib::Request &req, httplib::Response &res) {
  21870. std::string r = "params:";
  21871. for (const auto &p : req.params)
  21872. r += p.first + "=" + p.second + ";";
  21873. res.set_content(r + " body:" + req.body, "text/plain");
  21874. });
  21875. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21876. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21877. });
  21878. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21879. res.set_content("PUT:" + req.body, "text/plain");
  21880. });
  21881. svr_.Patch("/echo",
  21882. [](const httplib::Request &req, httplib::Response &res) {
  21883. res.set_content("PATCH:" + req.body, "text/plain");
  21884. });
  21885. svr_.Delete(
  21886. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21887. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21888. "text/plain");
  21889. });
  21890. svr_.Get("/head-test",
  21891. [](const httplib::Request &, httplib::Response &res) {
  21892. res.set_content("body for HEAD", "text/plain");
  21893. });
  21894. svr_.Options("/options",
  21895. [](const httplib::Request &, httplib::Response &res) {
  21896. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21897. });
  21898. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21899. svr_.wait_until_ready();
  21900. }
  21901. void TearDown() override {
  21902. svr_.stop();
  21903. if (thread_.joinable()) thread_.join();
  21904. }
  21905. httplib::Server svr_;
  21906. std::thread thread_;
  21907. };
  21908. // stream::Get tests
  21909. TEST_F(StreamApiTest, GetBasic) {
  21910. httplib::Client cli(HOST, PORT);
  21911. auto result = httplib::stream::Get(cli, "/hello");
  21912. ASSERT_TRUE(result.is_valid());
  21913. EXPECT_EQ(200, result.status());
  21914. EXPECT_EQ("Hello World!", read_body(result));
  21915. }
  21916. TEST_F(StreamApiTest, GetWithParams) {
  21917. httplib::Client cli(HOST, PORT);
  21918. httplib::Params params{{"foo", "bar"}};
  21919. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21920. ASSERT_TRUE(result.is_valid());
  21921. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21922. }
  21923. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21924. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21925. httplib::Client cli(HOST, PORT);
  21926. cli.set_payload_max_length(0);
  21927. auto result = httplib::stream::Get(cli, "/hello");
  21928. ASSERT_TRUE(result.is_valid());
  21929. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21930. EXPECT_EQ("Hello World!", read_body(result));
  21931. }
  21932. #endif
  21933. TEST_F(StreamApiTest, GetConnectionError) {
  21934. httplib::Client cli(HOST, 9999);
  21935. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21936. }
  21937. TEST_F(StreamApiTest, Get404) {
  21938. httplib::Client cli(HOST, PORT);
  21939. auto result = httplib::stream::Get(cli, "/nonexistent");
  21940. EXPECT_TRUE(result.is_valid());
  21941. EXPECT_EQ(404, result.status());
  21942. }
  21943. // stream::Post tests
  21944. TEST_F(StreamApiTest, PostBasic) {
  21945. httplib::Client cli(HOST, PORT);
  21946. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21947. "application/json");
  21948. ASSERT_TRUE(result.is_valid());
  21949. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21950. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21951. }
  21952. TEST_F(StreamApiTest, PostWithHeaders) {
  21953. httplib::Client cli(HOST, PORT);
  21954. httplib::Headers headers{{"X-Custom", "value"}};
  21955. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21956. "text/plain");
  21957. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21958. }
  21959. TEST_F(StreamApiTest, PostWithParams) {
  21960. httplib::Client cli(HOST, PORT);
  21961. httplib::Params params{{"k", "v"}};
  21962. auto result =
  21963. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21964. auto body = read_body(result);
  21965. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21966. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21967. }
  21968. TEST_F(StreamApiTest, PostLarge) {
  21969. httplib::Client cli(HOST, PORT);
  21970. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21971. size_t total = 0;
  21972. while (result.next()) {
  21973. total += result.size();
  21974. }
  21975. EXPECT_EQ(100u * 1024u, total);
  21976. }
  21977. // stream::Put/Patch tests
  21978. TEST_F(StreamApiTest, PutAndPatch) {
  21979. httplib::Client cli(HOST, PORT);
  21980. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21981. EXPECT_EQ("PUT:test", read_body(put));
  21982. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21983. EXPECT_EQ("PATCH:test", read_body(patch));
  21984. }
  21985. // stream::Delete tests
  21986. TEST_F(StreamApiTest, Delete) {
  21987. httplib::Client cli(HOST, PORT);
  21988. auto del1 = httplib::stream::Delete(cli, "/resource");
  21989. EXPECT_EQ("Deleted", read_body(del1));
  21990. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21991. EXPECT_EQ("Deleted:data", read_body(del2));
  21992. }
  21993. // stream::Head/Options tests
  21994. TEST_F(StreamApiTest, HeadAndOptions) {
  21995. httplib::Client cli(HOST, PORT);
  21996. auto head = httplib::stream::Head(cli, "/head-test");
  21997. EXPECT_TRUE(head.is_valid());
  21998. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21999. auto opts = httplib::stream::Options(cli, "/options");
  22000. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22001. }
  22002. // SSL stream::* tests
  22003. #ifdef CPPHTTPLIB_SSL_ENABLED
  22004. class SSLStreamApiTest : public ::testing::Test {
  22005. protected:
  22006. void SetUp() override {
  22007. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22008. res.set_content("Hello SSL!", "text/plain");
  22009. });
  22010. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22011. res.set_content(req.body, "text/plain");
  22012. });
  22013. port_ = svr_.bind_to_any_port("127.0.0.1");
  22014. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22015. svr_.wait_until_ready();
  22016. }
  22017. void TearDown() override {
  22018. svr_.stop();
  22019. if (thread_.joinable()) thread_.join();
  22020. }
  22021. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22022. std::thread thread_;
  22023. int port_ = 0;
  22024. };
  22025. TEST_F(SSLStreamApiTest, GetAndPost) {
  22026. httplib::SSLClient cli("127.0.0.1", port_);
  22027. cli.enable_server_certificate_verification(false);
  22028. auto get = httplib::stream::Get(cli, "/hello");
  22029. EXPECT_EQ("Hello SSL!", read_body(get));
  22030. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22031. EXPECT_EQ("test", read_body(post));
  22032. }
  22033. #endif
  22034. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22035. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22036. // BodyReader
  22037. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22038. // Test that read timeout during streaming is detected
  22039. // Use a large content-length response where server delays mid-stream
  22040. Server svr;
  22041. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22042. // Send a large response with delay in the middle
  22043. res.set_content_provider(
  22044. 1000, // content_length
  22045. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22046. if (offset < 100) {
  22047. // Send first 100 bytes immediately
  22048. std::string data(100, 'A');
  22049. sink.write(data.c_str(), data.size());
  22050. return true;
  22051. }
  22052. // Then delay longer than client timeout
  22053. std::this_thread::sleep_for(std::chrono::seconds(3));
  22054. std::string data(900, 'B');
  22055. sink.write(data.c_str(), data.size());
  22056. return true;
  22057. });
  22058. });
  22059. auto port = 8091;
  22060. std::thread t([&]() { svr.listen("localhost", port); });
  22061. svr.wait_until_ready();
  22062. Client cli("localhost", port);
  22063. cli.set_read_timeout(1, 0); // 1 second timeout
  22064. auto handle = cli.open_stream("GET", "/slow-stream");
  22065. ASSERT_TRUE(handle.is_valid());
  22066. char buf[256];
  22067. ssize_t total = 0;
  22068. ssize_t n;
  22069. bool got_error = false;
  22070. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22071. total += n;
  22072. }
  22073. if (n < 0) {
  22074. got_error = true;
  22075. // Should be timeout or read error
  22076. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22077. handle.get_read_error() == Error::Read)
  22078. << "Actual error: " << to_string(handle.get_read_error());
  22079. }
  22080. // Either we got an error, or we got less data than expected
  22081. EXPECT_TRUE(got_error || total < 1000)
  22082. << "Expected timeout but got all " << total << " bytes";
  22083. svr.stop();
  22084. t.join();
  22085. }
  22086. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22087. // Test connection closed detection via BodyReader
  22088. Server svr;
  22089. std::atomic<bool> close_now{false};
  22090. svr.Get("/will-close", [&](const Request &, Response &res) {
  22091. res.set_content_provider(
  22092. 10000, // Large content_length that we won't fully send
  22093. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22094. if (offset < 100) {
  22095. std::string data(100, 'X');
  22096. sink.write(data.c_str(), data.size());
  22097. return true;
  22098. }
  22099. // Wait for signal then abort
  22100. while (!close_now) {
  22101. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22102. }
  22103. return false; // Abort - server will close connection
  22104. });
  22105. });
  22106. auto port = 8092;
  22107. std::thread t([&]() { svr.listen("localhost", port); });
  22108. svr.wait_until_ready();
  22109. Client cli("localhost", port);
  22110. auto handle = cli.open_stream("GET", "/will-close");
  22111. ASSERT_TRUE(handle.is_valid());
  22112. char buf[256];
  22113. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22114. EXPECT_GT(n, 0) << "First read should succeed";
  22115. // Signal server to close
  22116. close_now = true;
  22117. // Keep reading until error or EOF
  22118. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22119. // Keep reading
  22120. }
  22121. // Should get an error since content_length wasn't satisfied
  22122. if (n < 0) {
  22123. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22124. handle.get_read_error() == Error::Read)
  22125. << "Actual error: " << to_string(handle.get_read_error());
  22126. }
  22127. svr.stop();
  22128. t.join();
  22129. }
  22130. #ifdef CPPHTTPLIB_SSL_ENABLED
  22131. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22132. // Test that read timeout during SSL streaming is detected
  22133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22134. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22135. res.set_content_provider(
  22136. 1000, "text/plain",
  22137. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22138. if (offset < 100) {
  22139. std::string data(100, 'A');
  22140. sink.write(data.c_str(), data.size());
  22141. return true;
  22142. }
  22143. std::this_thread::sleep_for(std::chrono::seconds(3));
  22144. std::string data(900, 'B');
  22145. sink.write(data.c_str(), data.size());
  22146. return true;
  22147. });
  22148. });
  22149. auto port = 8093;
  22150. std::thread t([&]() { svr.listen("localhost", port); });
  22151. svr.wait_until_ready();
  22152. SSLClient cli("localhost", port);
  22153. cli.enable_server_certificate_verification(false);
  22154. cli.set_read_timeout(1, 0); // 1 second timeout
  22155. auto handle = cli.open_stream("GET", "/slow-stream");
  22156. ASSERT_TRUE(handle.is_valid());
  22157. char buf[256];
  22158. ssize_t total = 0;
  22159. ssize_t n;
  22160. bool got_error = false;
  22161. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22162. total += n;
  22163. }
  22164. if (n < 0) {
  22165. got_error = true;
  22166. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22167. handle.get_read_error() == Error::Read)
  22168. << "Actual error: " << to_string(handle.get_read_error());
  22169. }
  22170. EXPECT_TRUE(got_error || total < 1000)
  22171. << "Expected timeout but got all " << total << " bytes";
  22172. svr.stop();
  22173. t.join();
  22174. }
  22175. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22176. // Test SSL connection closed detection
  22177. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22178. std::atomic<bool> close_now{false};
  22179. svr.Get("/will-close", [&](const Request &, Response &res) {
  22180. res.set_content_provider(
  22181. 10000, "text/plain",
  22182. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22183. if (offset < 100) {
  22184. std::string data(100, 'X');
  22185. sink.write(data.c_str(), data.size());
  22186. return true;
  22187. }
  22188. while (!close_now) {
  22189. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22190. }
  22191. return false;
  22192. });
  22193. });
  22194. auto port = 8094;
  22195. std::thread t([&]() { svr.listen("localhost", port); });
  22196. svr.wait_until_ready();
  22197. SSLClient cli("localhost", port);
  22198. cli.enable_server_certificate_verification(false);
  22199. auto handle = cli.open_stream("GET", "/will-close");
  22200. ASSERT_TRUE(handle.is_valid());
  22201. char buf[256];
  22202. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22203. EXPECT_GT(n, 0);
  22204. // Signal server to close
  22205. close_now = true;
  22206. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22207. // Keep reading
  22208. }
  22209. if (n < 0) {
  22210. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22211. handle.get_read_error() == Error::Read)
  22212. << "Actual error: " << to_string(handle.get_read_error());
  22213. }
  22214. svr.stop();
  22215. t.join();
  22216. }
  22217. #endif
  22218. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22219. using namespace httplib;
  22220. // Create a test file
  22221. const char *fname = "etag_testfile.txt";
  22222. const char *content = "etag-content";
  22223. {
  22224. std::ofstream ofs(fname);
  22225. ofs << content;
  22226. ASSERT_TRUE(ofs.good());
  22227. }
  22228. Server svr;
  22229. svr.set_mount_point("/static", ".");
  22230. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22231. svr.wait_until_ready();
  22232. Client cli(HOST, PORT);
  22233. // First request: should get 200 with ETag header
  22234. auto res1 = cli.Get("/static/etag_testfile.txt");
  22235. ASSERT_TRUE(res1);
  22236. ASSERT_EQ(200, res1->status);
  22237. ASSERT_TRUE(res1->has_header("ETag"));
  22238. std::string etag = res1->get_header_value("ETag");
  22239. EXPECT_FALSE(etag.empty());
  22240. // Verify ETag format: W/"hex-hex"
  22241. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22242. EXPECT_EQ('W', etag[0]);
  22243. EXPECT_EQ('/', etag[1]);
  22244. EXPECT_EQ('"', etag[2]);
  22245. EXPECT_EQ('"', etag.back());
  22246. // Exact match: expect 304 Not Modified
  22247. Headers h2 = {{"If-None-Match", etag}};
  22248. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22249. ASSERT_TRUE(res2);
  22250. EXPECT_EQ(304, res2->status);
  22251. // Wildcard match: expect 304 Not Modified
  22252. Headers h3 = {{"If-None-Match", "*"}};
  22253. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22254. ASSERT_TRUE(res3);
  22255. EXPECT_EQ(304, res3->status);
  22256. // Non-matching ETag: expect 200
  22257. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22258. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22259. ASSERT_TRUE(res4);
  22260. EXPECT_EQ(200, res4->status);
  22261. // Multiple ETags with one matching: expect 304
  22262. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22263. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22264. ASSERT_TRUE(res5);
  22265. EXPECT_EQ(304, res5->status);
  22266. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22267. // that equivalent to the single comma-separated list above, so the match on
  22268. // the second line must still be found.
  22269. Headers h6;
  22270. h6.emplace("If-None-Match", "W/\"other\"");
  22271. h6.emplace("If-None-Match", etag);
  22272. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22273. ASSERT_TRUE(res6);
  22274. EXPECT_EQ(304, res6->status);
  22275. svr.stop();
  22276. t.join();
  22277. std::remove(fname);
  22278. }
  22279. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22280. using namespace httplib;
  22281. Server svr;
  22282. svr.set_mount_point("/static", ".");
  22283. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22284. svr.wait_until_ready();
  22285. Client cli(HOST, PORT);
  22286. // Send If-None-Match: * to a non-existent file
  22287. Headers h = {{"If-None-Match", "*"}};
  22288. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22290. EXPECT_EQ(404, res->status);
  22291. svr.stop();
  22292. t.join();
  22293. }
  22294. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22295. using namespace httplib;
  22296. // Create a test file
  22297. const char *fname = "etag_boundary_testfile.txt";
  22298. const char *content = "boundary-test";
  22299. {
  22300. std::ofstream ofs(fname);
  22301. ofs << content;
  22302. ASSERT_TRUE(ofs.good());
  22303. }
  22304. Server svr;
  22305. svr.set_mount_point("/static", ".");
  22306. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22307. svr.wait_until_ready();
  22308. Client cli(HOST, PORT);
  22309. // Get the actual ETag
  22310. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22311. ASSERT_TRUE(res1);
  22312. ASSERT_EQ(200, res1->status);
  22313. ASSERT_TRUE(res1->has_header("ETag"));
  22314. std::string etag = res1->get_header_value("ETag");
  22315. // Test 1: Very long ETag value (longer than actual ETag)
  22316. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22317. Headers h1 = {{"If-None-Match", "W/"
  22318. "\"very-long-etag-value-that-is-much-longer-"
  22319. "than-the-actual-etag-value\""}};
  22320. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22321. ASSERT_TRUE(res2);
  22322. EXPECT_EQ(200, res2->status); // Should not match
  22323. // Test 2: Long string followed by wildcard
  22324. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22325. // string)
  22326. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22327. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22328. ASSERT_TRUE(res3);
  22329. EXPECT_EQ(304, res3->status); // Should match on "*"
  22330. // Test 3: Wildcard followed by long string
  22331. // Should match on "*" immediately and return 304
  22332. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22333. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22334. ASSERT_TRUE(res4);
  22335. EXPECT_EQ(304, res4->status); // Should match on "*"
  22336. // Test 4: Multiple long non-matching values
  22337. // Should NOT match and return 200 (test that all comparisons are safe)
  22338. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22339. "W/\"second-long-non-matching-value\", "
  22340. "W/\"third-long-non-matching-value\""}};
  22341. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22342. ASSERT_TRUE(res5);
  22343. EXPECT_EQ(200, res5->status); // Should not match
  22344. // Test 5: Single character that is not "*" (edge case)
  22345. Headers h5 = {{"If-None-Match", "X"}};
  22346. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22347. ASSERT_TRUE(res6);
  22348. EXPECT_EQ(200, res6->status); // Should not match
  22349. svr.stop();
  22350. t.join();
  22351. std::remove(fname);
  22352. }
  22353. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22354. using namespace httplib;
  22355. // Create a test file
  22356. const char *fname = "ims_testfile.txt";
  22357. const char *content = "if-modified-since-test";
  22358. {
  22359. std::ofstream ofs(fname);
  22360. ofs << content;
  22361. ASSERT_TRUE(ofs.good());
  22362. }
  22363. Server svr;
  22364. svr.set_mount_point("/static", ".");
  22365. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22366. svr.wait_until_ready();
  22367. Client cli(HOST, PORT);
  22368. // First request: should get 200 with Last-Modified header
  22369. auto res1 = cli.Get("/static/ims_testfile.txt");
  22370. ASSERT_TRUE(res1);
  22371. ASSERT_EQ(200, res1->status);
  22372. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22373. std::string last_modified = res1->get_header_value("Last-Modified");
  22374. EXPECT_FALSE(last_modified.empty());
  22375. // If-Modified-Since with same time: expect 304
  22376. Headers h2 = {{"If-Modified-Since", last_modified}};
  22377. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22378. ASSERT_TRUE(res2);
  22379. EXPECT_EQ(304, res2->status);
  22380. // If-Modified-Since with future time: expect 304
  22381. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22382. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22383. ASSERT_TRUE(res3);
  22384. EXPECT_EQ(304, res3->status);
  22385. // If-Modified-Since with past time: expect 200
  22386. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22387. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22388. ASSERT_TRUE(res4);
  22389. EXPECT_EQ(200, res4->status);
  22390. // If-None-Match takes precedence over If-Modified-Since
  22391. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22392. ASSERT_TRUE(res1->has_header("ETag"));
  22393. std::string etag = res1->get_header_value("ETag");
  22394. Headers h5 = {{"If-None-Match", etag},
  22395. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22396. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22397. ASSERT_TRUE(res5);
  22398. EXPECT_EQ(304, res5->status);
  22399. svr.stop();
  22400. t.join();
  22401. std::remove(fname);
  22402. }
  22403. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22404. using namespace httplib;
  22405. Server svr;
  22406. // Endpoint that returns compressible content
  22407. svr.Get("/compressible", [](const Request &, Response &res) {
  22408. // Return a large enough body to trigger compression
  22409. std::string body(1000, 'a');
  22410. res.set_content(body, "text/plain");
  22411. });
  22412. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22413. svr.wait_until_ready();
  22414. Client cli(HOST, PORT);
  22415. // Request with gzip support: should get Vary header when compressed
  22416. cli.set_compress(true);
  22417. auto res1 = cli.Get("/compressible");
  22418. ASSERT_TRUE(res1);
  22419. EXPECT_EQ(200, res1->status);
  22420. // If Content-Encoding is set, Vary should also be set
  22421. if (res1->has_header("Content-Encoding")) {
  22422. EXPECT_TRUE(res1->has_header("Vary"));
  22423. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22424. }
  22425. // Request without Accept-Encoding header: should not have compression
  22426. Headers h_no_compress;
  22427. auto res2 = cli.Get("/compressible", h_no_compress);
  22428. ASSERT_TRUE(res2);
  22429. EXPECT_EQ(200, res2->status);
  22430. // Verify Vary header is present when compression is applied
  22431. // (the exact behavior depends on server configuration)
  22432. svr.stop();
  22433. t.join();
  22434. }
  22435. TEST(ETagTest, IfRangeWithETag) {
  22436. using namespace httplib;
  22437. // Create a test file with known content
  22438. const char *fname = "if_range_testfile.txt";
  22439. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22440. {
  22441. std::ofstream ofs(fname);
  22442. ofs << content;
  22443. ASSERT_TRUE(ofs.good());
  22444. }
  22445. Server svr;
  22446. svr.set_mount_point("/static", ".");
  22447. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22448. svr.wait_until_ready();
  22449. Client cli(HOST, PORT);
  22450. // First request: get ETag
  22451. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22452. ASSERT_TRUE(res1);
  22453. ASSERT_EQ(200, res1->status);
  22454. ASSERT_TRUE(res1->has_header("ETag"));
  22455. std::string etag = res1->get_header_value("ETag");
  22456. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22457. // Since our server generates weak ETags (W/"..."), If-Range with our
  22458. // ETag should NOT result in partial content - it should return full content.
  22459. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22460. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22461. ASSERT_TRUE(res2);
  22462. // Weak ETag in If-Range -> full content (200), not partial (206)
  22463. EXPECT_EQ(200, res2->status);
  22464. EXPECT_EQ(content, res2->body);
  22465. EXPECT_FALSE(res2->has_header("Content-Range"));
  22466. // Range request with non-matching If-Range (ETag): should get 200 (full
  22467. // content)
  22468. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22469. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22470. ASSERT_TRUE(res3);
  22471. EXPECT_EQ(200, res3->status);
  22472. EXPECT_EQ(content, res3->body);
  22473. EXPECT_FALSE(res3->has_header("Content-Range"));
  22474. // Range request with strong ETag (hypothetical - our server doesn't generate
  22475. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22476. // should return full content)
  22477. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22478. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22479. ASSERT_TRUE(res4);
  22480. EXPECT_EQ(200, res4->status);
  22481. EXPECT_EQ(content, res4->body);
  22482. EXPECT_FALSE(res4->has_header("Content-Range"));
  22483. svr.stop();
  22484. t.join();
  22485. std::remove(fname);
  22486. }
  22487. TEST(ETagTest, IfRangeWithDate) {
  22488. using namespace httplib;
  22489. // Create a test file
  22490. const char *fname = "if_range_date_testfile.txt";
  22491. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22492. {
  22493. std::ofstream ofs(fname);
  22494. ofs << content;
  22495. ASSERT_TRUE(ofs.good());
  22496. }
  22497. Server svr;
  22498. svr.set_mount_point("/static", ".");
  22499. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22500. svr.wait_until_ready();
  22501. Client cli(HOST, PORT);
  22502. // First request: get Last-Modified
  22503. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22504. ASSERT_TRUE(res1);
  22505. ASSERT_EQ(200, res1->status);
  22506. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22507. std::string last_modified = res1->get_header_value("Last-Modified");
  22508. // Range request with matching If-Range (date): should get 206
  22509. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22510. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22511. ASSERT_TRUE(res2);
  22512. EXPECT_EQ(206, res2->status);
  22513. EXPECT_EQ("FGHIJ", res2->body);
  22514. // Range request with old If-Range date: should get 200 (full content)
  22515. Headers h3 = {{"Range", "bytes=5-9"},
  22516. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22517. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22518. ASSERT_TRUE(res3);
  22519. EXPECT_EQ(200, res3->status);
  22520. EXPECT_EQ(content, res3->body);
  22521. // Range request with future If-Range date: should get 206
  22522. Headers h4 = {{"Range", "bytes=0-4"},
  22523. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22524. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22525. ASSERT_TRUE(res4);
  22526. EXPECT_EQ(206, res4->status);
  22527. EXPECT_EQ("ABCDE", res4->body);
  22528. svr.stop();
  22529. t.join();
  22530. std::remove(fname);
  22531. }
  22532. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22533. using namespace httplib;
  22534. const char *fname = "etag_malformed.txt";
  22535. const char *content = "malformed-etag";
  22536. {
  22537. std::ofstream ofs(fname);
  22538. ofs << content;
  22539. ASSERT_TRUE(ofs.good());
  22540. }
  22541. Server svr;
  22542. svr.set_mount_point("/static", ".");
  22543. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22544. svr.wait_until_ready();
  22545. Client cli(HOST, PORT);
  22546. // baseline: should get 200 and an ETag
  22547. auto res1 = cli.Get("/static/etag_malformed.txt");
  22548. ASSERT_TRUE(res1);
  22549. ASSERT_EQ(200, res1->status);
  22550. ASSERT_TRUE(res1->has_header("ETag"));
  22551. // Malformed ETag value (missing quotes) should be treated as non-matching
  22552. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22553. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22554. ASSERT_TRUE(res_bad);
  22555. EXPECT_EQ(200, res_bad->status);
  22556. // Whitespace-only header value should be considered invalid / non-matching
  22557. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22558. "Host: localhost\r\n"
  22559. "If-None-Match: \r\n"
  22560. "Connection: close\r\n"
  22561. "\r\n";
  22562. std::string out;
  22563. ASSERT_TRUE(send_request(5, raw_req, &out));
  22564. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22565. svr.stop();
  22566. t.join();
  22567. std::remove(fname);
  22568. }
  22569. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22570. using namespace httplib;
  22571. const char *fname = "ims_invalid_format.txt";
  22572. const char *content = "ims-bad-format";
  22573. {
  22574. std::ofstream ofs(fname);
  22575. ofs << content;
  22576. ASSERT_TRUE(ofs.good());
  22577. }
  22578. Server svr;
  22579. svr.set_mount_point("/static", ".");
  22580. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22581. svr.wait_until_ready();
  22582. Client cli(HOST, PORT);
  22583. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22584. ASSERT_TRUE(res1);
  22585. ASSERT_EQ(200, res1->status);
  22586. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22587. // If-Modified-Since with invalid format should not result in 304
  22588. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22589. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22590. ASSERT_TRUE(res_bad);
  22591. EXPECT_EQ(200, res_bad->status);
  22592. // If-Range with invalid date format should be treated as mismatch -> full
  22593. // content (200)
  22594. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22595. {"If-Range", "invalid-date"}};
  22596. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22597. ASSERT_TRUE(res_ifrange);
  22598. EXPECT_EQ(200, res_ifrange->status);
  22599. svr.stop();
  22600. t.join();
  22601. std::remove(fname);
  22602. }
  22603. TEST(ETagTest, IfRangeWithMalformedETag) {
  22604. using namespace httplib;
  22605. const char *fname = "ifrange_malformed.txt";
  22606. const std::string content = "0123456789";
  22607. {
  22608. std::ofstream ofs(fname);
  22609. ofs << content;
  22610. ASSERT_TRUE(ofs.good());
  22611. }
  22612. Server svr;
  22613. svr.set_mount_point("/static", ".");
  22614. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22615. svr.wait_until_ready();
  22616. Client cli(HOST, PORT);
  22617. // First request: get ETag
  22618. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22619. ASSERT_TRUE(res1);
  22620. ASSERT_EQ(200, res1->status);
  22621. ASSERT_TRUE(res1->has_header("ETag"));
  22622. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22623. // full content (200)
  22624. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22625. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22626. ASSERT_TRUE(res2);
  22627. EXPECT_EQ(200, res2->status);
  22628. EXPECT_EQ(content, res2->body);
  22629. svr.stop();
  22630. t.join();
  22631. std::remove(fname);
  22632. }
  22633. TEST(ETagTest, ExtremeLargeDateValues) {
  22634. using namespace httplib;
  22635. const char *fname = "ims_extreme_date.txt";
  22636. const char *content = "ims-extreme-date";
  22637. {
  22638. std::ofstream ofs(fname);
  22639. ofs << content;
  22640. ASSERT_TRUE(ofs.good());
  22641. }
  22642. Server svr;
  22643. svr.set_mount_point("/static", ".");
  22644. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22645. svr.wait_until_ready();
  22646. Client cli(HOST, PORT);
  22647. auto res1 = cli.Get(std::string("/static/") + fname);
  22648. ASSERT_TRUE(res1);
  22649. ASSERT_EQ(200, res1->status);
  22650. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22651. // Extremely large year that may overflow date parsing routines.
  22652. Headers h_large_date = {
  22653. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22654. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22655. ASSERT_TRUE(res_bad);
  22656. // Expect server to treat this as invalid/mismatch and return full content
  22657. EXPECT_EQ(200, res_bad->status);
  22658. // If-Range with extremely large date should be treated as mismatch -> full
  22659. // content (200)
  22660. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22661. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22662. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22663. ASSERT_TRUE(res_ifrange);
  22664. EXPECT_EQ(200, res_ifrange->status);
  22665. svr.stop();
  22666. t.join();
  22667. std::remove(fname);
  22668. }
  22669. TEST(ETagTest, NegativeFileModificationTime) {
  22670. using namespace httplib;
  22671. const char *fname = "ims_negative_mtime.txt";
  22672. const std::string content = "negative-mtime";
  22673. {
  22674. std::ofstream ofs(fname);
  22675. ofs << content;
  22676. ASSERT_TRUE(ofs.good());
  22677. }
  22678. // Try to set file mtime to a negative value. This may fail on some
  22679. // platforms/filesystems; if it fails, the test will still verify server
  22680. // behaves safely by performing a regular conditional request.
  22681. #if defined(__APPLE__) || defined(__linux__)
  22682. bool set_negative = false;
  22683. do {
  22684. struct timeval times[2];
  22685. // access time: now
  22686. times[0].tv_sec = time(nullptr);
  22687. times[0].tv_usec = 0;
  22688. // modification time: negative (e.g., -1)
  22689. times[1].tv_sec = -1;
  22690. times[1].tv_usec = 0;
  22691. if (utimes(fname, times) == 0) { set_negative = true; }
  22692. } while (0);
  22693. #else
  22694. bool set_negative = false;
  22695. #endif
  22696. Server svr;
  22697. svr.set_mount_point("/static", ".");
  22698. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22699. svr.wait_until_ready();
  22700. Client cli(HOST, PORT);
  22701. auto res1 = cli.Get(std::string("/static/") + fname);
  22702. ASSERT_TRUE(res1);
  22703. ASSERT_EQ(200, res1->status);
  22704. bool has_last_modified = res1->has_header("Last-Modified");
  22705. std::string last_modified;
  22706. if (has_last_modified) {
  22707. last_modified = res1->get_header_value("Last-Modified");
  22708. }
  22709. if (set_negative) {
  22710. // If we successfully set a negative mtime, ensure server returns a
  22711. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22712. // with an old date and ensure server handles it without crash.
  22713. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22714. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22715. ASSERT_TRUE(res2);
  22716. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22717. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22718. } else {
  22719. // Could not set negative mtime on this platform; fall back to verifying
  22720. // that normal invalid/malformed dates are treated safely (non-304).
  22721. Headers h_bad_date = {
  22722. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22723. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22724. ASSERT_TRUE(res_bad);
  22725. EXPECT_EQ(200, res_bad->status);
  22726. }
  22727. svr.stop();
  22728. t.join();
  22729. std::remove(fname);
  22730. }
  22731. //==============================================================================
  22732. // Integration Tests with Server
  22733. //==============================================================================
  22734. class SSEIntegrationTest : public ::testing::Test {
  22735. protected:
  22736. void SetUp() override {
  22737. stop_server_.store(false);
  22738. events_.clear();
  22739. server_ = httplib::detail::make_unique<Server>();
  22740. setup_server();
  22741. start_server();
  22742. }
  22743. void TearDown() override {
  22744. stop_server_.store(true);
  22745. event_cv_.notify_all();
  22746. server_->stop();
  22747. if (server_thread_.joinable()) { server_thread_.join(); }
  22748. }
  22749. void setup_server() {
  22750. // Simple SSE endpoint
  22751. server_->Get("/events", [this](const Request &req, Response &res) {
  22752. auto last_id = req.get_header_value("Last-Event-ID");
  22753. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22754. res.set_chunked_content_provider(
  22755. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22756. std::unique_lock<std::mutex> lock(event_mutex_);
  22757. if (event_cv_.wait_for(
  22758. lock, std::chrono::milliseconds(200), [this] {
  22759. return !events_.empty() || stop_server_.load();
  22760. })) {
  22761. if (stop_server_.load()) { return false; }
  22762. if (!events_.empty()) {
  22763. std::string event = events_.front();
  22764. events_.erase(events_.begin());
  22765. sink.write(event.data(), event.size());
  22766. return true;
  22767. }
  22768. }
  22769. return !stop_server_.load();
  22770. });
  22771. });
  22772. // Endpoint that returns error
  22773. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22774. res.status = 500;
  22775. res.set_content("Internal Server Error", "text/plain");
  22776. });
  22777. // Endpoint for custom event types
  22778. server_->Get("/custom-events", [](const Request &, Response &res) {
  22779. res.set_chunked_content_provider(
  22780. "text/event-stream", [](size_t offset, DataSink &sink) {
  22781. if (offset == 0) {
  22782. std::string event = "event: update\ndata: updated\n\n"
  22783. "event: delete\ndata: deleted\n\n";
  22784. sink.write(event.data(), event.size());
  22785. }
  22786. return false; // End stream after sending
  22787. });
  22788. });
  22789. }
  22790. void start_server() {
  22791. port_ = server_->bind_to_any_port(HOST);
  22792. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22793. // Wait for server to start
  22794. while (!server_->is_running()) {
  22795. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22796. }
  22797. }
  22798. int get_port() const { return port_; }
  22799. void send_event(const std::string &event) {
  22800. std::lock_guard<std::mutex> lock(event_mutex_);
  22801. events_.push_back(event);
  22802. event_cv_.notify_all();
  22803. }
  22804. std::unique_ptr<Server> server_;
  22805. std::thread server_thread_;
  22806. std::mutex event_mutex_;
  22807. std::condition_variable event_cv_;
  22808. std::vector<std::string> events_;
  22809. std::atomic<bool> stop_server_{false};
  22810. std::string last_received_event_id_;
  22811. int port_ = 0;
  22812. };
  22813. //==============================================================================
  22814. // SSE Parser Tests
  22815. //==============================================================================
  22816. struct SSEParseResult {
  22817. std::vector<sse::SSEMessage> events;
  22818. std::vector<std::string> ids;
  22819. std::vector<int> retries;
  22820. bool ok = true;
  22821. std::string trace; // Every handler call in order
  22822. };
  22823. static SSEParseResult
  22824. sse_parse(const std::vector<std::string> &chunks,
  22825. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  22826. SSEParseResult r;
  22827. detail::SSEParser parser(
  22828. [&](const sse::SSEMessage &msg) {
  22829. r.events.push_back(msg);
  22830. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  22831. },
  22832. [&](const std::string &id) {
  22833. r.ids.push_back(id);
  22834. r.trace += "id[" + id + "]";
  22835. },
  22836. [&](int retry_ms) {
  22837. r.retries.push_back(retry_ms);
  22838. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  22839. },
  22840. max_event_length);
  22841. for (const auto &chunk : chunks) {
  22842. if (!parser.parse(chunk.data(), chunk.size())) {
  22843. r.ok = false;
  22844. break;
  22845. }
  22846. }
  22847. return r;
  22848. }
  22849. static SSEParseResult sse_parse(const std::string &stream) {
  22850. return sse_parse(std::vector<std::string>{stream});
  22851. }
  22852. TEST(SSEParserTest, SingleLineData) {
  22853. auto r = sse_parse("data: hello\n\n");
  22854. ASSERT_EQ(r.events.size(), 1u);
  22855. EXPECT_EQ(r.events[0].data, "hello");
  22856. EXPECT_EQ(r.events[0].event, "message");
  22857. }
  22858. TEST(SSEParserTest, MultiLineData) {
  22859. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  22860. ASSERT_EQ(r.events.size(), 1u);
  22861. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  22862. }
  22863. TEST(SSEParserTest, CustomEventType) {
  22864. auto r = sse_parse("event: update\ndata: payload\n\n");
  22865. ASSERT_EQ(r.events.size(), 1u);
  22866. EXPECT_EQ(r.events[0].event, "update");
  22867. EXPECT_EQ(r.events[0].data, "payload");
  22868. }
  22869. TEST(SSEParserTest, EventIdHandling) {
  22870. auto r = sse_parse("id: 12345\ndata: test\n\n");
  22871. ASSERT_EQ(r.events.size(), 1u);
  22872. EXPECT_EQ(r.events[0].id, "12345");
  22873. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  22874. }
  22875. TEST(SSEParserTest, EmptyEventId) {
  22876. auto r = sse_parse("id:\ndata: test\n\n");
  22877. ASSERT_EQ(r.events.size(), 1u);
  22878. EXPECT_EQ(r.events[0].id, "");
  22879. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  22880. }
  22881. TEST(SSEParserTest, CommentsIgnored) {
  22882. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  22883. ASSERT_EQ(r.events.size(), 1u);
  22884. EXPECT_EQ(r.events[0].data, "hello");
  22885. EXPECT_EQ(r.events[0].event, "message");
  22886. }
  22887. TEST(SSEParserTest, ColonInValue) {
  22888. auto r = sse_parse("data: hello:world:test\n\n");
  22889. ASSERT_EQ(r.events.size(), 1u);
  22890. EXPECT_EQ(r.events[0].data, "hello:world:test");
  22891. }
  22892. TEST(SSEParserTest, FieldNameOnly) {
  22893. // A line without a colon is a field name with an empty value
  22894. auto r = sse_parse("data\n\n");
  22895. ASSERT_EQ(r.events.size(), 1u);
  22896. EXPECT_EQ(r.events[0].data, "");
  22897. }
  22898. TEST(SSEParserTest, TrailingCarriageReturn) {
  22899. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  22900. ASSERT_EQ(r.events.size(), 1u);
  22901. EXPECT_EQ(r.events[0].event, "update");
  22902. EXPECT_EQ(r.events[0].data, "hello");
  22903. }
  22904. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  22905. auto r = sse_parse("data\r\n\r\n");
  22906. ASSERT_EQ(r.events.size(), 1u);
  22907. EXPECT_EQ(r.events[0].data, "");
  22908. }
  22909. TEST(SSEParserTest, CarriageReturnLineEnding) {
  22910. auto r = sse_parse("event: update\rdata: hello\r\r");
  22911. ASSERT_EQ(r.events.size(), 1u);
  22912. EXPECT_EQ(r.events[0].event, "update");
  22913. EXPECT_EQ(r.events[0].data, "hello");
  22914. }
  22915. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  22916. // Chunk boundaries fall inside every \r\n and right before the first one
  22917. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  22918. "\ndata: hello\r", "\n\r", "\n"});
  22919. ASSERT_EQ(r.events.size(), 1u);
  22920. EXPECT_EQ(r.events[0].event, "update");
  22921. EXPECT_EQ(r.events[0].data, "hello");
  22922. }
  22923. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  22924. // Only a BOM at the start of the stream is ignored
  22925. auto r = sse_parse("\xEF\xBB\xBF"
  22926. "data: first\n\n"
  22927. "\xEF\xBB\xBF"
  22928. "data: second\n\n");
  22929. ASSERT_EQ(r.events.size(), 1u);
  22930. EXPECT_EQ(r.events[0].data, "first");
  22931. }
  22932. TEST(SSEParserTest, UnknownFieldsIgnored) {
  22933. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  22934. ASSERT_EQ(r.events.size(), 1u);
  22935. EXPECT_EQ(r.events[0].data, "hello");
  22936. EXPECT_EQ(r.events[0].event, "message");
  22937. }
  22938. TEST(SSEParserTest, SpaceAfterColonOptional) {
  22939. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  22940. ASSERT_EQ(r.events.size(), 2u);
  22941. EXPECT_EQ(r.events[0].data, "hello");
  22942. EXPECT_EQ(r.events[1].data, "hello");
  22943. }
  22944. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  22945. // An event without data is not dispatched, and its type must not leak
  22946. // into the next event
  22947. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  22948. ASSERT_EQ(r.events.size(), 1u);
  22949. EXPECT_EQ(r.events[0].event, "message");
  22950. EXPECT_EQ(r.events[0].data, "hello");
  22951. }
  22952. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  22953. // Also when the empty field replaces an earlier type
  22954. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22955. ASSERT_EQ(r.events.size(), 2u);
  22956. EXPECT_EQ(r.events[0].event, "message");
  22957. EXPECT_EQ(r.events[1].event, "message");
  22958. }
  22959. TEST(SSEParserTest, EventWithoutDataReportsId) {
  22960. auto r = sse_parse("id: 42\n\n");
  22961. EXPECT_TRUE(r.events.empty());
  22962. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  22963. }
  22964. TEST(SSEParserTest, EmptyEventIdClearsId) {
  22965. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  22966. ASSERT_EQ(r.events.size(), 2u);
  22967. EXPECT_EQ(r.events[0].id, "1");
  22968. EXPECT_EQ(r.events[1].id, "");
  22969. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  22970. }
  22971. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  22972. // Ids that cannot be carried in a Last-Event-ID header
  22973. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  22974. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  22975. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  22976. }
  22977. TEST(SSEParserTest, RetryDigitsOnly) {
  22978. auto r = sse_parse("retry: 1000\n");
  22979. EXPECT_EQ(r.retries, std::vector<int>{1000});
  22980. // A value that is not all ASCII digits, or does not fit, is ignored
  22981. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  22982. EXPECT_TRUE(r.retries.empty());
  22983. }
  22984. TEST(SSEParserTest, CompleteEventParsing) {
  22985. auto r = sse_parse("event: notification\nid: evt-42\n"
  22986. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22987. ASSERT_EQ(r.events.size(), 1u);
  22988. EXPECT_EQ(r.events[0].event, "notification");
  22989. EXPECT_EQ(r.events[0].id, "evt-42");
  22990. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  22991. EXPECT_EQ(r.retries, std::vector<int>{1000});
  22992. }
  22993. TEST(SSEParserTest, IncompleteEventNotReported) {
  22994. // An event still waiting for its blank line when the stream ends is
  22995. // discarded per the SSE spec
  22996. auto r = sse_parse("id: 1\ndata: x\n");
  22997. EXPECT_TRUE(r.events.empty());
  22998. EXPECT_TRUE(r.ids.empty());
  22999. }
  23000. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23001. const std::vector<std::string> streams = {
  23002. "\xEF\xBB\xBF"
  23003. "data: bom\r\n\r\n",
  23004. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23005. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23006. };
  23007. for (const auto &stream : streams) {
  23008. auto expected = sse_parse(stream).trace;
  23009. ASSERT_FALSE(expected.empty());
  23010. for (size_t i = 0; i <= stream.size(); i++) {
  23011. auto r = sse_parse(
  23012. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23013. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23014. }
  23015. std::vector<std::string> bytes;
  23016. for (auto c : stream) {
  23017. bytes.emplace_back(1, c);
  23018. }
  23019. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23020. }
  23021. }
  23022. TEST(SSEParserTest, MaxEventLength) {
  23023. // A line still waiting for its end
  23024. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23025. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23026. // Data accumulated over the lines of one event
  23027. EXPECT_TRUE(
  23028. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23029. EXPECT_FALSE(
  23030. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23031. // 0 means no limit
  23032. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23033. // Events completed in the same chunk are still reported
  23034. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23035. EXPECT_FALSE(r.ok);
  23036. ASSERT_EQ(r.events.size(), 1u);
  23037. EXPECT_EQ(r.events[0].data, "a");
  23038. }
  23039. TEST(SSEMessageTest, Clear) {
  23040. sse::SSEMessage msg;
  23041. msg.event = "custom";
  23042. msg.data = "some data";
  23043. msg.id = "123";
  23044. msg.clear();
  23045. EXPECT_EQ(msg.event, "message");
  23046. EXPECT_EQ(msg.data, "");
  23047. EXPECT_EQ(msg.id, "");
  23048. }
  23049. //==============================================================================
  23050. // SSE Integration Tests
  23051. //==============================================================================
  23052. // Test: Successful connection and on_open callback
  23053. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23054. // Add a simple endpoint that sends one event and closes
  23055. server_->Get("/simple-event", [](const Request &, Response &res) {
  23056. res.set_chunked_content_provider(
  23057. "text/event-stream", [](size_t offset, DataSink &sink) {
  23058. if (offset == 0) {
  23059. std::string event = "data: hello\n\n";
  23060. sink.write(event.data(), event.size());
  23061. }
  23062. return false; // Close stream after sending
  23063. });
  23064. });
  23065. Client client("localhost", get_port());
  23066. sse::SSEClient sse(client, "/simple-event");
  23067. std::atomic<bool> open_called{false};
  23068. std::atomic<bool> message_received{false};
  23069. sse.on_open([&open_called]() { open_called.store(true); });
  23070. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23071. if (msg.data == "hello") { message_received.store(true); }
  23072. });
  23073. sse.set_reconnect_interval(100);
  23074. sse.set_max_reconnect_attempts(1);
  23075. // Start async
  23076. sse.start_async();
  23077. // Wait for message to be processed
  23078. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23079. sse.stop();
  23080. EXPECT_TRUE(open_called.load());
  23081. EXPECT_TRUE(message_received.load());
  23082. }
  23083. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23084. // A data line that never ends.
  23085. server_->Get("/endless-line", [](const Request &, Response &res) {
  23086. res.set_chunked_content_provider(
  23087. "text/event-stream", [](size_t offset, DataSink &sink) {
  23088. if (offset == 0) { sink.write("data: ", 6); }
  23089. std::string chunk(64 * 1024, 'A');
  23090. return sink.write(chunk.data(), chunk.size());
  23091. });
  23092. });
  23093. Client client("localhost", get_port());
  23094. sse::SSEClient sse(client, "/endless-line");
  23095. std::atomic<bool> too_long{false};
  23096. sse.on_error([&](Error err) {
  23097. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23098. });
  23099. sse.set_max_reconnect_attempts(1);
  23100. sse.start_async();
  23101. for (int i = 0; i < 500 && !too_long; i++) {
  23102. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23103. }
  23104. sse.stop();
  23105. EXPECT_TRUE(too_long);
  23106. }
  23107. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23108. // Far more in all than the client's payload limit below.
  23109. server_->Get("/many-events", [](const Request &, Response &res) {
  23110. res.set_chunked_content_provider(
  23111. "text/event-stream", [](size_t offset, DataSink &sink) {
  23112. if (offset == 0) {
  23113. std::string events;
  23114. for (int i = 0; i < 1000; i++) {
  23115. events += "data: message\n\n";
  23116. }
  23117. sink.write(events.data(), events.size());
  23118. }
  23119. return false;
  23120. });
  23121. });
  23122. Client client("localhost", get_port());
  23123. client.set_payload_max_length(1024);
  23124. sse::SSEClient sse(client, "/many-events");
  23125. std::atomic<int> messages{0};
  23126. std::atomic<bool> too_large{false};
  23127. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23128. sse.on_error([&](Error err) {
  23129. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23130. });
  23131. sse.set_max_reconnect_attempts(1);
  23132. sse.start_async();
  23133. for (int i = 0; i < 500 && messages < 1000; i++) {
  23134. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23135. }
  23136. sse.stop();
  23137. EXPECT_GE(messages.load(), 1000);
  23138. EXPECT_FALSE(too_large);
  23139. }
  23140. // Test: on_message callback
  23141. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23142. // Endpoint that sends multiple events then closes
  23143. server_->Get("/multi-event", [](const Request &, Response &res) {
  23144. res.set_chunked_content_provider(
  23145. "text/event-stream", [](size_t offset, DataSink &sink) {
  23146. if (offset == 0) {
  23147. std::string events = "data: message1\n\ndata: message2\n\n";
  23148. sink.write(events.data(), events.size());
  23149. }
  23150. return false;
  23151. });
  23152. });
  23153. Client client("localhost", get_port());
  23154. sse::SSEClient sse(client, "/multi-event");
  23155. std::vector<std::string> received_messages;
  23156. std::mutex messages_mutex;
  23157. sse.on_message([&](const sse::SSEMessage &msg) {
  23158. std::lock_guard<std::mutex> lock(messages_mutex);
  23159. received_messages.push_back(msg.data);
  23160. });
  23161. sse.set_reconnect_interval(100);
  23162. sse.set_max_reconnect_attempts(1);
  23163. sse.start_async();
  23164. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23165. sse.stop();
  23166. std::lock_guard<std::mutex> lock(messages_mutex);
  23167. EXPECT_GE(received_messages.size(), 2u);
  23168. if (received_messages.size() >= 2) {
  23169. EXPECT_EQ(received_messages[0], "message1");
  23170. EXPECT_EQ(received_messages[1], "message2");
  23171. }
  23172. }
  23173. // Test: on_event for specific types
  23174. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23175. Client client("localhost", get_port());
  23176. sse::SSEClient sse(client, "/custom-events");
  23177. std::atomic<bool> update_received{false};
  23178. std::atomic<bool> delete_received{false};
  23179. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23180. if (msg.data == "updated") { update_received.store(true); }
  23181. });
  23182. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23183. if (msg.data == "deleted") { delete_received.store(true); }
  23184. });
  23185. sse.set_max_reconnect_attempts(1);
  23186. sse.start_async();
  23187. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23188. sse.stop();
  23189. EXPECT_TRUE(update_received.load());
  23190. EXPECT_TRUE(delete_received.load());
  23191. }
  23192. // Test: on_error callback on connection failure
  23193. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23194. // Connect to a non-existent port
  23195. Client client("localhost", 59999);
  23196. sse::SSEClient sse(client, "/events");
  23197. std::atomic<bool> error_called{false};
  23198. Error received_error = Error::Success;
  23199. sse.on_error([&](Error err) {
  23200. error_called.store(true);
  23201. received_error = err;
  23202. });
  23203. sse.set_reconnect_interval(50);
  23204. sse.set_max_reconnect_attempts(1);
  23205. sse.start_async();
  23206. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23207. sse.stop();
  23208. EXPECT_TRUE(error_called.load());
  23209. EXPECT_NE(received_error, Error::Success);
  23210. }
  23211. // Test: Last-Event-ID header sent on reconnect
  23212. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23213. // Endpoint that sends event with ID
  23214. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23215. res.set_chunked_content_provider(
  23216. "text/event-stream", [](size_t offset, DataSink &sink) {
  23217. if (offset == 0) {
  23218. std::string event = "id: evt-123\ndata: test\n\n";
  23219. sink.write(event.data(), event.size());
  23220. }
  23221. return false;
  23222. });
  23223. });
  23224. Client client("localhost", get_port());
  23225. sse::SSEClient sse(client, "/event-with-id");
  23226. std::atomic<bool> id_received{false};
  23227. sse.on_message([&](const sse::SSEMessage &msg) {
  23228. if (!msg.id.empty()) { id_received.store(true); }
  23229. });
  23230. sse.set_reconnect_interval(100);
  23231. sse.set_max_reconnect_attempts(1);
  23232. sse.start_async();
  23233. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23234. sse.stop();
  23235. EXPECT_TRUE(id_received.load());
  23236. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23237. }
  23238. // Test: last_event_id() read from another thread while start_async() runs
  23239. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23240. // Ids of every length up to 200, so the stored id keeps changing size
  23241. server_->Get("/many-ids", [](const Request &, Response &res) {
  23242. res.set_chunked_content_provider(
  23243. "text/event-stream", [](size_t offset, DataSink &sink) {
  23244. if (offset == 0) {
  23245. std::string events;
  23246. for (size_t i = 0; i < 2000; i++) {
  23247. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23248. events += "data: x\n\n";
  23249. }
  23250. events += "id: end\ndata: x\n\n";
  23251. sink.write(events.data(), events.size());
  23252. }
  23253. return false;
  23254. });
  23255. });
  23256. Client client("localhost", get_port());
  23257. sse::SSEClient sse(client, "/many-ids");
  23258. // Wait out the rest of the test rather than replay the stream
  23259. sse.set_reconnect_interval(10000);
  23260. sse.set_max_reconnect_attempts(1);
  23261. sse.start_async();
  23262. auto well_formed = true;
  23263. std::string id;
  23264. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23265. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23266. id = sse.last_event_id();
  23267. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23268. well_formed = false;
  23269. }
  23270. }
  23271. sse.stop();
  23272. EXPECT_TRUE(well_formed);
  23273. EXPECT_EQ(sse.last_event_id(), "end");
  23274. }
  23275. // Test: Manual stop
  23276. TEST_F(SSEIntegrationTest, ManualStop) {
  23277. // Endpoint that sends one event and stays open briefly. The server outlives
  23278. // this test body, so the provider uses the fixture's flag, not a local.
  23279. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23280. res.set_chunked_content_provider(
  23281. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23282. if (offset == 0) {
  23283. std::string event = "data: connected\n\n";
  23284. sink.write(event.data(), event.size());
  23285. }
  23286. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23287. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23288. }
  23289. return false;
  23290. });
  23291. });
  23292. Client client("localhost", get_port());
  23293. sse::SSEClient sse(client, "/stay-open");
  23294. std::atomic<bool> connected{false};
  23295. sse.on_open([&connected]() { connected.store(true); });
  23296. sse.set_reconnect_interval(100);
  23297. sse.set_max_reconnect_attempts(1);
  23298. sse.start_async();
  23299. // Wait for connection to establish
  23300. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23301. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23302. }
  23303. EXPECT_TRUE(connected.load());
  23304. EXPECT_TRUE(sse.is_connected());
  23305. // Signal handler to stop
  23306. stop_server_.store(true);
  23307. // Stop SSE client
  23308. sse.stop();
  23309. EXPECT_FALSE(sse.is_connected());
  23310. }
  23311. // Sends one event, then nothing until stop is set
  23312. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23313. return [&stop](const Request &, Response &res) {
  23314. res.set_chunked_content_provider(
  23315. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23316. if (offset == 0) {
  23317. std::string event = "data: hello\n\n";
  23318. sink.write(event.data(), event.size());
  23319. }
  23320. while (!stop.load()) {
  23321. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23322. }
  23323. return false;
  23324. });
  23325. };
  23326. }
  23327. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23328. static void check_stop_interrupts_blocked_read(Client &client) {
  23329. client.set_read_timeout(30, 0);
  23330. for (auto by_destructor : {false, true}) {
  23331. std::atomic<bool> received{false};
  23332. std::chrono::steady_clock::time_point start;
  23333. {
  23334. sse::SSEClient sse(client, "/idle-stream");
  23335. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23336. sse.start_async();
  23337. for (int i = 0; i < 500 && !received.load(); ++i) {
  23338. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23339. }
  23340. ASSERT_TRUE(received.load());
  23341. // Let the client block in the next read
  23342. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23343. start = std::chrono::steady_clock::now();
  23344. if (!by_destructor) { sse.stop(); }
  23345. }
  23346. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23347. std::chrono::seconds(2));
  23348. }
  23349. }
  23350. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23351. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23352. Client client("localhost", get_port());
  23353. check_stop_interrupts_blocked_read(client);
  23354. }
  23355. #ifdef CPPHTTPLIB_SSL_ENABLED
  23356. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23357. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23358. std::atomic<bool> done{false};
  23359. svr.Get("/idle-stream", idle_event_stream(done));
  23360. auto port = svr.bind_to_any_port(HOST);
  23361. std::thread t([&] { svr.listen_after_bind(); });
  23362. auto se = detail::scope_exit([&] {
  23363. done.store(true);
  23364. svr.stop();
  23365. t.join();
  23366. });
  23367. svr.wait_until_ready();
  23368. Client client("https://localhost:" + std::to_string(port));
  23369. client.enable_server_certificate_verification(false);
  23370. check_stop_interrupts_blocked_read(client);
  23371. }
  23372. #endif
  23373. // Test: SSEClient with custom headers
  23374. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23375. // Setup a server endpoint that checks for custom header
  23376. std::atomic<bool> header_received{false};
  23377. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23378. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23379. header_received.store(true);
  23380. }
  23381. res.set_chunked_content_provider("text/event-stream",
  23382. [](size_t, DataSink &) { return false; });
  23383. });
  23384. Client client("localhost", get_port());
  23385. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23386. sse::SSEClient sse(client, "/header-check", headers);
  23387. sse.set_max_reconnect_attempts(1);
  23388. sse.start_async();
  23389. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23390. sse.stop();
  23391. EXPECT_TRUE(header_received.load());
  23392. }
  23393. // Test: Reconnect interval configuration
  23394. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23395. Client client("localhost", get_port());
  23396. sse::SSEClient sse(client, "/events");
  23397. auto &result = sse.set_reconnect_interval(500);
  23398. // Builder pattern should return reference to self
  23399. EXPECT_EQ(&result, &sse);
  23400. }
  23401. // Test: Max reconnect attempts
  23402. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23403. // Connect to non-existent port to force reconnects
  23404. Client client("localhost", 59998);
  23405. sse::SSEClient sse(client, "/events");
  23406. std::atomic<int> error_count{0};
  23407. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23408. sse.set_reconnect_interval(50);
  23409. sse.set_max_reconnect_attempts(2);
  23410. auto start = std::chrono::steady_clock::now();
  23411. sse.start(); // Blocking call
  23412. auto end = std::chrono::steady_clock::now();
  23413. // Should have stopped after 2 failed attempts
  23414. EXPECT_GE(error_count.load(), 2);
  23415. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23416. auto duration =
  23417. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23418. #ifdef _WIN32
  23419. // Windows is much slower for socket connection failures
  23420. EXPECT_LT(duration.count(), 7000);
  23421. #else
  23422. EXPECT_LT(duration.count(), 1000);
  23423. #endif
  23424. }
  23425. // Test: Multi-line data in integration
  23426. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23427. // Endpoint with multi-line data
  23428. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23429. res.set_chunked_content_provider(
  23430. "text/event-stream", [](size_t offset, DataSink &sink) {
  23431. if (offset == 0) {
  23432. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23433. sink.write(event.data(), event.size());
  23434. }
  23435. return false;
  23436. });
  23437. });
  23438. Client client("localhost", get_port());
  23439. sse::SSEClient sse(client, "/multiline-data");
  23440. std::string received_data;
  23441. std::mutex data_mutex;
  23442. sse.on_message([&](const sse::SSEMessage &msg) {
  23443. std::lock_guard<std::mutex> lock(data_mutex);
  23444. received_data = msg.data;
  23445. });
  23446. sse.set_reconnect_interval(100);
  23447. sse.set_max_reconnect_attempts(1);
  23448. sse.start_async();
  23449. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23450. sse.stop();
  23451. std::lock_guard<std::mutex> lock(data_mutex);
  23452. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23453. }
  23454. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23455. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23456. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23457. DataSink &sink) {
  23458. if (offset == 0) {
  23459. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23460. sink.write(events.data(), events.size());
  23461. }
  23462. return false;
  23463. });
  23464. });
  23465. Client client("localhost", get_port());
  23466. sse::SSEClient sse(client, "/empty-data-lines");
  23467. std::mutex mutex;
  23468. std::condition_variable cv;
  23469. std::vector<std::string> received;
  23470. sse.on_message([&](const sse::SSEMessage &msg) {
  23471. std::lock_guard<std::mutex> lock(mutex);
  23472. received.push_back(msg.data);
  23473. cv.notify_all();
  23474. });
  23475. sse.set_max_reconnect_attempts(1);
  23476. sse.start_async();
  23477. {
  23478. std::unique_lock<std::mutex> lock(mutex);
  23479. cv.wait_for(lock, std::chrono::seconds(2),
  23480. [&] { return received.size() >= 3; });
  23481. }
  23482. sse.stop();
  23483. ASSERT_GE(received.size(), 3u);
  23484. EXPECT_EQ(received[0], "");
  23485. EXPECT_EQ(received[1], "\nhello");
  23486. EXPECT_EQ(received[2], "");
  23487. }
  23488. // Test: Auto-reconnect after server disconnection
  23489. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23490. std::atomic<int> connection_count{0};
  23491. std::atomic<int> message_count{0};
  23492. // Endpoint that sends one event and closes, forcing reconnect
  23493. server_->Get("/reconnect-test",
  23494. [&connection_count](const Request &, Response &res) {
  23495. connection_count.fetch_add(1);
  23496. res.set_chunked_content_provider(
  23497. "text/event-stream", [](size_t offset, DataSink &sink) {
  23498. if (offset == 0) {
  23499. std::string event = "data: hello\n\n";
  23500. sink.write(event.data(), event.size());
  23501. }
  23502. return false; // Close connection after sending
  23503. });
  23504. });
  23505. Client client("localhost", get_port());
  23506. sse::SSEClient sse(client, "/reconnect-test");
  23507. sse.on_message([&message_count](const sse::SSEMessage &) {
  23508. message_count.fetch_add(1);
  23509. });
  23510. sse.set_reconnect_interval(100);
  23511. sse.set_max_reconnect_attempts(3);
  23512. sse.start_async();
  23513. // Wait long enough for multiple reconnects
  23514. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23515. sse.stop();
  23516. // Should have connected multiple times (initial + reconnects)
  23517. EXPECT_GE(connection_count.load(), 2);
  23518. // Should have received messages from multiple connections
  23519. EXPECT_GE(message_count.load(), 2);
  23520. }
  23521. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23522. std::atomic<int> connection_count{0};
  23523. // Neither Content-Length nor chunked: the close ends the stream
  23524. server_->Get("/close-delimited",
  23525. [&connection_count](const Request &, Response &res) {
  23526. connection_count.fetch_add(1);
  23527. res.set_content_provider(
  23528. "text/event-stream", [](size_t offset, DataSink &sink) {
  23529. if (offset == 0) {
  23530. std::string event = "data: hello\n\n";
  23531. sink.write(event.data(), event.size());
  23532. } else {
  23533. sink.done();
  23534. }
  23535. return true;
  23536. });
  23537. });
  23538. Client client("localhost", get_port());
  23539. sse::SSEClient sse(client, "/close-delimited");
  23540. std::atomic<int> error_count{0};
  23541. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23542. sse.set_reconnect_interval(100);
  23543. sse.start_async();
  23544. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23545. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23546. }
  23547. sse.stop();
  23548. // Reconnects as after any end of the stream, but reports no error
  23549. EXPECT_GE(connection_count.load(), 2);
  23550. EXPECT_EQ(0, error_count.load());
  23551. }
  23552. // Test: A retry field of all ASCII digits sets the reconnection time
  23553. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23554. std::mutex mutex;
  23555. std::condition_variable cv;
  23556. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23557. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23558. {
  23559. std::lock_guard<std::mutex> lock(mutex);
  23560. connected_at.push_back(std::chrono::steady_clock::now());
  23561. cv.notify_all();
  23562. }
  23563. res.set_chunked_content_provider(
  23564. "text/event-stream", [](size_t offset, DataSink &sink) {
  23565. if (offset == 0) {
  23566. std::string event = "retry: 0\ndata: hello\n\n";
  23567. sink.write(event.data(), event.size());
  23568. }
  23569. return false;
  23570. });
  23571. });
  23572. Client client("localhost", get_port());
  23573. sse::SSEClient sse(client, "/zero-retry");
  23574. sse.set_reconnect_interval(10000);
  23575. sse.start_async();
  23576. {
  23577. std::unique_lock<std::mutex> lock(mutex);
  23578. cv.wait_for(lock, std::chrono::seconds(5),
  23579. [&] { return connected_at.size() >= 2; });
  23580. }
  23581. sse.stop();
  23582. // The server-supplied interval is applied, but never below 100ms, so
  23583. // "retry: 0" does not cause a busy reconnect loop
  23584. std::lock_guard<std::mutex> lock(mutex);
  23585. ASSERT_GE(connected_at.size(), 2u);
  23586. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23587. connected_at[1] - connected_at[0])
  23588. .count();
  23589. EXPECT_GE(interval_ms, 100);
  23590. }
  23591. // Test: Last-Event-ID sent on reconnect
  23592. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23593. std::atomic<int> connection_count{0};
  23594. std::vector<std::string> received_last_event_ids;
  23595. std::mutex id_mutex;
  23596. // Endpoint that checks Last-Event-ID header and sends event with ID
  23597. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23598. int conn = connection_count.fetch_add(1);
  23599. // Capture the Last-Event-ID header from each connection
  23600. {
  23601. std::lock_guard<std::mutex> lock(id_mutex);
  23602. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23603. }
  23604. res.set_chunked_content_provider(
  23605. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23606. if (offset == 0) {
  23607. std::string event =
  23608. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23609. sink.write(event.data(), event.size());
  23610. }
  23611. return false;
  23612. });
  23613. });
  23614. Client client("localhost", get_port());
  23615. sse::SSEClient sse(client, "/reconnect-with-id");
  23616. sse.set_reconnect_interval(100);
  23617. sse.set_max_reconnect_attempts(3);
  23618. sse.start_async();
  23619. // Wait for at least 2 connections
  23620. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23621. sse.stop();
  23622. // Verify behavior
  23623. std::lock_guard<std::mutex> lock(id_mutex);
  23624. EXPECT_GE(received_last_event_ids.size(), 2u);
  23625. // First connection should have no Last-Event-ID
  23626. if (!received_last_event_ids.empty()) {
  23627. EXPECT_EQ(received_last_event_ids[0], "");
  23628. }
  23629. // Second connection should have Last-Event-ID from first connection
  23630. if (received_last_event_ids.size() >= 2) {
  23631. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23632. }
  23633. }
  23634. // Test: set_headers updates headers used on reconnect
  23635. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23636. std::vector<std::string> received_tokens;
  23637. std::mutex token_mutex;
  23638. // Endpoint that captures Authorization header
  23639. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23640. {
  23641. std::lock_guard<std::mutex> lock(token_mutex);
  23642. received_tokens.push_back(req.get_header_value("Authorization"));
  23643. }
  23644. res.set_chunked_content_provider(
  23645. "text/event-stream", [](size_t offset, DataSink &sink) {
  23646. if (offset == 0) {
  23647. std::string event = "data: hello\n\n";
  23648. sink.write(event.data(), event.size());
  23649. }
  23650. return false; // Close connection to trigger reconnect
  23651. });
  23652. });
  23653. Client client("localhost", get_port());
  23654. Headers headers = {{"Authorization", "Bearer old-token"}};
  23655. sse::SSEClient sse(client, "/auth-check", headers);
  23656. // Update headers on each successful connection
  23657. sse.on_open(
  23658. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23659. sse.set_reconnect_interval(100);
  23660. sse.set_max_reconnect_attempts(3);
  23661. sse.start_async();
  23662. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23663. sse.stop();
  23664. std::lock_guard<std::mutex> lock(token_mutex);
  23665. ASSERT_GE(received_tokens.size(), 2u);
  23666. // First connection uses original header
  23667. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23668. // Second connection uses updated header from set_headers
  23669. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23670. }
  23671. // Test: 401 allows reconnection (so on_error can refresh headers)
  23672. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23673. std::atomic<int> connection_count{0};
  23674. // Endpoint: returns 401 on first attempt, 200 on second
  23675. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23676. int conn = connection_count.fetch_add(1);
  23677. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23678. res.status = StatusCode::Unauthorized_401;
  23679. res.set_content("Unauthorized", "text/plain");
  23680. return;
  23681. }
  23682. res.set_chunked_content_provider(
  23683. "text/event-stream", [](size_t offset, DataSink &sink) {
  23684. if (offset == 0) {
  23685. std::string event = "data: authenticated\n\n";
  23686. sink.write(event.data(), event.size());
  23687. }
  23688. return false;
  23689. });
  23690. });
  23691. Client client("localhost", get_port());
  23692. Headers headers = {{"Authorization", "Bearer expired"}};
  23693. sse::SSEClient sse(client, "/auth-retry", headers);
  23694. std::atomic<bool> message_received{false};
  23695. // Refresh token on error
  23696. sse.on_error(
  23697. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23698. sse.on_message([&](const sse::SSEMessage &msg) {
  23699. if (msg.data == "authenticated") { message_received.store(true); }
  23700. });
  23701. sse.set_reconnect_interval(100);
  23702. sse.set_max_reconnect_attempts(3);
  23703. sse.start_async();
  23704. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23705. sse.stop();
  23706. // Should have reconnected after 401 and succeeded with new token
  23707. EXPECT_GE(connection_count.load(), 2);
  23708. EXPECT_TRUE(message_received.load());
  23709. }
  23710. TEST(Issue2318Test, EmptyHostString) {
  23711. {
  23712. httplib::Client cli_empty("", PORT);
  23713. auto res = cli_empty.Get("/");
  23714. ASSERT_FALSE(res);
  23715. EXPECT_EQ(httplib::Error::Connection, res.error());
  23716. }
  23717. {
  23718. httplib::Client cli(" ", PORT);
  23719. auto res = cli.Get("/");
  23720. ASSERT_FALSE(res);
  23721. EXPECT_EQ(httplib::Error::Connection, res.error());
  23722. }
  23723. }
  23724. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23725. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23726. Server svr;
  23727. // Set a small payload limit (1KB)
  23728. svr.set_payload_max_length(1024);
  23729. svr.Post("/test", [&](const Request &req, Response &res) {
  23730. res.set_content("Body size: " + std::to_string(req.body.size()),
  23731. "text/plain");
  23732. });
  23733. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23734. auto se = detail::scope_exit([&] {
  23735. svr.stop();
  23736. listen_thread.join();
  23737. });
  23738. svr.wait_until_ready();
  23739. // Create data that compresses well but exceeds limit when decompressed
  23740. // 8KB of repeated null bytes compresses to a very small size
  23741. std::string original_data(8 * 1024, '\0');
  23742. // Compress the data using gzip
  23743. std::string compressed_data;
  23744. detail::gzip_compressor compressor;
  23745. compressor.compress(original_data.data(), original_data.size(), true,
  23746. [&](const char *data, size_t size) {
  23747. compressed_data.append(data, size);
  23748. return true;
  23749. });
  23750. // Verify compression worked (compressed should be much smaller)
  23751. ASSERT_LT(compressed_data.size(), original_data.size());
  23752. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23753. // Send compressed data with Content-Encoding: gzip
  23754. Client cli(HOST, PORT);
  23755. Headers headers = {{"Content-Encoding", "gzip"}};
  23756. auto res =
  23757. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23758. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23760. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23761. }
  23762. #endif
  23763. // ============================================================================
  23764. // OpenSSL-Specific Tests
  23765. // ============================================================================
  23766. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23767. X509 *readCertificate(const std::string &strFileName) {
  23768. std::ifstream inStream(strFileName);
  23769. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23770. std::istreambuf_iterator<char>());
  23771. if (strCertPEM.empty()) return (nullptr);
  23772. BIO *pbCert = BIO_new(BIO_s_mem());
  23773. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23774. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23775. BIO_free(pbCert);
  23776. return (pCert);
  23777. }
  23778. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23779. std::ifstream inStream(strFileName);
  23780. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23781. std::istreambuf_iterator<char>());
  23782. if (strPrivateKeyPEM.empty()) return (nullptr);
  23783. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23784. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23785. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23786. BIO_free(pbPrivKey);
  23787. return (pPrivateKey);
  23788. }
  23789. TEST(BindServerTest, UpdateCerts) {
  23790. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23791. int port = svr.bind_to_any_port("0.0.0.0");
  23792. ASSERT_TRUE(svr.is_valid());
  23793. ASSERT_TRUE(port > 0);
  23794. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23795. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23796. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23797. ASSERT_TRUE(cert != nullptr);
  23798. ASSERT_TRUE(ca_cert != nullptr);
  23799. ASSERT_TRUE(key != nullptr);
  23800. X509_STORE *cert_store = X509_STORE_new();
  23801. X509_STORE_add_cert(cert_store, ca_cert);
  23802. // svr.update_certs(cert, key, cert_store); // deprecated
  23803. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23804. CLIENT_CA_CERT_FILE);
  23805. ASSERT_TRUE(svr.is_valid());
  23806. svr.stop();
  23807. X509_STORE_free(cert_store);
  23808. X509_free(cert);
  23809. X509_free(ca_cert);
  23810. EVP_PKEY_free(key);
  23811. }
  23812. // Test that update_certs() updates client CA list correctly
  23813. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23814. // Start with file-based constructor
  23815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23816. ASSERT_TRUE(svr.is_valid());
  23817. // Initially no client CA list should be set
  23818. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23819. ASSERT_TRUE(ssl_ctx != nullptr);
  23820. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23821. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23822. // Now update with client CA (PEM string)
  23823. std::string cert_pem, key_pem, ca_pem;
  23824. read_file(SERVER_CERT_FILE, cert_pem);
  23825. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23826. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23827. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23828. ASSERT_TRUE(svr.is_valid());
  23829. // Now client CA list should be set
  23830. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23831. ASSERT_TRUE(ca_list_after != nullptr);
  23832. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23833. }
  23834. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23835. // Test that the file-path SSLServer constructor properly sets the client CA
  23836. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23837. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23838. ASSERT_TRUE(svr.is_valid());
  23839. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23840. ASSERT_TRUE(ssl_ctx != nullptr);
  23841. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23842. ASSERT_TRUE(ca_list != nullptr);
  23843. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23844. }
  23845. #endif
  23846. // ============================================================================
  23847. // MbedTLS-Specific Tests
  23848. // ============================================================================
  23849. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23850. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23851. using namespace httplib::tls;
  23852. // Track if callback was invoked
  23853. bool callback_invoked = false;
  23854. // The callback receives void* ctx which is actually MbedTlsContext*
  23855. // We can access the mbedtls_ssl_config via the context
  23856. auto setup_callback = [&callback_invoked](void *ctx) {
  23857. callback_invoked = true;
  23858. // Cast to MbedTlsContext* to access the ssl config
  23859. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23860. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23861. // Use static variables to hold certificate data (simplified for test)
  23862. static mbedtls_x509_crt own_cert;
  23863. static mbedtls_pk_context own_key;
  23864. static mbedtls_x509_crt ca_chain;
  23865. static bool initialized = false;
  23866. if (!initialized) {
  23867. mbedtls_x509_crt_init(&own_cert);
  23868. mbedtls_pk_init(&own_key);
  23869. mbedtls_x509_crt_init(&ca_chain);
  23870. // Load server certificate
  23871. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23872. return false;
  23873. }
  23874. // Load server private key.
  23875. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23876. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23877. #if MBEDTLS_VERSION_MAJOR == 3
  23878. ,
  23879. mbedtls_ctr_drbg_random, nullptr
  23880. #endif
  23881. ) != 0) {
  23882. return false;
  23883. }
  23884. // Load CA chain for client verification
  23885. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23886. return false;
  23887. }
  23888. initialized = true;
  23889. }
  23890. // Configure the SSL config
  23891. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23892. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23893. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23894. // Set minimum TLS version using mbedTLS native API
  23895. #if MBEDTLS_VERSION_MAJOR >= 3
  23896. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23897. #else
  23898. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23899. MBEDTLS_SSL_MINOR_VERSION_3);
  23900. #endif
  23901. return true;
  23902. };
  23903. SSLServer svr(setup_callback);
  23904. ASSERT_TRUE(svr.is_valid());
  23905. ASSERT_TRUE(callback_invoked);
  23906. svr.Get("/test", [&](const Request &req, Response &res) {
  23907. res.set_content("test", "text/plain");
  23908. auto cert = req.peer_cert();
  23909. ASSERT_TRUE(static_cast<bool>(cert));
  23910. auto common_name = cert.subject_cn();
  23911. EXPECT_EQ("Common Name", common_name);
  23912. });
  23913. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23914. auto se = detail::scope_exit([&] {
  23915. svr.stop();
  23916. t.join();
  23917. ASSERT_FALSE(svr.is_running());
  23918. });
  23919. svr.wait_until_ready();
  23920. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23921. cli.enable_server_certificate_verification(false);
  23922. cli.set_connection_timeout(30);
  23923. auto res = cli.Get("/test");
  23924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23925. ASSERT_EQ(StatusCode::OK_200, res->status);
  23926. }
  23927. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23928. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23929. // keep-alive SSL session, which reads through that config in
  23930. // mbedtls_ssl_close_notify.
  23931. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23932. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23933. ASSERT_TRUE(svr.is_valid());
  23934. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23935. res.set_content("test", "text/plain");
  23936. });
  23937. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23938. auto se = detail::scope_exit([&] {
  23939. svr.stop();
  23940. t.join();
  23941. ASSERT_FALSE(svr.is_running());
  23942. });
  23943. svr.wait_until_ready();
  23944. {
  23945. SSLClient cli(HOST, PORT);
  23946. cli.enable_server_certificate_verification(false);
  23947. cli.set_keep_alive(true);
  23948. auto res = cli.Get("/test");
  23949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23950. ASSERT_EQ(StatusCode::OK_200, res->status);
  23951. // cli is destructed here with the keep-alive SSL session still open.
  23952. }
  23953. }
  23954. #endif
  23955. // WebSocket Tests
  23956. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23957. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23958. // defining the meaning of these bits has been negotiated.
  23959. auto make_frame = [](uint8_t first_byte) {
  23960. std::string frame;
  23961. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23962. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23963. frame += "Hello";
  23964. return frame;
  23965. };
  23966. // RSV1 set (0x40)
  23967. {
  23968. detail::BufferStream strm;
  23969. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23970. ws::Opcode opcode;
  23971. std::string payload;
  23972. bool fin;
  23973. EXPECT_EQ(
  23974. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23975. ws::impl::FrameRead::Fail);
  23976. }
  23977. // RSV2 set (0x20)
  23978. {
  23979. detail::BufferStream strm;
  23980. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23981. ws::Opcode opcode;
  23982. std::string payload;
  23983. bool fin;
  23984. EXPECT_EQ(
  23985. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23986. ws::impl::FrameRead::Fail);
  23987. }
  23988. // RSV3 set (0x10)
  23989. {
  23990. detail::BufferStream strm;
  23991. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23992. ws::Opcode opcode;
  23993. std::string payload;
  23994. bool fin;
  23995. EXPECT_EQ(
  23996. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23997. ws::impl::FrameRead::Fail);
  23998. }
  23999. // No RSV bits set - should succeed
  24000. {
  24001. detail::BufferStream strm;
  24002. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24003. ws::Opcode opcode;
  24004. std::string payload;
  24005. bool fin;
  24006. EXPECT_EQ(
  24007. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24008. ws::impl::FrameRead::Ok);
  24009. EXPECT_EQ(ws::Opcode::Text, opcode);
  24010. EXPECT_EQ("Hello", payload);
  24011. EXPECT_TRUE(fin);
  24012. }
  24013. }
  24014. TEST(WebSocketTest, ControlFrameValidation) {
  24015. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24016. // payload length <= 125.
  24017. // Ping with FIN=0 - must be rejected
  24018. {
  24019. detail::BufferStream strm;
  24020. std::string frame;
  24021. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24022. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24023. strm.write(frame.data(), frame.size());
  24024. ws::Opcode opcode;
  24025. std::string payload;
  24026. bool fin;
  24027. EXPECT_EQ(
  24028. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24029. ws::impl::FrameRead::Fail);
  24030. }
  24031. // Close with FIN=0 - must be rejected
  24032. {
  24033. detail::BufferStream strm;
  24034. std::string frame;
  24035. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24036. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24037. strm.write(frame.data(), frame.size());
  24038. ws::Opcode opcode;
  24039. std::string payload;
  24040. bool fin;
  24041. EXPECT_EQ(
  24042. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24043. ws::impl::FrameRead::Fail);
  24044. }
  24045. // Ping with payload_len=126 (extended length) - must be rejected
  24046. {
  24047. detail::BufferStream strm;
  24048. std::string frame;
  24049. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24050. frame += static_cast<char>(126); // payload_len=126 (>125)
  24051. frame += static_cast<char>(0x00); // extended length high byte
  24052. frame += static_cast<char>(126); // extended length low byte
  24053. frame += std::string(126, 'x');
  24054. strm.write(frame.data(), frame.size());
  24055. ws::Opcode opcode;
  24056. std::string payload;
  24057. bool fin;
  24058. EXPECT_EQ(
  24059. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24060. ws::impl::FrameRead::Fail);
  24061. }
  24062. // Ping with FIN=1 and payload_len=125 - should succeed
  24063. {
  24064. detail::BufferStream strm;
  24065. std::string frame;
  24066. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24067. frame += static_cast<char>(125); // payload_len=125
  24068. frame += std::string(125, 'x');
  24069. strm.write(frame.data(), frame.size());
  24070. ws::Opcode opcode;
  24071. std::string payload;
  24072. bool fin;
  24073. EXPECT_EQ(
  24074. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24075. ws::impl::FrameRead::Ok);
  24076. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24077. EXPECT_EQ(125u, payload.size());
  24078. EXPECT_TRUE(fin);
  24079. }
  24080. }
  24081. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24082. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24083. // length MUST be 0.
  24084. // MSB set - must be rejected
  24085. {
  24086. detail::BufferStream strm;
  24087. std::string frame;
  24088. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24089. frame += static_cast<char>(127); // 64-bit extended length
  24090. frame += static_cast<char>(0x80); // MSB set (invalid)
  24091. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24092. strm.write(frame.data(), frame.size());
  24093. ws::Opcode opcode;
  24094. std::string payload;
  24095. bool fin;
  24096. EXPECT_EQ(
  24097. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24098. ws::impl::FrameRead::Fail);
  24099. }
  24100. // MSB clear - should pass length parsing (will be rejected by max_len,
  24101. // but that's a different check; use a small length to verify)
  24102. {
  24103. detail::BufferStream strm;
  24104. std::string frame;
  24105. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24106. frame += static_cast<char>(127); // 64-bit extended length
  24107. frame += std::string(7, '\0'); // high bytes = 0
  24108. frame += static_cast<char>(0x03); // length = 3
  24109. frame += "abc";
  24110. strm.write(frame.data(), frame.size());
  24111. ws::Opcode opcode;
  24112. std::string payload;
  24113. bool fin;
  24114. EXPECT_EQ(
  24115. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24116. ws::impl::FrameRead::Ok);
  24117. EXPECT_EQ(ws::Opcode::Text, opcode);
  24118. EXPECT_EQ("abc", payload);
  24119. }
  24120. }
  24121. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24122. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24123. // Valid UTF-8
  24124. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24125. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24126. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24127. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24128. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24129. // Invalid UTF-8
  24130. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24131. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24132. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24133. EXPECT_FALSE(
  24134. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24135. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24136. }
  24137. TEST(WebSocketTest, ConnectAndDisconnect) {
  24138. Server svr;
  24139. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24140. std::string msg;
  24141. while (ws.read(msg)) {}
  24142. });
  24143. auto port = svr.bind_to_any_port(HOST);
  24144. std::thread t([&]() { svr.listen_after_bind(); });
  24145. svr.wait_until_ready();
  24146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24147. auto res = client.connect();
  24148. ASSERT_TRUE(res);
  24149. EXPECT_EQ(Error::Success, res.error());
  24150. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24151. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24152. EXPECT_TRUE(client.is_open());
  24153. client.close();
  24154. EXPECT_FALSE(client.is_open());
  24155. svr.stop();
  24156. t.join();
  24157. }
  24158. TEST(WebSocketTest, ValidURL) {
  24159. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24160. EXPECT_TRUE(ws1.is_valid());
  24161. ws::WebSocketClient ws2("ws://example.com/path");
  24162. EXPECT_TRUE(ws2.is_valid());
  24163. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24164. EXPECT_TRUE(ws3.is_valid());
  24165. #ifdef CPPHTTPLIB_SSL_ENABLED
  24166. ws::WebSocketClient wss1("wss://example.com/path");
  24167. EXPECT_TRUE(wss1.is_valid());
  24168. ws::WebSocketClient wss2("wss://example.com:443/path");
  24169. EXPECT_TRUE(wss2.is_valid());
  24170. #endif
  24171. }
  24172. TEST(WebSocketTest, InvalidURL) {
  24173. // No scheme
  24174. ws::WebSocketClient ws1("localhost:8080/path");
  24175. EXPECT_FALSE(ws1.is_valid());
  24176. // No path
  24177. ws::WebSocketClient ws2("ws://localhost:8080");
  24178. EXPECT_FALSE(ws2.is_valid());
  24179. // Empty string
  24180. ws::WebSocketClient ws3("");
  24181. EXPECT_FALSE(ws3.is_valid());
  24182. // Missing host
  24183. ws::WebSocketClient ws4("ws://:8080/path");
  24184. EXPECT_FALSE(ws4.is_valid());
  24185. // Port number overflow — should not crash
  24186. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24187. EXPECT_FALSE(ws5.is_valid());
  24188. // Port out of range
  24189. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24190. EXPECT_FALSE(ws6.is_valid());
  24191. }
  24192. TEST(WebSocketTest, UnsupportedScheme) {
  24193. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24194. ws::WebSocketClient ws1("http://localhost:8080/path");
  24195. EXPECT_FALSE(ws1.is_valid());
  24196. ws::WebSocketClient ws2("https://localhost:8080/path");
  24197. EXPECT_FALSE(ws2.is_valid());
  24198. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24199. EXPECT_FALSE(ws3.is_valid());
  24200. #else
  24201. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24202. std::invalid_argument);
  24203. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24204. std::invalid_argument);
  24205. #endif
  24206. }
  24207. TEST(WebSocketTest, ConnectWhenInvalid) {
  24208. ws::WebSocketClient ws("not a valid url");
  24209. EXPECT_FALSE(ws.is_valid());
  24210. auto res = ws.connect();
  24211. EXPECT_FALSE(res);
  24212. EXPECT_EQ(Error::Connection, res.error());
  24213. EXPECT_EQ(-1, res.status());
  24214. }
  24215. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24216. // Grab a port that is free, then close it again so nothing listens there
  24217. Server svr;
  24218. auto port = svr.bind_to_any_port(HOST);
  24219. svr.stop();
  24220. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24221. auto res = client.connect();
  24222. ASSERT_FALSE(res);
  24223. EXPECT_EQ(Error::Connection, res.error());
  24224. EXPECT_EQ(-1, res.status());
  24225. }
  24226. TEST(WebSocketTest, DefaultPort) {
  24227. ws::WebSocketClient ws1("ws://example.com/path");
  24228. EXPECT_TRUE(ws1.is_valid());
  24229. // ws:// defaults to port 80 (verified by successful parse)
  24230. #ifdef CPPHTTPLIB_SSL_ENABLED
  24231. ws::WebSocketClient ws2("wss://example.com/path");
  24232. EXPECT_TRUE(ws2.is_valid());
  24233. // wss:// defaults to port 443 (verified by successful parse)
  24234. #endif
  24235. }
  24236. TEST(WebSocketTest, IPv6LiteralAddress) {
  24237. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24238. EXPECT_TRUE(ws1.is_valid());
  24239. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24240. EXPECT_TRUE(ws2.is_valid());
  24241. }
  24242. TEST(WebSocketTest, ComplexPath) {
  24243. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24244. EXPECT_TRUE(ws1.is_valid());
  24245. ws::WebSocketClient ws2("ws://localhost:8080/");
  24246. EXPECT_TRUE(ws2.is_valid());
  24247. }
  24248. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24249. Server svr;
  24250. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24251. std::string msg;
  24252. while (ws.read(msg)) {}
  24253. });
  24254. auto port = svr.bind_to_any_port(HOST);
  24255. std::thread t([&]() { svr.listen_after_bind(); });
  24256. svr.wait_until_ready();
  24257. auto another_host = "example.com";
  24258. auto wrong_ip = "192.0.2.1";
  24259. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24260. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24261. ASSERT_TRUE(client.connect());
  24262. EXPECT_TRUE(client.is_open());
  24263. client.close();
  24264. svr.stop();
  24265. t.join();
  24266. }
  24267. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24268. Server svr;
  24269. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24270. std::string msg;
  24271. while (ws.read(msg)) {}
  24272. });
  24273. auto port = svr.bind_to_any_port(HOST);
  24274. std::thread t([&]() { svr.listen_after_bind(); });
  24275. svr.wait_until_ready();
  24276. auto wrong_ip = "192.0.2.1";
  24277. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24278. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24279. client.set_connection_timeout(1);
  24280. client.set_read_timeout(1);
  24281. client.set_write_timeout(1);
  24282. EXPECT_FALSE(client.connect());
  24283. EXPECT_FALSE(client.is_open());
  24284. svr.stop();
  24285. t.join();
  24286. }
  24287. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24288. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24289. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24290. // (RFC 6761) is only a map key and the Host header value.
  24291. auto host = "target.invalid";
  24292. Server svr;
  24293. std::string received_host;
  24294. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24295. received_host = req.get_header_value("Host");
  24296. std::string msg;
  24297. while (ws.read(msg)) {}
  24298. });
  24299. auto port = svr.bind_to_any_port(HOST);
  24300. std::thread t([&]() { svr.listen_after_bind(); });
  24301. // ASSERT_* below returns from the test body, which would leave t joinable
  24302. // and make ~thread call std::terminate.
  24303. auto se = detail::scope_exit([&] {
  24304. svr.stop();
  24305. if (t.joinable()) { t.join(); }
  24306. });
  24307. svr.wait_until_ready();
  24308. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24309. std::to_string(port) + "/ws");
  24310. client.set_direct_hostname_addr_map({{host, HOST}});
  24311. ASSERT_TRUE(client.connect());
  24312. EXPECT_TRUE(client.is_open());
  24313. client.close();
  24314. svr.stop();
  24315. t.join();
  24316. // The mapping only redirects the connection; the identity stays host_.
  24317. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24318. }
  24319. class WebSocketIntegrationTest : public ::testing::Test {
  24320. protected:
  24321. void SetUp() override {
  24322. server_ = httplib::detail::make_unique<Server>();
  24323. setup_server();
  24324. start_server();
  24325. }
  24326. void TearDown() override {
  24327. server_->stop();
  24328. if (server_thread_.joinable()) { server_thread_.join(); }
  24329. }
  24330. void setup_server() {
  24331. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24332. std::string msg;
  24333. ws::ReadResult ret;
  24334. while ((ret = ws.read(msg))) {
  24335. if (ret == ws::Binary) {
  24336. ws.send(msg.data(), msg.size());
  24337. } else {
  24338. ws.send(msg);
  24339. }
  24340. }
  24341. });
  24342. server_->WebSocket("/ws-echo-string",
  24343. [](const Request &, ws::WebSocket &ws) {
  24344. std::string msg;
  24345. while (ws.read(msg)) {
  24346. ws.send("echo: " + msg);
  24347. }
  24348. });
  24349. server_->WebSocket(
  24350. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24351. // Echo back request metadata
  24352. ws.send("path:" + req.path);
  24353. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24354. std::string msg;
  24355. while (ws.read(msg)) {}
  24356. });
  24357. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24358. std::string msg;
  24359. ws.read(msg); // wait for a message
  24360. ws.close();
  24361. });
  24362. server_->WebSocket("/ws-close-status",
  24363. [](const Request &, ws::WebSocket &ws) {
  24364. std::string msg;
  24365. ws.read(msg); // wait for a message
  24366. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24367. });
  24368. server_->WebSocket(
  24369. "/ws-subprotocol",
  24370. [](const Request &, ws::WebSocket &ws) {
  24371. std::string msg;
  24372. while (ws.read(msg)) {
  24373. ws.send(msg);
  24374. }
  24375. },
  24376. [](const std::vector<std::string> &protocols) -> std::string {
  24377. for (const auto &p : protocols) {
  24378. if (p == "graphql-ws") { return p; }
  24379. }
  24380. return "";
  24381. });
  24382. server_->WebSocket(
  24383. "/ws-subprotocol-unoffered",
  24384. [](const Request &, ws::WebSocket &ws) {
  24385. std::string msg;
  24386. while (ws.read(msg)) {
  24387. ws.send(msg);
  24388. }
  24389. },
  24390. [](const std::vector<std::string> &) -> std::string {
  24391. return "admin";
  24392. });
  24393. }
  24394. void start_server() {
  24395. port_ = server_->bind_to_any_port(HOST);
  24396. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24397. server_->wait_until_ready();
  24398. }
  24399. std::unique_ptr<Server> server_;
  24400. std::thread server_thread_;
  24401. int port_ = 0;
  24402. };
  24403. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24404. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24405. "/ws-echo");
  24406. ASSERT_TRUE(client.connect());
  24407. ASSERT_TRUE(client.is_open());
  24408. ASSERT_TRUE(client.send("Hello WebSocket"));
  24409. std::string msg;
  24410. EXPECT_EQ(ws::Text, client.read(msg));
  24411. EXPECT_EQ("Hello WebSocket", msg);
  24412. client.close();
  24413. }
  24414. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24415. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24416. "/ws-echo");
  24417. ASSERT_TRUE(client.connect());
  24418. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24419. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24420. std::string msg;
  24421. EXPECT_EQ(ws::Binary, client.read(msg));
  24422. EXPECT_EQ(binary_data, msg);
  24423. client.close();
  24424. }
  24425. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24426. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24427. "/ws-echo");
  24428. ASSERT_TRUE(client.connect());
  24429. for (int i = 0; i < 10; i++) {
  24430. auto text = "message " + std::to_string(i);
  24431. ASSERT_TRUE(client.send(text));
  24432. std::string msg;
  24433. ASSERT_TRUE(client.read(msg));
  24434. EXPECT_EQ(text, msg);
  24435. }
  24436. client.close();
  24437. }
  24438. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24439. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24440. "/ws-close");
  24441. ASSERT_TRUE(client.connect());
  24442. // Send a message to trigger the server to close
  24443. ASSERT_TRUE(client.send("trigger close"));
  24444. // The server will close, so read should return false
  24445. std::string msg;
  24446. EXPECT_FALSE(client.read(msg));
  24447. EXPECT_FALSE(client.is_open());
  24448. }
  24449. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24450. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24451. "/ws-echo");
  24452. ASSERT_TRUE(client.connect());
  24453. // 128KB message
  24454. std::string large_data(128 * 1024, 'X');
  24455. ASSERT_TRUE(client.send(large_data));
  24456. std::string msg;
  24457. ASSERT_TRUE(client.read(msg));
  24458. EXPECT_EQ(large_data, msg);
  24459. client.close();
  24460. }
  24461. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24462. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24463. "/ws-echo");
  24464. ASSERT_TRUE(client.connect());
  24465. const int num_threads = 4;
  24466. std::vector<std::thread> threads;
  24467. std::atomic<int> send_count{0};
  24468. for (int t = 0; t < num_threads; t++) {
  24469. threads.emplace_back([&client, &send_count, t]() {
  24470. for (int i = 0; i < 5; i++) {
  24471. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24472. if (client.send(text)) { send_count++; }
  24473. }
  24474. });
  24475. }
  24476. for (auto &th : threads) {
  24477. th.join();
  24478. }
  24479. int received = 0;
  24480. std::string msg;
  24481. while (received < send_count.load()) {
  24482. if (!client.read(msg)) { break; }
  24483. received++;
  24484. }
  24485. EXPECT_EQ(send_count.load(), received);
  24486. client.close();
  24487. }
  24488. TEST_F(WebSocketIntegrationTest, ReadString) {
  24489. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24490. "/ws-echo-string");
  24491. ASSERT_TRUE(client.connect());
  24492. ASSERT_TRUE(client.send("hello"));
  24493. std::string msg;
  24494. ASSERT_TRUE(client.read(msg));
  24495. EXPECT_EQ("echo: hello", msg);
  24496. ASSERT_TRUE(client.send("world"));
  24497. ASSERT_TRUE(client.read(msg));
  24498. EXPECT_EQ("echo: world", msg);
  24499. client.close();
  24500. }
  24501. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24502. Headers headers = {{"X-Test-Header", "test-value"}};
  24503. ws::WebSocketClient client(
  24504. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24505. ASSERT_TRUE(client.connect());
  24506. std::string msg;
  24507. ASSERT_TRUE(client.read(msg));
  24508. EXPECT_EQ("path:/ws-request-info", msg);
  24509. ASSERT_TRUE(client.read(msg));
  24510. EXPECT_EQ("header:test-value", msg);
  24511. client.close();
  24512. }
  24513. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24514. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24515. "/ws-echo");
  24516. client.set_read_timeout(1, 0); // 1 second
  24517. ASSERT_TRUE(client.connect());
  24518. // Don't send anything — server echo handler waits for a message, so read()
  24519. // should time out. The connection survives it: nothing was consumed.
  24520. std::string msg;
  24521. EXPECT_EQ(client.read(msg), ws::Timeout);
  24522. EXPECT_TRUE(client.is_open());
  24523. // And it is still usable afterwards.
  24524. EXPECT_TRUE(client.send("after timeout"));
  24525. EXPECT_EQ(client.read(msg), ws::Text);
  24526. EXPECT_EQ(msg, "after timeout");
  24527. }
  24528. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24529. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24530. "/ws-echo");
  24531. client.set_read_timeout(1, 0);
  24532. ASSERT_TRUE(client.connect());
  24533. ASSERT_TRUE(client.send("first"));
  24534. std::string msg;
  24535. ASSERT_EQ(client.read(msg), ws::Text);
  24536. ASSERT_EQ(msg, "first");
  24537. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24538. // not be used with a read timeout: it would reprocess the previous message.
  24539. EXPECT_EQ(client.read(msg), ws::Timeout);
  24540. EXPECT_EQ(msg, "first");
  24541. }
  24542. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24543. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24544. "/ws-echo");
  24545. ASSERT_TRUE(client.connect());
  24546. // Setting it once the connection is open reaches the live stream, not just
  24547. // the seed for the next connect().
  24548. client.set_read_timeout(1, 0);
  24549. std::string msg;
  24550. EXPECT_EQ(client.read(msg), ws::Timeout);
  24551. EXPECT_TRUE(client.is_open());
  24552. }
  24553. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24554. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24555. "/ws-echo");
  24556. client.set_read_timeout(5, 0);
  24557. ASSERT_TRUE(client.connect());
  24558. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24559. // The server should reject it and close the connection.
  24560. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24561. client.send(oversized);
  24562. // The server's read() should have failed due to payload limit,
  24563. // so our read() should return false (connection closed).
  24564. std::string msg;
  24565. EXPECT_FALSE(client.read(msg));
  24566. }
  24567. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24568. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24569. "/ws-echo");
  24570. client.set_read_timeout(10, 0);
  24571. ASSERT_TRUE(client.connect());
  24572. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24573. // This should succeed.
  24574. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24575. ASSERT_TRUE(client.send(at_limit));
  24576. std::string msg;
  24577. ASSERT_TRUE(client.read(msg));
  24578. EXPECT_EQ(at_limit.size(), msg.size());
  24579. client.close();
  24580. }
  24581. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24582. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24583. "/nonexistent");
  24584. auto res = client.connect();
  24585. EXPECT_FALSE(res);
  24586. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24587. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24588. EXPECT_FALSE(client.is_open());
  24589. }
  24590. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24591. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24592. "/ws-echo");
  24593. ASSERT_TRUE(client.connect());
  24594. ASSERT_TRUE(client.send(""));
  24595. std::string msg;
  24596. EXPECT_EQ(ws::Text, client.read(msg));
  24597. EXPECT_EQ("", msg);
  24598. client.close();
  24599. }
  24600. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24602. "/ws-echo");
  24603. // First connection
  24604. ASSERT_TRUE(client.connect());
  24605. ASSERT_TRUE(client.send("first"));
  24606. std::string msg;
  24607. ASSERT_TRUE(client.read(msg));
  24608. EXPECT_EQ("first", msg);
  24609. client.close();
  24610. EXPECT_FALSE(client.is_open());
  24611. // Reconnect using the same client object
  24612. ASSERT_TRUE(client.connect());
  24613. ASSERT_TRUE(client.is_open());
  24614. ASSERT_TRUE(client.send("second"));
  24615. ASSERT_TRUE(client.read(msg));
  24616. EXPECT_EQ("second", msg);
  24617. client.close();
  24618. }
  24619. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24620. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24621. "/ws-close-status");
  24622. ASSERT_TRUE(client.connect());
  24623. // Trigger the server to close with GoingAway status
  24624. ASSERT_TRUE(client.send("trigger"));
  24625. // read() should return false after receiving the close frame
  24626. std::string msg;
  24627. EXPECT_FALSE(client.read(msg));
  24628. EXPECT_FALSE(client.is_open());
  24629. }
  24630. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24631. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24632. "/ws-echo");
  24633. ASSERT_TRUE(client.connect());
  24634. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24635. EXPECT_FALSE(client.is_open());
  24636. }
  24637. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24638. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24639. ws::WebSocketClient client(
  24640. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24641. ASSERT_TRUE(client.connect());
  24642. // Server should have selected graphql-ws
  24643. EXPECT_EQ("graphql-ws", client.subprotocol());
  24644. client.close();
  24645. }
  24646. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24647. Headers headers;
  24648. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24649. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24650. ws::WebSocketClient client(
  24651. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24652. ASSERT_TRUE(client.connect());
  24653. // The offer on the second field line counts too, so graphql-ws is selected
  24654. EXPECT_EQ("graphql-ws", client.subprotocol());
  24655. client.close();
  24656. }
  24657. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24658. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24659. ws::WebSocketClient client(
  24660. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24661. ASSERT_TRUE(client.connect());
  24662. // Server should not have selected any subprotocol
  24663. EXPECT_TRUE(client.subprotocol().empty());
  24664. client.close();
  24665. }
  24666. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24667. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24668. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24669. "/ws-subprotocol-unoffered",
  24670. headers);
  24671. ASSERT_TRUE(client.connect());
  24672. EXPECT_TRUE(client.subprotocol().empty());
  24673. client.close();
  24674. }
  24675. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24676. // Connect without requesting any subprotocol
  24677. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24678. "/ws-subprotocol");
  24679. ASSERT_TRUE(client.connect());
  24680. EXPECT_TRUE(client.subprotocol().empty());
  24681. client.close();
  24682. }
  24683. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24684. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24685. "/ws-echo");
  24686. client.set_tcp_nodelay(true);
  24687. client.set_connection_timeout(3, 0);
  24688. bool socket_options_called = false;
  24689. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24690. ASSERT_TRUE(client.connect());
  24691. ASSERT_TRUE(client.is_open());
  24692. EXPECT_TRUE(socket_options_called);
  24693. ASSERT_TRUE(client.send("hello"));
  24694. std::string msg;
  24695. auto result = client.read(msg);
  24696. EXPECT_EQ(result, ws::ReadResult::Text);
  24697. EXPECT_EQ(msg, "hello");
  24698. client.close();
  24699. }
  24700. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24701. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24702. "/ws-echo");
  24703. client.set_connection_timeout(std::chrono::seconds(3));
  24704. client.set_write_timeout(std::chrono::seconds(3));
  24705. // A sub-second remainder exercises the seconds/microseconds split.
  24706. client.set_read_timeout(std::chrono::milliseconds(1500));
  24707. ASSERT_TRUE(client.connect());
  24708. auto start = std::chrono::steady_clock::now();
  24709. std::string msg;
  24710. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24711. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24712. std::chrono::steady_clock::now() - start)
  24713. .count();
  24714. // Above 1s so that dropping the microseconds half of the split fails here.
  24715. // Ignoring the setter altogether would not reach this line at all: a client
  24716. // waits forever by default.
  24717. EXPECT_GE(elapsed, 1400);
  24718. EXPECT_LT(elapsed, 30000);
  24719. }
  24720. #ifndef _WIN32
  24721. // A send() that times out after part of the data went out returns the count
  24722. // written so far. Every byte of the frame must still be sent, or the peer reads
  24723. // the next frame's header and payload as the rest of this one.
  24724. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24725. signal(SIGPIPE, SIG_IGN);
  24726. const std::string large(4 * 1024 * 1024, 'A');
  24727. std::atomic<bool> large_sent{false};
  24728. std::atomic<bool> small_sent{false};
  24729. Server svr;
  24730. svr.set_write_timeout(0, 500000);
  24731. svr.set_socket_options([](socket_t sock) {
  24732. int size = 8192;
  24733. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24734. reinterpret_cast<const char *>(&size), sizeof(size));
  24735. });
  24736. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24737. large_sent = ws.send(large.data(), large.size());
  24738. small_sent = ws.send("after");
  24739. std::string msg;
  24740. while (ws.read(msg)) {}
  24741. });
  24742. auto port = svr.bind_to_any_port(HOST);
  24743. std::thread t([&]() { svr.listen_after_bind(); });
  24744. auto se = detail::scope_exit([&] {
  24745. svr.stop();
  24746. t.join();
  24747. });
  24748. svr.wait_until_ready();
  24749. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24750. std::to_string(port) + "/ws");
  24751. client.set_read_timeout(5);
  24752. client.set_socket_options([](socket_t sock) {
  24753. int size = 8192;
  24754. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24755. reinterpret_cast<const char *>(&size), sizeof(size));
  24756. });
  24757. ASSERT_TRUE(client.connect());
  24758. // Outlast the server's write timeout, then drain.
  24759. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24760. std::string msg;
  24761. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24762. EXPECT_TRUE(msg == large);
  24763. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24764. EXPECT_EQ("after", msg);
  24765. EXPECT_TRUE(large_sent);
  24766. EXPECT_TRUE(small_sent);
  24767. client.close();
  24768. }
  24769. #endif
  24770. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24771. Server svr;
  24772. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24773. if (!req.has_header("Authorization")) {
  24774. res.status = StatusCode::Unauthorized_401;
  24775. res.set_content("Unauthorized", "text/plain");
  24776. return Server::HandlerResponse::Handled;
  24777. }
  24778. return Server::HandlerResponse::Unhandled;
  24779. });
  24780. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24781. std::string msg;
  24782. while (ws.read(msg)) {
  24783. ws.send(msg);
  24784. }
  24785. });
  24786. auto port = svr.bind_to_any_port("localhost");
  24787. std::thread t([&]() { svr.listen_after_bind(); });
  24788. svr.wait_until_ready();
  24789. // Without Authorization header - should be rejected before upgrade
  24790. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24791. EXPECT_FALSE(client1.connect());
  24792. // The rejection is framed like any other HTTP response
  24793. {
  24794. Client cli("localhost", port);
  24795. Headers headers = {{"Upgrade", "websocket"},
  24796. {"Connection", "Upgrade"},
  24797. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24798. {"Sec-WebSocket-Version", "13"}};
  24799. auto res = cli.Get("/ws", headers);
  24800. ASSERT_TRUE(res);
  24801. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24802. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24803. EXPECT_EQ("Unauthorized", res->body);
  24804. }
  24805. // With Authorization header - should succeed
  24806. Headers headers = {{"Authorization", "Bearer token123"}};
  24807. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24808. headers);
  24809. ASSERT_TRUE(client2.connect());
  24810. ASSERT_TRUE(client2.send("hello"));
  24811. std::string msg;
  24812. ASSERT_TRUE(client2.read(msg));
  24813. EXPECT_EQ("hello", msg);
  24814. client2.close();
  24815. svr.stop();
  24816. t.join();
  24817. }
  24818. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24819. Server svr;
  24820. std::atomic<int> pre_routing_calls{0};
  24821. std::atomic<int> pre_request_calls{0};
  24822. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24823. pre_routing_calls++;
  24824. if (req.path == "/handled") {
  24825. res.set_content("handled", "text/plain");
  24826. return Server::HandlerResponse::Handled;
  24827. }
  24828. return Server::HandlerResponse::Unhandled;
  24829. });
  24830. svr.set_pre_request_handler([&](const Request &, Response &) {
  24831. pre_request_calls++;
  24832. return Server::HandlerResponse::Unhandled;
  24833. });
  24834. svr.Get("/http", [](const Request &, Response &res) {
  24835. res.set_content("http", "text/plain");
  24836. });
  24837. svr.WebSocket("/ws",
  24838. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24839. auto port = svr.bind_to_any_port("localhost");
  24840. std::thread t([&]() { svr.listen_after_bind(); });
  24841. auto se = detail::scope_exit([&] {
  24842. svr.stop();
  24843. t.join();
  24844. });
  24845. svr.wait_until_ready();
  24846. Headers upgrade = {{"Upgrade", "websocket"},
  24847. {"Connection", "Upgrade"},
  24848. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24849. {"Sec-WebSocket-Version", "13"}};
  24850. auto get = [&](const char *path) {
  24851. pre_routing_calls = 0;
  24852. return Client("localhost", port).Get(path, upgrade);
  24853. };
  24854. // No WebSocket route, but an HTTP one
  24855. auto res = get("/http");
  24856. ASSERT_TRUE(res);
  24857. EXPECT_EQ(StatusCode::OK_200, res->status);
  24858. EXPECT_EQ("http", res->body);
  24859. EXPECT_EQ(1, pre_routing_calls);
  24860. EXPECT_EQ(1, pre_request_calls);
  24861. // No route at all
  24862. res = get("/none");
  24863. ASSERT_TRUE(res);
  24864. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24865. EXPECT_EQ(1, pre_routing_calls);
  24866. // Answered by the pre-routing handler
  24867. res = get("/handled");
  24868. ASSERT_TRUE(res);
  24869. EXPECT_EQ(StatusCode::OK_200, res->status);
  24870. EXPECT_EQ("handled", res->body);
  24871. EXPECT_EQ(1, pre_routing_calls);
  24872. // A WebSocket route
  24873. pre_routing_calls = 0;
  24874. pre_request_calls = 0;
  24875. {
  24876. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24877. "/ws");
  24878. ASSERT_TRUE(client.connect());
  24879. std::string msg;
  24880. ASSERT_TRUE(client.read(msg));
  24881. EXPECT_EQ("ws", msg);
  24882. client.close();
  24883. }
  24884. EXPECT_EQ(1, pre_routing_calls);
  24885. EXPECT_EQ(1, pre_request_calls);
  24886. }
  24887. // An upgrade request answered by a hook leaves its body unread, so that body
  24888. // must not be served as the next request on the connection.
  24889. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24890. Server svr;
  24891. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24892. if (req.path == "/pre-routing") {
  24893. res.set_content("pre-routing", "text/plain");
  24894. return Server::HandlerResponse::Handled;
  24895. }
  24896. return Server::HandlerResponse::Unhandled;
  24897. });
  24898. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24899. if (req.matched_route == "/pre-request") {
  24900. res.set_content("pre-request", "text/plain");
  24901. return Server::HandlerResponse::Handled;
  24902. }
  24903. return Server::HandlerResponse::Unhandled;
  24904. });
  24905. svr.Get("/smuggled", [](const Request &, Response &res) {
  24906. res.set_content("smuggled", "text/plain");
  24907. });
  24908. svr.WebSocket("/pre-request",
  24909. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24910. auto port = svr.bind_to_any_port(HOST);
  24911. std::thread t([&]() { svr.listen_after_bind(); });
  24912. auto se = detail::scope_exit([&] {
  24913. svr.stop();
  24914. t.join();
  24915. });
  24916. svr.wait_until_ready();
  24917. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24918. for (auto path : {"/pre-routing", "/pre-request"}) {
  24919. std::string req = std::string("GET ") + path +
  24920. " HTTP/1.1\r\n"
  24921. "Host: localhost\r\n"
  24922. "Upgrade: websocket\r\n"
  24923. "Connection: Upgrade\r\n"
  24924. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24925. "Sec-WebSocket-Version: 13\r\n"
  24926. "Content-Length: " +
  24927. std::to_string(body.size()) + "\r\n\r\n" + body;
  24928. std::string res;
  24929. ASSERT_TRUE(send_request(5, req, &res, port));
  24930. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24931. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24932. // Only one response, and the body was not served as a request
  24933. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24934. }
  24935. }
  24936. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24937. Server svr;
  24938. std::atomic<int> pre_request_calls{0};
  24939. std::atomic<bool> route_matched{false};
  24940. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24941. pre_request_calls++;
  24942. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24943. if (req.get_header_value("Authorization") != "Bearer token123") {
  24944. res.status = StatusCode::Unauthorized_401;
  24945. res.set_content("Unauthorized", "text/plain");
  24946. return Server::HandlerResponse::Handled;
  24947. }
  24948. return Server::HandlerResponse::Unhandled;
  24949. });
  24950. std::atomic<bool> handler_called{false};
  24951. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24952. handler_called = true;
  24953. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24954. });
  24955. auto port = svr.bind_to_any_port("localhost");
  24956. std::thread t([&]() { svr.listen_after_bind(); });
  24957. svr.wait_until_ready();
  24958. // Without Authorization header - should be rejected before upgrade
  24959. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24960. "/ws/1");
  24961. EXPECT_FALSE(client1.connect());
  24962. EXPECT_FALSE(handler_called);
  24963. EXPECT_EQ(1, pre_request_calls);
  24964. EXPECT_TRUE(route_matched);
  24965. // The rejection is an ordinary HTTP response, not a protocol switch
  24966. {
  24967. Client cli("localhost", port);
  24968. Headers headers = {{"Upgrade", "websocket"},
  24969. {"Connection", "Upgrade"},
  24970. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24971. {"Sec-WebSocket-Version", "13"}};
  24972. auto res = cli.Get("/ws/1", headers);
  24973. ASSERT_TRUE(res);
  24974. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24975. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24976. EXPECT_EQ("Unauthorized", res->body);
  24977. }
  24978. EXPECT_FALSE(handler_called);
  24979. // With Authorization header - should succeed
  24980. Headers headers = {{"Authorization", "Bearer token123"}};
  24981. ws::WebSocketClient client2(
  24982. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24983. ASSERT_TRUE(client2.connect());
  24984. std::string msg;
  24985. ASSERT_TRUE(client2.read(msg));
  24986. EXPECT_EQ("/ws/:id 2", msg);
  24987. EXPECT_TRUE(handler_called);
  24988. client2.close();
  24989. svr.stop();
  24990. t.join();
  24991. }
  24992. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24993. static Headers websocket_upgrade_headers() {
  24994. return {{"Upgrade", "websocket"},
  24995. {"Connection", "Upgrade"},
  24996. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24997. {"Sec-WebSocket-Version", "13"},
  24998. {"Sec-WebSocket-Protocol", "chat"}};
  24999. }
  25000. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25001. Server svr;
  25002. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25003. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25004. return Server::HandlerResponse::Unhandled;
  25005. });
  25006. svr.set_pre_request_handler([](const Request &req, Response &) {
  25007. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25008. return Server::HandlerResponse::Unhandled;
  25009. });
  25010. svr.set_exception_handler(
  25011. [](const Request &, Response &res, std::exception_ptr ep) {
  25012. try {
  25013. std::rethrow_exception(ep);
  25014. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25015. });
  25016. auto handler = [](const Request &, ws::WebSocket &) {};
  25017. svr.WebSocket("/pre-routing", handler);
  25018. svr.WebSocket("/pre-request", handler);
  25019. svr.WebSocket("/sub-protocol", handler,
  25020. [](const std::vector<std::string> &) -> std::string {
  25021. throw std::runtime_error("/sub-protocol");
  25022. });
  25023. auto port = svr.bind_to_any_port(HOST);
  25024. ASSERT_GT(port, 0);
  25025. thread t = thread([&] { svr.listen_after_bind(); });
  25026. auto se = detail::scope_exit([&] {
  25027. svr.stop();
  25028. t.join();
  25029. ASSERT_FALSE(svr.is_running());
  25030. });
  25031. svr.wait_until_ready();
  25032. Client cli(HOST, port);
  25033. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25034. auto res = cli.Get(path, websocket_upgrade_headers());
  25035. if (!res) {
  25036. ADD_FAILURE() << path << ": " << to_string(res.error());
  25037. continue;
  25038. }
  25039. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25040. EXPECT_EQ(path, res->body);
  25041. }
  25042. }
  25043. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25044. Server svr;
  25045. svr.set_pre_routing_handler(
  25046. [](const Request &, Response &) -> Server::HandlerResponse {
  25047. throw std::runtime_error("pre-routing");
  25048. });
  25049. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25050. auto port = svr.bind_to_any_port(HOST);
  25051. ASSERT_GT(port, 0);
  25052. thread t = thread([&] { svr.listen_after_bind(); });
  25053. auto se = detail::scope_exit([&] {
  25054. svr.stop();
  25055. t.join();
  25056. ASSERT_FALSE(svr.is_running());
  25057. });
  25058. svr.wait_until_ready();
  25059. Client cli(HOST, port);
  25060. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25061. ASSERT_TRUE(res) << to_string(res.error());
  25062. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25063. }
  25064. #endif
  25065. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25066. Server svr;
  25067. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25068. // A read timeout is how a handler gets control back. Without it, a handler
  25069. // parked in read() can never write on the connection it is reading.
  25070. ws.set_read_timeout(std::chrono::milliseconds(100));
  25071. std::string msg;
  25072. while (ws.is_open()) {
  25073. auto r = ws.read(msg);
  25074. if (r == httplib::ws::Timeout) {
  25075. ws.send("tick");
  25076. continue;
  25077. }
  25078. if (r == httplib::ws::Fail) { break; }
  25079. ws.send(msg);
  25080. }
  25081. });
  25082. auto port = svr.bind_to_any_port("localhost");
  25083. std::thread t([&]() { svr.listen_after_bind(); });
  25084. svr.wait_until_ready();
  25085. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25086. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25087. ASSERT_TRUE(client.connect());
  25088. // The client sends nothing, so anything it receives came out of the
  25089. // handler's timeout path.
  25090. std::string msg;
  25091. ASSERT_EQ(client.read(msg), ws::Text);
  25092. EXPECT_EQ("tick", msg);
  25093. client.close();
  25094. svr.stop();
  25095. t.join();
  25096. }
  25097. // Stream::read may return fewer bytes than asked for. This is that contract at
  25098. // its worst -- one byte per call -- which is what a frame header straddling a
  25099. // read buffer's boundary looks like to the frame parser.
  25100. class WsByteAtATimeStream : public Stream {
  25101. public:
  25102. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25103. bool is_readable() const override { return true; }
  25104. bool wait_readable() const override { return true; }
  25105. bool wait_writable() const override { return true; }
  25106. ssize_t read(char *ptr, size_t size) override {
  25107. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25108. *ptr = data_[pos_++];
  25109. return 1;
  25110. }
  25111. ssize_t write(const char *, size_t size) override {
  25112. return static_cast<ssize_t>(size);
  25113. }
  25114. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25115. ip = "127.0.0.1";
  25116. port = 0;
  25117. }
  25118. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25119. ip = "127.0.0.1";
  25120. port = 0;
  25121. }
  25122. socket_t socket() const override { return INVALID_SOCKET; }
  25123. time_t duration() const override { return 0; }
  25124. private:
  25125. std::string data_;
  25126. size_t pos_ = 0;
  25127. };
  25128. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25129. // The payload uses the 16-bit extended length, so the header, the length
  25130. // and the mask key are all multi-byte fields here. Each used to be read
  25131. // with a single read() call, which fails as soon as one is split. The
  25132. // payload is also a little over one read chunk, so it is read in two.
  25133. std::string body;
  25134. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25135. body += static_cast<char>(i % 251);
  25136. }
  25137. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25138. std::string frame;
  25139. frame += static_cast<char>(0x81); // FIN + Text
  25140. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25141. frame += static_cast<char>(body.size() >> 8);
  25142. frame += static_cast<char>(body.size() & 0xff);
  25143. for (size_t i = 0; i < 4; i++) {
  25144. frame += static_cast<char>(mask[i]);
  25145. }
  25146. for (size_t i = 0; i < body.size(); i++) {
  25147. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25148. }
  25149. WsByteAtATimeStream strm(frame);
  25150. ws::Opcode opcode;
  25151. std::string payload;
  25152. bool fin = false;
  25153. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25154. /*expect_masked=*/true, body.size()),
  25155. ws::impl::FrameRead::Ok);
  25156. EXPECT_TRUE(fin);
  25157. EXPECT_EQ(opcode, ws::Opcode::Text);
  25158. EXPECT_EQ(payload, body);
  25159. }
  25160. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25161. std::string body(2000, 'x');
  25162. std::string frame;
  25163. frame += static_cast<char>(0x82); // FIN + Binary
  25164. frame += static_cast<char>(126); // 16-bit length follows
  25165. frame += static_cast<char>(body.size() >> 8);
  25166. frame += static_cast<char>(body.size() & 0xff);
  25167. frame += body;
  25168. detail::BufferStream strm;
  25169. strm.write(frame.data(), frame.size());
  25170. ws::Opcode opcode;
  25171. std::string payload;
  25172. bool fin;
  25173. EXPECT_EQ(
  25174. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25175. ws::impl::FrameRead::Ok);
  25176. EXPECT_EQ(body, payload);
  25177. }
  25178. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25179. // The header announces the largest payload allowed, and only 3 bytes of it
  25180. // ever arrive.
  25181. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25182. std::string frame;
  25183. frame += static_cast<char>(0x82); // FIN + Binary
  25184. frame += static_cast<char>(127); // 64-bit length follows
  25185. for (int shift = 56; shift >= 0; shift -= 8) {
  25186. frame += static_cast<char>((len >> shift) & 0xff);
  25187. }
  25188. frame += "abc";
  25189. detail::BufferStream strm;
  25190. strm.write(frame.data(), frame.size());
  25191. ws::Opcode opcode;
  25192. std::string payload;
  25193. bool fin;
  25194. EXPECT_EQ(
  25195. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25196. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25197. ws::impl::FrameRead::Fail);
  25198. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25199. }
  25200. TEST(WebSocketTest, QueryStringInHandshake) {
  25201. Server svr;
  25202. std::mutex mtx;
  25203. std::string received_target;
  25204. std::string received_token;
  25205. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25206. {
  25207. std::lock_guard<std::mutex> lock(mtx);
  25208. received_target = req.target;
  25209. if (req.has_param("token")) {
  25210. received_token = req.get_param_value("token");
  25211. }
  25212. }
  25213. std::string msg;
  25214. while (ws.read(msg)) {
  25215. ws.send(msg);
  25216. }
  25217. });
  25218. auto port = svr.bind_to_any_port("localhost");
  25219. std::thread t([&]() { svr.listen_after_bind(); });
  25220. svr.wait_until_ready();
  25221. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25222. "/ws?token=ABC&session=123");
  25223. ASSERT_TRUE(client.connect());
  25224. // Round-trip ensures the handler has run and captured the request.
  25225. ASSERT_TRUE(client.send("hello"));
  25226. std::string msg;
  25227. ASSERT_TRUE(client.read(msg));
  25228. EXPECT_EQ("hello", msg);
  25229. client.close();
  25230. {
  25231. std::lock_guard<std::mutex> lock(mtx);
  25232. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25233. EXPECT_EQ("ABC", received_token);
  25234. }
  25235. svr.stop();
  25236. t.join();
  25237. }
  25238. // Run a handshake against a throwaway server and hand the request the server
  25239. // received back to the caller, so tests can assert on the headers the client
  25240. // actually put on the wire.
  25241. static void capture_websocket_handshake_request(
  25242. const Headers &client_headers,
  25243. std::function<void(const Request &, int port)> verify) {
  25244. Server svr;
  25245. std::mutex mtx;
  25246. Request received;
  25247. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25248. {
  25249. std::lock_guard<std::mutex> lock(mtx);
  25250. received = req;
  25251. }
  25252. std::string msg;
  25253. while (ws.read(msg)) {
  25254. ws.send(msg);
  25255. }
  25256. });
  25257. auto port = svr.bind_to_any_port("localhost");
  25258. std::thread t([&]() { svr.listen_after_bind(); });
  25259. auto se = detail::scope_exit([&] {
  25260. svr.stop();
  25261. t.join();
  25262. });
  25263. svr.wait_until_ready();
  25264. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25265. client_headers);
  25266. ASSERT_TRUE(client.connect());
  25267. ASSERT_TRUE(client.send("hello"));
  25268. std::string msg;
  25269. ASSERT_TRUE(client.read(msg));
  25270. client.close();
  25271. {
  25272. std::lock_guard<std::mutex> lock(mtx);
  25273. verify(received, port);
  25274. }
  25275. }
  25276. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25277. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25278. // Non-default port must be present in the Host header. Default ports
  25279. // (80/443) are omitted; that logic is covered by
  25280. // MakeHostAndPortStringTest.
  25281. EXPECT_EQ("localhost:" + std::to_string(port),
  25282. req.get_header_value("Host"));
  25283. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25284. req.get_header_value("User-Agent"));
  25285. EXPECT_FALSE(req.has_header("Accept"));
  25286. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25287. EXPECT_FALSE(req.has_header("Content-Length"));
  25288. });
  25289. }
  25290. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25291. capture_websocket_handshake_request(
  25292. {{"Host", "example.com"},
  25293. {"User-Agent", "custom-agent"},
  25294. {"X-Custom", "value"}},
  25295. [](const Request &req, int) {
  25296. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25297. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25298. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25299. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25300. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25301. });
  25302. }
  25303. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25304. capture_websocket_handshake_request(
  25305. {{"Upgrade", "bogus"},
  25306. {"Connection", "close"},
  25307. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25308. {"Sec-WebSocket-Version", "8"}},
  25309. [](const Request &req, int) {
  25310. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25311. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25312. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25313. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25314. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25315. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25316. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25317. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25318. req.get_header_value("Sec-WebSocket-Key"));
  25319. });
  25320. }
  25321. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25322. // A header the client refuses to send must abort the handshake before any
  25323. // part of it reaches the wire; a lone request line would otherwise sit in
  25324. // the peer's buffer as a truncated request.
  25325. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25326. ASSERT_NE(INVALID_SOCKET, srv);
  25327. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25328. sockaddr_in addr{};
  25329. addr.sin_family = AF_INET;
  25330. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25331. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25332. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25333. ASSERT_EQ(0, ::listen(srv, 1));
  25334. sockaddr_in bound{};
  25335. socklen_t bound_len = sizeof(bound);
  25336. ASSERT_EQ(
  25337. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25338. auto port = ntohs(bound.sin_port);
  25339. ssize_t received = -1;
  25340. std::thread t([&] {
  25341. // Bound every blocking call so a regression fails the test with a bad
  25342. // value instead of hanging the suite.
  25343. fd_set rfds;
  25344. FD_ZERO(&rfds);
  25345. FD_SET(srv, &rfds);
  25346. timeval tv{5, 0};
  25347. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25348. 0) {
  25349. return;
  25350. }
  25351. sockaddr_in cli_addr{};
  25352. socklen_t cli_len = sizeof(cli_addr);
  25353. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25354. if (cli == INVALID_SOCKET) { return; }
  25355. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25356. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25357. char buf[4096];
  25358. received = ::recv(cli, buf, sizeof(buf), 0);
  25359. });
  25360. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25361. // connect() has already shut the socket down by the time it returns false,
  25362. // so the peer sees EOF without waiting for the client to be destroyed.
  25363. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25364. {{"X-Bad", "a\r\nInjected: 1"}});
  25365. EXPECT_FALSE(client.connect());
  25366. t.join();
  25367. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25368. EXPECT_EQ(0, received);
  25369. }
  25370. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25371. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25372. // contains "upgrade" as a substring is a different token and must not
  25373. // start a WebSocket handshake.
  25374. auto make_request = [](const std::vector<std::string> &connection_values) {
  25375. Request req;
  25376. req.method = "GET";
  25377. req.headers.emplace("Upgrade", "websocket");
  25378. for (const auto &value : connection_values) {
  25379. req.headers.emplace("Connection", value);
  25380. }
  25381. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25382. req.headers.emplace("Sec-WebSocket-Version", "13");
  25383. return req;
  25384. };
  25385. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25386. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25387. EXPECT_TRUE(
  25388. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25389. EXPECT_TRUE(
  25390. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25391. EXPECT_TRUE(
  25392. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25393. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25394. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25395. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25396. EXPECT_FALSE(
  25397. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25398. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25399. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25400. }
  25401. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25402. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25403. // asks recipients to match each protocol-name case-insensitively, and RFC
  25404. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25405. // client naming websocket alongside another protocol, or on a second field
  25406. // line, is offering websocket; a value that merely contains "websocket" as a
  25407. // substring is a different protocol name and is not.
  25408. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25409. Request req;
  25410. req.method = "GET";
  25411. for (const auto &value : upgrade_values) {
  25412. req.headers.emplace("Upgrade", value);
  25413. }
  25414. req.headers.emplace("Connection", "Upgrade");
  25415. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25416. req.headers.emplace("Sec-WebSocket-Version", "13");
  25417. return req;
  25418. };
  25419. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25420. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25421. EXPECT_TRUE(
  25422. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25423. EXPECT_TRUE(
  25424. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25425. EXPECT_TRUE(
  25426. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25427. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25428. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25429. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25430. EXPECT_FALSE(
  25431. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25432. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25433. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25434. }
  25435. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25436. Server svr;
  25437. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25438. auto port = svr.bind_to_any_port("localhost");
  25439. std::thread t([&]() { svr.listen_after_bind(); });
  25440. auto se = detail::scope_exit([&] {
  25441. svr.stop();
  25442. t.join();
  25443. });
  25444. svr.wait_until_ready();
  25445. Headers headers = {{"Upgrade", "websocket"},
  25446. {"Connection", "notupgrade"},
  25447. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25448. {"Sec-WebSocket-Version", "13"}};
  25449. Client cli("localhost", port);
  25450. auto res = cli.Get("/ws", headers);
  25451. // The route exists only as a WebSocket route, so a request that fails the
  25452. // handshake check falls through to ordinary routing.
  25453. ASSERT_TRUE(res);
  25454. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25455. }
  25456. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25457. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25458. // Connection value is the only thing left for the client to reject.
  25459. Server svr;
  25460. svr.Get("/ws", [](const Request &req, Response &res) {
  25461. res.status = StatusCode::SwitchingProtocol_101;
  25462. res.set_header("Upgrade", "websocket");
  25463. res.set_header("Connection", "notupgrade");
  25464. res.set_header("Sec-WebSocket-Accept",
  25465. detail::websocket_accept_key(
  25466. req.get_header_value("Sec-WebSocket-Key")));
  25467. });
  25468. auto port = svr.bind_to_any_port("localhost");
  25469. std::thread t([&]() { svr.listen_after_bind(); });
  25470. auto se = detail::scope_exit([&] {
  25471. svr.stop();
  25472. t.join();
  25473. });
  25474. svr.wait_until_ready();
  25475. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25476. auto res = client.connect();
  25477. EXPECT_FALSE(res);
  25478. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25479. EXPECT_FALSE(client.is_open());
  25480. }
  25481. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25482. Server svr;
  25483. svr.Get("/ws", [](const Request &req, Response &res) {
  25484. res.status = StatusCode::SwitchingProtocol_101;
  25485. res.set_header("Upgrade", "websocket");
  25486. res.set_header("Connection", "Upgrade");
  25487. res.set_header("Sec-WebSocket-Accept",
  25488. detail::websocket_accept_key(
  25489. req.get_header_value("Sec-WebSocket-Key")));
  25490. res.set_header("Sec-WebSocket-Protocol", "admin");
  25491. });
  25492. auto port = svr.bind_to_any_port("localhost");
  25493. std::thread t([&]() { svr.listen_after_bind(); });
  25494. auto se = detail::scope_exit([&] {
  25495. svr.stop();
  25496. t.join();
  25497. });
  25498. svr.wait_until_ready();
  25499. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25500. // Server selects a subprotocol the client never offered
  25501. {
  25502. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25503. ws::WebSocketClient client(url, headers);
  25504. auto res = client.connect();
  25505. EXPECT_FALSE(res);
  25506. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25507. EXPECT_FALSE(client.is_open());
  25508. EXPECT_TRUE(client.subprotocol().empty());
  25509. }
  25510. // Client offered none but the server named one anyway
  25511. {
  25512. ws::WebSocketClient client(url);
  25513. auto res = client.connect();
  25514. EXPECT_FALSE(res);
  25515. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25516. EXPECT_FALSE(client.is_open());
  25517. EXPECT_TRUE(client.subprotocol().empty());
  25518. }
  25519. }
  25520. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25521. // The socket path doubles as the URL host, so it must not contain '/'.
  25522. const char *shard = getenv("GTEST_SHARD_INDEX");
  25523. const std::string sock_path =
  25524. shard ? std::string("httplib-ws-") + shard + ".sock"
  25525. : std::string("httplib-ws.sock");
  25526. std::remove(sock_path.c_str());
  25527. Server svr;
  25528. std::mutex mtx;
  25529. std::string received_host;
  25530. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25531. {
  25532. std::lock_guard<std::mutex> lock(mtx);
  25533. received_host = req.get_header_value("Host");
  25534. }
  25535. std::string msg;
  25536. while (ws.read(msg)) {
  25537. ws.send(msg);
  25538. }
  25539. });
  25540. svr.set_address_family(AF_UNIX);
  25541. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25542. auto se = detail::scope_exit([&] {
  25543. svr.stop();
  25544. t.join();
  25545. std::remove(sock_path.c_str());
  25546. });
  25547. svr.wait_until_ready();
  25548. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25549. client.set_address_family(AF_UNIX);
  25550. ASSERT_TRUE(client.connect());
  25551. ASSERT_TRUE(client.send("hello"));
  25552. std::string msg;
  25553. ASSERT_TRUE(client.read(msg));
  25554. client.close();
  25555. {
  25556. std::lock_guard<std::mutex> lock(mtx);
  25557. // There is no host:port for a Unix socket, so the same "localhost"
  25558. // placeholder the HTTP client uses is expected.
  25559. EXPECT_EQ("localhost", received_host);
  25560. }
  25561. }
  25562. // Two threads must never parse WebSocket frames from the same stream.
  25563. // close() used to read the peer's Close reply with its own frame read, so it
  25564. // raced a reader thread that was in the middle of a payload: the payload loop
  25565. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25566. // so bytes taken by close() were replaced with bytes from further along the
  25567. // stream. The message kept its length and silently changed content.
  25568. //
  25569. // The raw peer below sends a frame header plus part of the payload, waits for
  25570. // the handler to call close(), and only then sends the rest. Whichever thread
  25571. // would win the race for those bytes, the message must arrive intact, because
  25572. // close() must not touch the stream while read() owns it.
  25573. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25574. #ifndef _WIN32
  25575. signal(SIGPIPE, SIG_IGN);
  25576. #endif
  25577. const size_t payload_len = 120; // fits the 7-bit length field
  25578. const size_t prefix_len = 8;
  25579. const int attempts = 8;
  25580. std::string expected(payload_len, '\0');
  25581. for (size_t i = 0; i < payload_len; i++) {
  25582. expected[i] = static_cast<char>('a' + i % 26);
  25583. }
  25584. std::atomic<bool> peer_stalled{false};
  25585. std::atomic<bool> handler_done{false};
  25586. std::mutex received_mutex;
  25587. std::vector<std::string> received;
  25588. // Bound every wait, so a regression fails the test instead of hanging the
  25589. // suite.
  25590. auto wait_for = [](const std::atomic<bool> &flag) {
  25591. for (int i = 0; i < 500 && !flag; i++) {
  25592. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25593. }
  25594. };
  25595. Server svr;
  25596. svr.set_websocket_ping_interval(0);
  25597. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25598. std::thread reader([&]() {
  25599. std::string msg;
  25600. while (ws.read(msg)) {
  25601. std::lock_guard<std::mutex> guard(received_mutex);
  25602. received.push_back(msg);
  25603. }
  25604. });
  25605. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25606. // inside read_websocket_frame() when close() runs.
  25607. wait_for(peer_stalled);
  25608. ws.close();
  25609. reader.join();
  25610. handler_done = true;
  25611. });
  25612. auto port = svr.bind_to_any_port("127.0.0.1");
  25613. std::thread t([&]() { svr.listen_after_bind(); });
  25614. auto se = detail::scope_exit([&] {
  25615. svr.stop();
  25616. t.join();
  25617. });
  25618. svr.wait_until_ready();
  25619. auto send_bytes = [](socket_t s, const std::string &data) {
  25620. #ifdef _WIN32
  25621. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25622. #else
  25623. auto n = ::send(s, data.data(), data.size(), 0);
  25624. #endif
  25625. return n == static_cast<decltype(n)>(data.size());
  25626. };
  25627. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25628. // Every length used here fits the 7-bit length field.
  25629. auto masked_header = [](uint8_t first_byte, size_t len) {
  25630. std::string h;
  25631. h += static_cast<char>(first_byte);
  25632. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25633. h.append(4, '\0'); // mask key
  25634. return h;
  25635. };
  25636. for (int attempt = 0; attempt < attempts; attempt++) {
  25637. peer_stalled = false;
  25638. handler_done = false;
  25639. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25640. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25641. auto se_sock = detail::scope_exit([&] {
  25642. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25643. });
  25644. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25645. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25646. sockaddr_in addr{};
  25647. addr.sin_family = AF_INET;
  25648. addr.sin_port = htons(static_cast<uint16_t>(port));
  25649. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25650. ASSERT_EQ(
  25651. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25652. << "attempt " << attempt;
  25653. ASSERT_TRUE(send_bytes(sock,
  25654. "GET /ws HTTP/1.1\r\n"
  25655. "Host: 127.0.0.1\r\n"
  25656. "Upgrade: websocket\r\n"
  25657. "Connection: Upgrade\r\n"
  25658. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25659. "Sec-WebSocket-Version: 13\r\n"
  25660. "\r\n"))
  25661. << "attempt " << attempt;
  25662. std::string response;
  25663. while (response.find("\r\n\r\n") == std::string::npos) {
  25664. char buf[512];
  25665. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25666. if (n <= 0) { break; }
  25667. response.append(buf, static_cast<size_t>(n));
  25668. }
  25669. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25670. << "attempt " << attempt;
  25671. // Send the header of a Binary message but only the first prefix_len bytes
  25672. // of its payload, leaving the reader thread stalled inside the payload.
  25673. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25674. expected.substr(0, prefix_len)))
  25675. << "attempt " << attempt;
  25676. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25677. peer_stalled = true;
  25678. // Let close() send its Close frame and park in its own read before the
  25679. // rest of the payload arrives, so both threads are waiting for it.
  25680. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25681. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25682. close_frame += static_cast<char>(0x03); // status 1000
  25683. close_frame += static_cast<char>(0xE8);
  25684. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25685. << "attempt " << attempt;
  25686. // Closing the peer releases the reader thread even on the buggy path,
  25687. // where it waits for bytes another thread already consumed.
  25688. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25689. detail::close_socket(sock);
  25690. sock = INVALID_SOCKET;
  25691. wait_for(handler_done);
  25692. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25693. }
  25694. std::lock_guard<std::mutex> guard(received_mutex);
  25695. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25696. << "a message in flight when close() ran was dropped";
  25697. for (size_t i = 0; i < received.size(); i++) {
  25698. EXPECT_EQ(expected, received[i]) << "message " << i;
  25699. }
  25700. }
  25701. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25702. // returning the socket, or INVALID_SOCKET.
  25703. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25704. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25705. if (sock == INVALID_SOCKET) { return sock; }
  25706. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25707. sockaddr_in addr{};
  25708. addr.sin_family = AF_INET;
  25709. addr.sin_port = htons(static_cast<uint16_t>(port));
  25710. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25711. std::string req = "GET " + path +
  25712. " HTTP/1.1\r\n"
  25713. "Host: 127.0.0.1\r\n"
  25714. "Upgrade: websocket\r\n"
  25715. "Connection: Upgrade\r\n"
  25716. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25717. "Sec-WebSocket-Version: 13\r\n"
  25718. "\r\n";
  25719. std::string res;
  25720. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25721. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25722. static_cast<ssize_t>(req.size())) {
  25723. char c;
  25724. while (res.find("\r\n\r\n") == std::string::npos &&
  25725. ::recv(sock, &c, 1, 0) == 1) {
  25726. res += c;
  25727. }
  25728. }
  25729. if (res.find(" 101 ") == std::string::npos) {
  25730. detail::close_socket(sock);
  25731. return INVALID_SOCKET;
  25732. }
  25733. return sock;
  25734. }
  25735. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25736. // The payload must fit the 7-bit length field.
  25737. static std::string masked_frame(uint8_t first_byte,
  25738. const std::string &payload) {
  25739. std::string f;
  25740. f += static_cast<char>(first_byte);
  25741. f += static_cast<char>(0x80 | payload.size());
  25742. f.append(4, '\0');
  25743. return f + payload;
  25744. }
  25745. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25746. std::atomic<bool> done{false};
  25747. std::string received;
  25748. Server svr;
  25749. svr.set_websocket_ping_interval(0);
  25750. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25751. std::string msg;
  25752. if (ws.read(msg) == ws::Binary) { received = msg; }
  25753. done = true;
  25754. });
  25755. auto port = svr.bind_to_any_port("127.0.0.1");
  25756. std::thread t([&]() { svr.listen_after_bind(); });
  25757. auto se = detail::scope_exit([&] {
  25758. svr.stop();
  25759. t.join();
  25760. });
  25761. svr.wait_until_ready();
  25762. auto sock = connect_raw_websocket(port, "/ws");
  25763. ASSERT_NE(INVALID_SOCKET, sock);
  25764. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25765. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25766. masked_frame(0x89, "p") + // FIN + Ping
  25767. masked_frame(0x80, "lo"); // FIN + Continuation
  25768. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25769. for (int i = 0; i < 500 && !done; i++) {
  25770. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25771. }
  25772. ASSERT_TRUE(done);
  25773. EXPECT_EQ("Hello", received);
  25774. // The Ping between the fragments is answered with a Pong.
  25775. char pong[3];
  25776. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25777. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25778. }
  25779. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25780. Server svr;
  25781. svr.set_websocket_ping_interval(-1);
  25782. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25783. std::string msg;
  25784. while (ws.read(msg)) {}
  25785. });
  25786. auto port = svr.bind_to_any_port("127.0.0.1");
  25787. std::thread t([&]() { svr.listen_after_bind(); });
  25788. auto se = detail::scope_exit([&] {
  25789. svr.stop();
  25790. t.join();
  25791. });
  25792. svr.wait_until_ready();
  25793. auto sock = connect_raw_websocket(port, "/ws");
  25794. ASSERT_NE(INVALID_SOCKET, sock);
  25795. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25796. // Nothing comes while the client stays quiet.
  25797. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25798. char c;
  25799. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25800. }
  25801. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25802. // and that has to end a read() already waiting on the peer, on every platform.
  25803. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25804. // The peer sends no pings, and its handler never calls read(), which is
  25805. // where pongs are written.
  25806. std::mutex mutex;
  25807. std::condition_variable cv;
  25808. auto release = false;
  25809. svr.set_websocket_ping_interval(0);
  25810. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25811. std::unique_lock<std::mutex> lock(mutex);
  25812. cv.wait(lock, [&] { return release; });
  25813. });
  25814. auto port = svr.bind_to_any_port(HOST);
  25815. std::thread t([&]() { svr.listen_after_bind(); });
  25816. auto se = detail::scope_exit([&] {
  25817. {
  25818. std::lock_guard<std::mutex> lock(mutex);
  25819. release = true;
  25820. }
  25821. cv.notify_all();
  25822. svr.stop();
  25823. t.join();
  25824. });
  25825. svr.wait_until_ready();
  25826. ws::WebSocketClient client(std::string(scheme) +
  25827. "://localhost:" + std::to_string(port) + "/ws");
  25828. #ifdef CPPHTTPLIB_SSL_ENABLED
  25829. client.enable_server_certificate_verification(false);
  25830. #endif
  25831. // A ping a second, given up on after two go unanswered: about 3s
  25832. client.set_websocket_ping_interval(1);
  25833. client.set_websocket_max_missed_pongs(2);
  25834. // Well past that, so that a read the timeout ends instead stands out
  25835. client.set_read_timeout(10);
  25836. ASSERT_TRUE(client.connect());
  25837. auto start = std::chrono::steady_clock::now();
  25838. std::string msg;
  25839. EXPECT_EQ(ws::Fail, client.read(msg));
  25840. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25841. std::chrono::steady_clock::now() - start)
  25842. .count(),
  25843. 6000);
  25844. EXPECT_FALSE(client.is_open());
  25845. }
  25846. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25847. Server svr;
  25848. check_pong_timeout_ends_read(svr, "ws");
  25849. }
  25850. #ifdef CPPHTTPLIB_SSL_ENABLED
  25851. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25852. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25853. ASSERT_TRUE(svr.is_valid());
  25854. check_pong_timeout_ends_read(svr, "wss");
  25855. }
  25856. #endif
  25857. // listen() returns only after every handler has, so Server::stop() has to end
  25858. // a WebSocket handler's read() waiting on a client that stays connected and
  25859. // quiet, whether or not the handler bounded its reads, and the client's
  25860. // connection ends with it.
  25861. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  25862. bool bounded) {
  25863. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25864. if (bounded) { ws.set_read_timeout(0, 50000); }
  25865. std::string msg;
  25866. while (ws.read(msg) != ws::Fail) {}
  25867. });
  25868. auto port = svr.bind_to_any_port(HOST);
  25869. std::thread t([&]() { svr.listen_after_bind(); });
  25870. auto se = detail::scope_exit([&] {
  25871. if (t.joinable()) {
  25872. svr.stop();
  25873. t.join();
  25874. }
  25875. });
  25876. svr.wait_until_ready();
  25877. ws::WebSocketClient client(std::string(scheme) +
  25878. "://localhost:" + std::to_string(port) + "/ws");
  25879. #ifdef CPPHTTPLIB_SSL_ENABLED
  25880. client.enable_server_certificate_verification(false);
  25881. #endif
  25882. client.set_read_timeout(2);
  25883. ASSERT_TRUE(client.connect());
  25884. auto stopped = std::async(std::launch::async, [&] {
  25885. svr.stop();
  25886. t.join();
  25887. });
  25888. std::string msg;
  25889. EXPECT_EQ(ws::Fail, client.read(msg));
  25890. EXPECT_FALSE(client.is_open());
  25891. auto in_time =
  25892. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  25893. // A handler the stop did not reach ends when the client leaves
  25894. if (!in_time) { client.close(); }
  25895. stopped.wait();
  25896. EXPECT_TRUE(in_time);
  25897. }
  25898. TEST(WebSocketTest, StopEndsAWaitingRead) {
  25899. Server svr;
  25900. check_stop_ends_websocket_read(svr, "ws", false);
  25901. }
  25902. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  25903. Server svr;
  25904. check_stop_ends_websocket_read(svr, "ws", true);
  25905. }
  25906. #ifdef CPPHTTPLIB_SSL_ENABLED
  25907. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  25908. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25909. ASSERT_TRUE(svr.is_valid());
  25910. check_stop_ends_websocket_read(svr, "wss", false);
  25911. }
  25912. #endif
  25913. // The stop reaches the client as a Close with 1001 Going Away, not as a
  25914. // dropped connection, whether the handler waits for a message or for the rest
  25915. // of one: `sent` is what the client sends first.
  25916. static void check_stop_closes_with_going_away(const std::string &sent) {
  25917. Server svr;
  25918. svr.set_websocket_ping_interval(0);
  25919. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25920. std::string msg;
  25921. while (ws.read(msg)) {}
  25922. });
  25923. auto port = svr.bind_to_any_port("127.0.0.1");
  25924. std::thread t([&]() { svr.listen_after_bind(); });
  25925. auto se = detail::scope_exit([&] {
  25926. svr.stop();
  25927. t.join();
  25928. });
  25929. svr.wait_until_ready();
  25930. // Closed before the join above, which a handler the stop did not reach
  25931. // would otherwise hold up.
  25932. auto sock = connect_raw_websocket(port, "/ws");
  25933. ASSERT_NE(INVALID_SOCKET, sock);
  25934. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25935. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  25936. detail::send_socket(sock, sent.data(), sent.size(), 0));
  25937. // Let the handler take what was sent and wait for more
  25938. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25939. svr.stop();
  25940. // FIN + Close, its length, then the code: unmasked, from a server
  25941. std::string head;
  25942. char c;
  25943. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  25944. head += c;
  25945. }
  25946. const std::string reason = "server stopping";
  25947. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  25948. "\x03\xe9",
  25949. head);
  25950. }
  25951. TEST(WebSocketTest, StopClosesWithGoingAway) {
  25952. check_stop_closes_with_going_away("");
  25953. }
  25954. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  25955. // A Text frame without FIN: the first fragment of a message
  25956. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  25957. }
  25958. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25959. Server svr;
  25960. svr.set_websocket_ping_interval(0);
  25961. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25962. std::string msg;
  25963. while (ws.read(msg)) {}
  25964. });
  25965. auto port = svr.bind_to_any_port("127.0.0.1");
  25966. std::thread t([&]() { svr.listen_after_bind(); });
  25967. auto se = detail::scope_exit([&] {
  25968. svr.stop();
  25969. t.join();
  25970. });
  25971. svr.wait_until_ready();
  25972. // Each Close payload and the reply it should get: an echo when valid, 1002
  25973. // otherwise.
  25974. std::vector<std::pair<std::string, std::string>> cases = {
  25975. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25976. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25977. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25978. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25979. };
  25980. // Also between the fragments of a message.
  25981. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25982. for (const auto &c : cases) {
  25983. auto sock = connect_raw_websocket(port, "/ws");
  25984. ASSERT_NE(INVALID_SOCKET, sock);
  25985. auto frames = prefix + masked_frame(0x88, c.first);
  25986. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25987. std::string reply;
  25988. char buf[256];
  25989. while (reply.size() < 2 + c.second.size()) {
  25990. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25991. if (n <= 0) { break; }
  25992. reply.append(buf, static_cast<size_t>(n));
  25993. }
  25994. detail::close_socket(sock);
  25995. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25996. c.second,
  25997. reply);
  25998. }
  25999. }
  26000. }
  26001. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26002. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26003. protected:
  26004. void SetUp() override {
  26005. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26006. SERVER_PRIVATE_KEY_FILE);
  26007. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26008. std::string msg;
  26009. ws::ReadResult ret;
  26010. while ((ret = ws.read(msg))) {
  26011. if (ret == ws::Binary) {
  26012. ws.send(msg.data(), msg.size());
  26013. } else {
  26014. ws.send(msg);
  26015. }
  26016. }
  26017. });
  26018. port_ = server_->bind_to_any_port(HOST);
  26019. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26020. server_->wait_until_ready();
  26021. }
  26022. void TearDown() override {
  26023. server_->stop();
  26024. if (server_thread_.joinable()) { server_thread_.join(); }
  26025. }
  26026. std::unique_ptr<SSLServer> server_;
  26027. std::thread server_thread_;
  26028. int port_ = 0;
  26029. };
  26030. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26031. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26032. {
  26033. ws::WebSocketClient client(url);
  26034. client.enable_server_certificate_verification(false);
  26035. auto calls = 0;
  26036. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26037. calls++;
  26038. return false;
  26039. });
  26040. EXPECT_FALSE(client.connect());
  26041. EXPECT_GT(calls, 0);
  26042. }
  26043. {
  26044. ws::WebSocketClient client(url);
  26045. client.enable_server_certificate_verification(false);
  26046. client.set_session_verifier([](tls::session_t) {
  26047. return SSLVerifierResponse::CertificateRejected;
  26048. });
  26049. EXPECT_FALSE(client.connect());
  26050. }
  26051. {
  26052. ws::WebSocketClient client(url);
  26053. client.enable_server_certificate_verification(false);
  26054. client.set_session_verifier([](tls::session_t) {
  26055. return SSLVerifierResponse::CertificateAccepted;
  26056. });
  26057. EXPECT_TRUE(client.connect());
  26058. }
  26059. }
  26060. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26061. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26062. "/ws-echo");
  26063. client.enable_server_certificate_verification(false);
  26064. ASSERT_TRUE(client.connect());
  26065. ASSERT_TRUE(client.is_open());
  26066. ASSERT_TRUE(client.send("Hello WSS"));
  26067. std::string msg;
  26068. EXPECT_EQ(ws::Text, client.read(msg));
  26069. EXPECT_EQ("Hello WSS", msg);
  26070. client.close();
  26071. }
  26072. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26073. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26074. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26075. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26076. // client (without calling close() first) is the only path that runs
  26077. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26078. // bug exactly.
  26079. //
  26080. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26081. // when linked against an instrumented libssl; run under Valgrind to catch it
  26082. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26083. // suite (the freed session otherwise stalls on the close handshake) — this test
  26084. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26085. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26086. {
  26087. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26088. "/ws-echo");
  26089. client.enable_server_certificate_verification(false);
  26090. client.set_read_timeout(2, 0);
  26091. client.set_write_timeout(2, 0);
  26092. ASSERT_TRUE(client.connect());
  26093. ASSERT_TRUE(client.is_open());
  26094. ASSERT_TRUE(client.send("still open"));
  26095. // Intentionally do NOT call client.close(): leaving scope runs
  26096. // shutdown_and_close() with the WebSocket still open, which must send the
  26097. // close frame while the TLS session is still alive.
  26098. }
  26099. }
  26100. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26101. // shutdown_and_close() at the start of connect(), reproducing the same
  26102. // use-after-free within the test body rather than at scope exit. The second
  26103. // connect must succeed and echo, proving the close handshake ran over a live
  26104. // session. See the note above about memory-tool requirements.
  26105. TEST_F(WebSocketSSLIntegrationTest,
  26106. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26107. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26108. "/ws-echo");
  26109. client.enable_server_certificate_verification(false);
  26110. client.set_read_timeout(2, 0);
  26111. client.set_write_timeout(2, 0);
  26112. ASSERT_TRUE(client.connect());
  26113. ASSERT_TRUE(client.is_open());
  26114. ASSERT_TRUE(client.send("still open"));
  26115. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26116. // the still-open connection, which must not touch a freed TLS session.
  26117. ASSERT_TRUE(client.connect());
  26118. ASSERT_TRUE(client.is_open());
  26119. ASSERT_TRUE(client.send("after reconnect"));
  26120. std::string msg;
  26121. EXPECT_EQ(ws::Text, client.read(msg));
  26122. EXPECT_EQ("after reconnect", msg);
  26123. client.close();
  26124. }
  26125. #endif
  26126. #ifdef CPPHTTPLIB_SSL_ENABLED
  26127. class WebSocketSSLCATest : public ::testing::Test {
  26128. protected:
  26129. void SetUp() override {
  26130. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26131. SERVER_PRIVATE_KEY_FILE);
  26132. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26133. std::string msg;
  26134. while (ws.read(msg)) {
  26135. ws.send(msg);
  26136. }
  26137. });
  26138. port_ = server_->bind_to_any_port("127.0.0.1");
  26139. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26140. server_->wait_until_ready();
  26141. }
  26142. void TearDown() override {
  26143. server_->stop();
  26144. if (server_thread_.joinable()) { server_thread_.join(); }
  26145. }
  26146. std::string url() const {
  26147. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26148. }
  26149. std::unique_ptr<SSLServer> server_;
  26150. std::thread server_thread_;
  26151. int port_ = 0;
  26152. };
  26153. // A custom CA loaded as PEM verifies the server with full certificate
  26154. // verification enabled
  26155. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26156. ws::WebSocketClient client(url());
  26157. std::string cert;
  26158. read_file(SERVER_CERT2_FILE, cert);
  26159. client.load_ca_cert_store(cert.c_str(), cert.size());
  26160. ASSERT_TRUE(client.connect());
  26161. ASSERT_TRUE(client.send("hello"));
  26162. std::string msg;
  26163. EXPECT_EQ(ws::Text, client.read(msg));
  26164. EXPECT_EQ("hello", msg);
  26165. client.close();
  26166. }
  26167. // A custom CA that does not cover the server must fail verification (the
  26168. // custom CA is exclusive; system certs are not loaded alongside it)
  26169. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26170. ws::WebSocketClient client(url());
  26171. std::string cert;
  26172. read_file(CLIENT_CA_CERT_FILE, cert);
  26173. client.load_ca_cert_store(cert.c_str(), cert.size());
  26174. auto res = client.connect();
  26175. ASSERT_FALSE(res);
  26176. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26177. EXPECT_EQ(-1, res.status());
  26178. EXPECT_NE(0u, res.ssl_backend_error());
  26179. }
  26180. // The same CA as a file path rather than PEM in memory
  26181. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26182. ws::WebSocketClient client(url());
  26183. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26184. ASSERT_TRUE(client.connect());
  26185. ASSERT_TRUE(client.send("hello"));
  26186. std::string msg;
  26187. EXPECT_EQ(ws::Text, client.read(msg));
  26188. EXPECT_EQ("hello", msg);
  26189. client.close();
  26190. }
  26191. // ...and a CA file that does not cover the server still fails, so it is the
  26192. // path above that decides the outcome
  26193. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26194. ws::WebSocketClient client(url());
  26195. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26196. ASSERT_FALSE(client.connect());
  26197. }
  26198. // Regression test: reconnecting with a native custom CA store used to reuse
  26199. // a store handle the previous TLS context had already freed (use-after-free
  26200. // under the OpenSSL backend). The context now lives as long as the client.
  26201. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26202. ws::WebSocketClient client(url());
  26203. std::string cert;
  26204. read_file(SERVER_CERT2_FILE, cert);
  26205. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26206. ASSERT_TRUE(client.connect());
  26207. client.close();
  26208. ASSERT_TRUE(client.connect());
  26209. ASSERT_TRUE(client.send("again"));
  26210. std::string msg;
  26211. EXPECT_EQ(ws::Text, client.read(msg));
  26212. EXPECT_EQ("again", msg);
  26213. client.close();
  26214. }
  26215. // Regression test: a certificate with a trusted chain but no identity match
  26216. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26217. // verification entirely for IP hosts, so this connection succeeded there.
  26218. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26219. // chain verification while the identity check must still fail.
  26220. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26221. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26222. ASSERT_TRUE(svr.is_valid());
  26223. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26224. std::string msg;
  26225. while (ws.read(msg)) {
  26226. ws.send(msg);
  26227. }
  26228. });
  26229. auto port = svr.bind_to_any_port("127.0.0.1");
  26230. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26231. auto se = detail::scope_exit([&] {
  26232. svr.stop();
  26233. t.join();
  26234. });
  26235. svr.wait_until_ready();
  26236. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26237. "/echo");
  26238. std::string cert;
  26239. read_file(SERVER_CERT_FILE, cert);
  26240. client.load_ca_cert_store(cert.c_str(), cert.size());
  26241. ASSERT_FALSE(client.connect());
  26242. }
  26243. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26244. // SNI, so nothing binds the host name to the TLS session. These bind the
  26245. // server to "localhost" instead, the only shape that exercises the SNI and
  26246. // hostname-verification path with certificate verification left enabled.
  26247. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26248. protected:
  26249. void Start(const char *cert_file) {
  26250. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26251. SERVER_PRIVATE_KEY_FILE);
  26252. ASSERT_TRUE(server_->is_valid());
  26253. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26254. std::string msg;
  26255. while (ws.read(msg)) {
  26256. ws.send(msg);
  26257. }
  26258. });
  26259. port_ = server_->bind_to_any_port("localhost");
  26260. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26261. server_->wait_until_ready();
  26262. }
  26263. void TearDown() override {
  26264. if (server_) { server_->stop(); }
  26265. if (server_thread_.joinable()) { server_thread_.join(); }
  26266. }
  26267. std::string url() const {
  26268. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26269. }
  26270. std::unique_ptr<SSLServer> server_;
  26271. std::thread server_thread_;
  26272. int port_ = 0;
  26273. };
  26274. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26275. // out and the connection is usable
  26276. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26277. Start(SERVER_CERT2_FILE);
  26278. ws::WebSocketClient client(url());
  26279. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26280. ASSERT_TRUE(client.connect());
  26281. ASSERT_TRUE(client.send("hello"));
  26282. std::string msg;
  26283. EXPECT_EQ(ws::Text, client.read(msg));
  26284. EXPECT_EQ("hello", msg);
  26285. client.close();
  26286. }
  26287. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26288. // while the identity check must still reject "localhost"
  26289. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26290. Start(SERVER_CERT_FILE);
  26291. ws::WebSocketClient client(url());
  26292. client.set_ca_cert_path(SERVER_CERT_FILE);
  26293. auto res = client.connect();
  26294. ASSERT_FALSE(res);
  26295. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26296. EXPECT_EQ(-1, res.status());
  26297. }
  26298. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26299. // disabled: the chain is still checked, only the identity check is skipped
  26300. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26301. Start(SERVER_CERT_FILE);
  26302. ws::WebSocketClient client(url());
  26303. client.set_ca_cert_path(SERVER_CERT_FILE);
  26304. client.enable_server_hostname_verification(false);
  26305. ASSERT_TRUE(client.connect());
  26306. ASSERT_TRUE(client.send("hello"));
  26307. std::string msg;
  26308. EXPECT_EQ(ws::Text, client.read(msg));
  26309. EXPECT_EQ("hello", msg);
  26310. client.close();
  26311. }
  26312. // A CA that did not sign the server certificate fails the chain, even though
  26313. // the name would match
  26314. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26315. Start(SERVER_CERT2_FILE);
  26316. ws::WebSocketClient client(url());
  26317. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26318. ASSERT_FALSE(client.connect());
  26319. }
  26320. // With verification disabled, neither the chain nor the name is checked
  26321. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26322. Start(SERVER_CERT_FILE);
  26323. ws::WebSocketClient client(url());
  26324. client.enable_server_certificate_verification(false);
  26325. ASSERT_TRUE(client.connect());
  26326. ASSERT_TRUE(client.send("hello"));
  26327. std::string msg;
  26328. EXPECT_EQ(ws::Text, client.read(msg));
  26329. EXPECT_EQ("hello", msg);
  26330. client.close();
  26331. }
  26332. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26333. protected:
  26334. void SetUp() override {
  26335. server_ = httplib::detail::make_unique<SSLServer>(
  26336. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26337. ASSERT_TRUE(server_->is_valid());
  26338. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26339. std::string msg;
  26340. while (ws.read(msg)) {
  26341. ws.send(msg);
  26342. }
  26343. });
  26344. port_ = server_->bind_to_any_port("localhost");
  26345. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26346. server_->wait_until_ready();
  26347. }
  26348. void TearDown() override {
  26349. server_->stop();
  26350. if (server_thread_.joinable()) { server_thread_.join(); }
  26351. }
  26352. std::string url() const {
  26353. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26354. }
  26355. void ConnectWithClientCert(const std::string &client_cert_file,
  26356. const std::string &client_private_key_file,
  26357. const char *private_key_password) {
  26358. std::string cert_pem, key_pem;
  26359. read_file(client_cert_file, cert_pem);
  26360. read_file(client_private_key_file, key_pem);
  26361. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26362. key_pem.c_str(), key_pem.size(),
  26363. private_key_password};
  26364. ConnectWithPem(pem);
  26365. }
  26366. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26367. ws::WebSocketClient client(url(), pem);
  26368. ASSERT_TRUE(client.is_valid());
  26369. client.enable_server_certificate_verification(false);
  26370. ASSERT_TRUE(client.connect());
  26371. ASSERT_TRUE(client.send("hello"));
  26372. std::string msg;
  26373. EXPECT_EQ(ws::Text, client.read(msg));
  26374. EXPECT_EQ("hello", msg);
  26375. client.close();
  26376. }
  26377. std::unique_ptr<SSLServer> server_;
  26378. std::thread server_thread_;
  26379. int port_ = 0;
  26380. };
  26381. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26382. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26383. }
  26384. // Control for the tests above: the fixture's server really does require a
  26385. // client certificate, so it is the PEM the constructor installed that decides
  26386. // the outcome.
  26387. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26388. ws::WebSocketClient client(url());
  26389. ASSERT_TRUE(client.is_valid());
  26390. client.enable_server_certificate_verification(false);
  26391. EXPECT_FALSE(client.connect());
  26392. }
  26393. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26394. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26395. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26396. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26397. }
  26398. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26399. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26400. std::string cert_pem, key_pem;
  26401. read_file(CLIENT_CERT_FILE, cert_pem);
  26402. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26403. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26404. std::vector<char> key(key_pem.begin(), key_pem.end());
  26405. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26406. key.size(), nullptr};
  26407. ConnectWithPem(pem);
  26408. }
  26409. #endif
  26410. #if !defined(_WIN32)
  26411. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26412. auto secret_dir = std::string("./symlink_test_secret");
  26413. auto served_dir = std::string("./symlink_test_served");
  26414. auto secret_file = secret_dir + "/secret.txt";
  26415. auto symlink_path = served_dir + "/escape";
  26416. // Setup: create directories and files
  26417. mkdir(secret_dir.c_str(), 0755);
  26418. mkdir(served_dir.c_str(), 0755);
  26419. {
  26420. std::ofstream ofs(secret_file);
  26421. ofs << "SECRET_DATA";
  26422. }
  26423. // Create symlink using absolute path so it resolves correctly
  26424. #ifdef PATH_MAX
  26425. char abs_secret[PATH_MAX];
  26426. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26427. #else
  26428. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26429. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26430. ASSERT_NE(nullptr, abs_secret);
  26431. #endif
  26432. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26433. auto se = detail::scope_exit([&] {
  26434. unlink(symlink_path.c_str());
  26435. unlink(secret_file.c_str());
  26436. rmdir(served_dir.c_str());
  26437. rmdir(secret_dir.c_str());
  26438. });
  26439. Server svr;
  26440. svr.set_mount_point("/", served_dir);
  26441. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26442. auto se2 = detail::scope_exit([&] {
  26443. svr.stop();
  26444. listen_thread.join();
  26445. });
  26446. svr.wait_until_ready();
  26447. Client cli("localhost", PORT);
  26448. // Symlink pointing outside base dir should be blocked
  26449. auto res = cli.Get("/escape/secret.txt");
  26450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26451. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26452. }
  26453. #else
  26454. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26455. auto secret_dir = std::string("junction_test_secret");
  26456. auto served_dir = std::string("junction_test_served");
  26457. auto secret_file = secret_dir + "\\secret.txt";
  26458. auto junction_path = served_dir + "\\escape";
  26459. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26460. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26461. {
  26462. std::ofstream ofs(secret_file);
  26463. ofs << "SECRET_DATA";
  26464. }
  26465. // A junction needs no privilege to create, unlike a symlink
  26466. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26467. ASSERT_EQ(0, std::system(cmd.c_str()));
  26468. auto se = detail::scope_exit([&] {
  26469. ::RemoveDirectoryA(junction_path.c_str());
  26470. std::remove(secret_file.c_str());
  26471. ::RemoveDirectoryA(served_dir.c_str());
  26472. ::RemoveDirectoryA(secret_dir.c_str());
  26473. });
  26474. Server svr;
  26475. svr.set_mount_point("/", served_dir);
  26476. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26477. auto se2 = detail::scope_exit([&] {
  26478. svr.stop();
  26479. listen_thread.join();
  26480. });
  26481. svr.wait_until_ready();
  26482. Client cli("localhost", PORT);
  26483. // Junction pointing outside base dir should be blocked
  26484. auto res = cli.Get("/escape/secret.txt");
  26485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26486. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26487. }
  26488. #endif
  26489. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26490. // "GET /smuggled" request), reads the first response, and only then sends the
  26491. // embedded request as the body. Returns how many times /smuggled ran.
  26492. //
  26493. // The body is sent AFTER receiving the first response (as in the original
  26494. // PoC) so that the stream_line_reader cannot buffer it together with the
  26495. // headers of the first request.
  26496. static int count_smuggled_requests(const std::string &outer_head,
  26497. std::string &first_response) {
  26498. Server svr;
  26499. svr.set_mount_point("/", "./www");
  26500. std::atomic<int> smuggled_count(0);
  26501. svr.Get("/smuggled", [&](const Request &, Response &res) {
  26502. smuggled_count++;
  26503. res.set_content("oops", "text/plain");
  26504. });
  26505. svr.Post("/post", [&](const Request &req, Response &res) {
  26506. res.set_content(req.body, "text/plain");
  26507. });
  26508. auto port = svr.bind_to_any_port("localhost");
  26509. thread t = thread([&] { svr.listen_after_bind(); });
  26510. auto se = detail::scope_exit([&] {
  26511. svr.stop();
  26512. t.join();
  26513. });
  26514. svr.wait_until_ready();
  26515. auto error = Error::Success;
  26516. auto sock = detail::create_client_socket(
  26517. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  26518. /*connection_timeout_sec=*/2, 0,
  26519. /*read_timeout_sec=*/2, 0,
  26520. /*write_timeout_sec=*/2, 0, std::string(), error);
  26521. EXPECT_NE(INVALID_SOCKET, sock);
  26522. if (sock == INVALID_SOCKET) { return -1; }
  26523. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26524. // The "smuggled" request will be sent as the body of the outer request
  26525. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  26526. "Host: localhost\r\n"
  26527. "Connection: close\r\n"
  26528. "\r\n";
  26529. auto head = outer_head;
  26530. auto len = std::to_string(smuggled.size());
  26531. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26532. pos = head.find("{len}", pos + len.size())) {
  26533. head.replace(pos, 5, len);
  26534. }
  26535. // Step 1: Send only the outer request headers (no body yet)
  26536. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26537. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26538. // Step 2: Read the first response
  26539. char buf[4096];
  26540. for (;;) {
  26541. auto n = recv(sock, buf, sizeof(buf), 0);
  26542. if (n <= 0) break;
  26543. first_response.append(buf, static_cast<size_t>(n));
  26544. // Stop once we have a complete response (headers + body)
  26545. auto hdr_end = first_response.find("\r\n\r\n");
  26546. if (hdr_end != std::string::npos) {
  26547. // Check for Content-Length to know when the body is complete
  26548. auto cl_pos = first_response.find("Content-Length:");
  26549. if (cl_pos != std::string::npos) {
  26550. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26551. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26552. auto cl = std::stoul(
  26553. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26554. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26555. } else {
  26556. break; // No Content-Length, assume headers-only response
  26557. }
  26558. }
  26559. }
  26560. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26561. // vulnerable server the keep-alive loop reads this as a second request. The
  26562. // server may already have closed the connection, so the result is ignored.
  26563. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26564. // Half-close so that a server which drained the body sees EOF and closes,
  26565. // instead of the read below waiting for the read timeout.
  26566. #ifdef _WIN32
  26567. ::shutdown(sock, SD_SEND);
  26568. #else
  26569. ::shutdown(sock, SHUT_WR);
  26570. #endif
  26571. // Step 4: Read until the server closes the connection
  26572. for (;;) {
  26573. auto n = recv(sock, buf, sizeof(buf), 0);
  26574. if (n <= 0) break;
  26575. }
  26576. return smuggled_count.load();
  26577. }
  26578. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26579. // A GET request with Content-Length to a static file handler must have its
  26580. // body drained before the keep-alive connection is reused. Otherwise the
  26581. // unread body bytes are interpreted as the next HTTP request.
  26582. std::string first_response;
  26583. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26584. "Host: localhost\r\n"
  26585. "Content-Length: {len}\r\n"
  26586. "\r\n",
  26587. first_response));
  26588. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26589. }
  26590. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26591. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26592. // be answered with 400 and the connection closed. Treating it as "no body"
  26593. // leaves the body to be parsed as the next request.
  26594. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26595. const char *targets[] = {
  26596. "GET /file", // handler that never reads the body
  26597. "GET /not-found", // no handler matches (404)
  26598. "POST /post", // handler that reads the body
  26599. };
  26600. for (auto target : targets) {
  26601. for (auto value : values) {
  26602. std::string first_response;
  26603. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26604. " HTTP/1.1\r\n"
  26605. "Host: localhost\r\n"
  26606. "Content-Length: " +
  26607. value + "\r\n\r\n",
  26608. first_response))
  26609. << target << " with Content-Length: " << value;
  26610. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  26611. << target << " with Content-Length: " << value;
  26612. }
  26613. }
  26614. }
  26615. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  26616. // A 400 for an unparseable request line leaves the rest of the message
  26617. // unread, so the connection must be closed rather than reused.
  26618. std::string first_response;
  26619. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  26620. "Host: localhost\r\n"
  26621. "Content-Length: {len}\r\n"
  26622. "\r\n",
  26623. first_response));
  26624. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26625. }
  26626. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  26627. // Same as above for a header block that fails to parse.
  26628. std::string first_response;
  26629. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26630. "Host: localhost\r\n"
  26631. "Bad Header\r\n"
  26632. "Content-Length: {len}\r\n"
  26633. "\r\n",
  26634. first_response));
  26635. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26636. }
  26637. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  26638. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  26639. // server must not read another request on that connection, even when the
  26640. // request had no body to drain.
  26641. std::string first_response;
  26642. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  26643. "Host: localhost\r\n"
  26644. "\r\n",
  26645. first_response));
  26646. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  26647. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  26648. }
  26649. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  26650. // A content reader that stops early leaves the stream inside the body.
  26651. // Draining the whole Content-Length from there, or reading the body again,
  26652. // reads into the next request, and whatever follows is parsed as a request
  26653. // of its own.
  26654. Server svr;
  26655. std::atomic<int> smuggled_count(0);
  26656. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  26657. svr.Post("/upload", [](const Request &req, Response &res,
  26658. const ContentReader &content_reader) {
  26659. // Stop at the last chunk, so the whole body has been read however it
  26660. // arrives.
  26661. auto length = req.get_header_value_u64("Content-Length");
  26662. size_t total = 0;
  26663. auto consumed = content_reader([&](const char *, size_t n) {
  26664. total += n;
  26665. return total < length;
  26666. });
  26667. EXPECT_FALSE(consumed);
  26668. if (req.has_param("retry")) {
  26669. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  26670. }
  26671. // Replace the 400 the aborted read set, which would close the connection.
  26672. res.set_redirect("/done");
  26673. });
  26674. auto port = svr.bind_to_any_port(HOST);
  26675. thread t = thread([&] { svr.listen_after_bind(); });
  26676. auto se = detail::scope_exit([&] {
  26677. svr.stop();
  26678. t.join();
  26679. });
  26680. svr.wait_until_ready();
  26681. // A front end sees the second request as a POST whose body is the GET. The
  26682. // first body is as long as the POST's headers, so draining it again reads
  26683. // exactly those and leaves the GET to be parsed next.
  26684. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  26685. "Host: localhost\r\n"
  26686. "\r\n";
  26687. std::string second_head = "POST /post HTTP/1.1\r\n"
  26688. "Host: localhost\r\n"
  26689. "Content-Length: " +
  26690. std::to_string(inner.size()) +
  26691. "\r\n"
  26692. "\r\n";
  26693. for (auto target : {"/upload", "/upload?retry"}) {
  26694. smuggled_count = 0;
  26695. std::string request = "POST " + std::string(target) +
  26696. " HTTP/1.1\r\n"
  26697. "Host: localhost\r\n"
  26698. "Content-Length: " +
  26699. std::to_string(second_head.size()) +
  26700. "\r\n"
  26701. "\r\n" +
  26702. std::string(second_head.size(), 'A') + second_head +
  26703. inner;
  26704. std::string response;
  26705. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  26706. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  26707. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  26708. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  26709. EXPECT_EQ(0, smuggled_count.load()) << target;
  26710. }
  26711. }
  26712. // An error response closes the connection anyway, so the body is left unread
  26713. // with a redirect, such as one to a login page.
  26714. static void serve_redirects(Server &svr,
  26715. const std::function<void(int)> &client) {
  26716. svr.set_pre_routing_handler([](const Request &, Response &res) {
  26717. res.set_redirect("/login");
  26718. return Server::HandlerResponse::Handled;
  26719. });
  26720. auto port = svr.bind_to_any_port(HOST);
  26721. ASSERT_GT(port, 0);
  26722. thread t = thread([&] { svr.listen_after_bind(); });
  26723. auto se = detail::scope_exit([&] {
  26724. svr.stop();
  26725. t.join();
  26726. ASSERT_FALSE(svr.is_running());
  26727. });
  26728. svr.wait_until_ready();
  26729. client(port);
  26730. }
  26731. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  26732. Server svr;
  26733. serve_redirects(svr, [](int port) {
  26734. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  26735. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  26736. std::to_string(body.size()) + "\r\n\r\n" + body +
  26737. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  26738. std::string resp;
  26739. ASSERT_TRUE(send_request(1, req, &resp, port));
  26740. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  26741. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  26742. });
  26743. }
  26744. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  26745. Server svr;
  26746. svr.set_read_timeout(0, 200000);
  26747. serve_redirects(svr, [](int port) {
  26748. // A byte every 100 ms keeps each read within the read timeout, but not the
  26749. // body as a whole, so the server closes and the bytes sent after that fail.
  26750. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  26751. "Content-Length: 10\r\n\r\n"};
  26752. parts.resize(11, "x");
  26753. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26754. });
  26755. }
  26756. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26757. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26758. // must be rejected with 400 Bad Request.
  26759. Server svr;
  26760. svr.Post("/test", [&](const Request &, Response &res) {
  26761. res.set_content("ok", "text/plain");
  26762. });
  26763. thread t = thread([&] { svr.listen(HOST, PORT); });
  26764. auto se = detail::scope_exit([&] {
  26765. svr.stop();
  26766. t.join();
  26767. ASSERT_FALSE(svr.is_running());
  26768. });
  26769. svr.wait_until_ready();
  26770. // Exact "chunked"
  26771. {
  26772. auto req = "POST /test HTTP/1.1\r\n"
  26773. "Host: localhost\r\n"
  26774. "Content-Length: 5\r\n"
  26775. "Transfer-Encoding: chunked\r\n"
  26776. "Connection: close\r\n"
  26777. "\r\n"
  26778. "hello";
  26779. std::string response;
  26780. ASSERT_TRUE(send_request(1, req, &response));
  26781. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26782. response.substr(0, response.find("\r\n")));
  26783. }
  26784. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26785. {
  26786. auto req = "POST /test HTTP/1.1\r\n"
  26787. "Host: localhost\r\n"
  26788. "Content-Length: 5\r\n"
  26789. "Transfer-Encoding: gzip, chunked\r\n"
  26790. "Connection: close\r\n"
  26791. "\r\n"
  26792. "hello";
  26793. std::string response;
  26794. ASSERT_TRUE(send_request(1, req, &response));
  26795. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26796. response.substr(0, response.find("\r\n")));
  26797. }
  26798. }
  26799. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26800. Server svr;
  26801. svr.Post("/test", [&](const Request &, Response &res) {
  26802. res.set_content("ok", "text/plain");
  26803. });
  26804. thread t = thread([&] { svr.listen(HOST, PORT); });
  26805. auto se = detail::scope_exit([&] {
  26806. svr.stop();
  26807. t.join();
  26808. ASSERT_FALSE(svr.is_running());
  26809. });
  26810. svr.wait_until_ready();
  26811. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26812. // length cannot be determined, so the server must answer 400 and close
  26813. // rather than treat the request as bodyless and leave the body in the
  26814. // socket for the next request to pick up.
  26815. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26816. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26817. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26818. std::string response;
  26819. ASSERT_TRUE(send_request(1, req, &response));
  26820. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26821. response.substr(0, response.find("\r\n")))
  26822. << transfer_encoding;
  26823. }
  26824. // RFC 9110 5.3: the codings may also be split across several
  26825. // Transfer-Encoding lines, which combine in the order they were received.
  26826. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26827. // just like the single-line "chunked, gzip" above.
  26828. {
  26829. auto req = "POST /test HTTP/1.1\r\n"
  26830. "Host: localhost\r\n"
  26831. "Transfer-Encoding: chunked\r\n"
  26832. "Transfer-Encoding: gzip\r\n"
  26833. "\r\n"
  26834. "0\r\n\r\n";
  26835. std::string response;
  26836. ASSERT_TRUE(send_request(1, req, &response));
  26837. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26838. response.substr(0, response.find("\r\n")));
  26839. }
  26840. }
  26841. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26842. Server svr;
  26843. svr.Post("/test", [&](const Request &, Response &res) {
  26844. res.set_content("ok", "text/plain");
  26845. });
  26846. auto port = svr.bind_to_any_port(HOST);
  26847. ASSERT_GT(port, 0);
  26848. thread t = thread([&] { svr.listen_after_bind(); });
  26849. auto se = detail::scope_exit([&] {
  26850. svr.stop();
  26851. t.join();
  26852. ASSERT_FALSE(svr.is_running());
  26853. });
  26854. svr.wait_until_ready();
  26855. for (auto transfer_encoding :
  26856. {"Transfer-Encoding: gzip, chunked\r\n",
  26857. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26858. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26859. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26860. transfer_encoding + "\r\n0\r\n\r\n";
  26861. std::string response;
  26862. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26863. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26864. response.substr(0, response.find("\r\n")))
  26865. << transfer_encoding;
  26866. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26867. << transfer_encoding;
  26868. }
  26869. }
  26870. // Regression for issue #2450: a DELETE without Content-Length on a
  26871. // keep-alive connection must not let the post-response drain consume the
  26872. // next request's bytes.
  26873. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26874. Server svr;
  26875. std::atomic<int> delete_count(0);
  26876. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26877. delete_count++;
  26878. res.status = StatusCode::NoContent_204;
  26879. });
  26880. auto port = svr.bind_to_any_port(HOST);
  26881. thread t = thread([&] { svr.listen_after_bind(); });
  26882. auto se = detail::scope_exit([&] {
  26883. svr.stop();
  26884. t.join();
  26885. });
  26886. svr.wait_until_ready();
  26887. auto error = Error::Success;
  26888. auto sock = detail::create_client_socket(
  26889. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26890. /*connection_timeout_sec=*/2, 0,
  26891. /*read_timeout_sec=*/2, 0,
  26892. /*write_timeout_sec=*/2, 0, std::string(), error);
  26893. ASSERT_NE(INVALID_SOCKET, sock);
  26894. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26895. auto send_request_and_read_response = [&](const std::string &req,
  26896. std::string &out) -> bool {
  26897. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26898. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26899. char buf[4096];
  26900. for (;;) {
  26901. auto n = recv(sock, buf, sizeof(buf), 0);
  26902. if (n <= 0) { return !out.empty(); }
  26903. out.append(buf, static_cast<size_t>(n));
  26904. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26905. }
  26906. };
  26907. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26908. "Host: localhost\r\n"
  26909. "\r\n";
  26910. std::string resp1;
  26911. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26912. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26913. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26914. "Host: localhost\r\n"
  26915. "Connection: close\r\n"
  26916. "\r\n";
  26917. std::string resp2;
  26918. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26919. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26920. EXPECT_EQ(2, delete_count.load());
  26921. }
  26922. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26923. Server svr;
  26924. svr.Post("/ingest", [&](const Request &, Response &res,
  26925. const ContentReader &content_reader) {
  26926. auto consumed = content_reader([](const char *, size_t) { return false; });
  26927. EXPECT_FALSE(consumed);
  26928. res.status = StatusCode::Conflict_409;
  26929. res.set_header("Connection", "close");
  26930. });
  26931. auto port = svr.bind_to_any_port(HOST);
  26932. thread t = thread([&] { svr.listen_after_bind(); });
  26933. auto se = detail::scope_exit([&] {
  26934. svr.stop();
  26935. t.join();
  26936. });
  26937. svr.wait_until_ready();
  26938. auto error = Error::Success;
  26939. auto sock = detail::create_client_socket(
  26940. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26941. /*connection_timeout_sec=*/2, 0,
  26942. /*read_timeout_sec=*/1, 0,
  26943. /*write_timeout_sec=*/2, 0, std::string(), error);
  26944. ASSERT_NE(INVALID_SOCKET, sock);
  26945. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26946. std::string request = "POST /ingest HTTP/1.1\r\n"
  26947. "Host: localhost\r\n"
  26948. "Transfer-Encoding: chunked\r\n"
  26949. "\r\n"
  26950. "4\r\n"
  26951. "data\r\n";
  26952. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26953. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  26954. std::string response;
  26955. ssize_t received = 0;
  26956. do {
  26957. char buf[4096];
  26958. received = recv(sock, buf, sizeof(buf), 0);
  26959. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  26960. } while (received > 0);
  26961. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  26962. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  26963. EXPECT_EQ(0, received);
  26964. }
  26965. namespace no_proxy_test {
  26966. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  26967. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  26968. // calling listen().
  26969. class ScopedServer {
  26970. public:
  26971. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  26972. ~ScopedServer() {
  26973. svr_.stop();
  26974. if (th_.joinable()) { th_.join(); }
  26975. }
  26976. Server &svr() { return svr_; }
  26977. int port() const { return port_; }
  26978. void listen() {
  26979. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26980. svr_.wait_until_ready();
  26981. }
  26982. private:
  26983. Server svr_;
  26984. std::thread th_;
  26985. int port_ = 0;
  26986. };
  26987. class ProxyAndTargetServers {
  26988. public:
  26989. ProxyAndTargetServers() {
  26990. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26991. proxy_hits_++;
  26992. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26993. res.set_content("via-proxy", "text/plain");
  26994. });
  26995. target_.Get(".*", [this](const Request &req, Response &res) {
  26996. target_hits_++;
  26997. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26998. res.set_content("direct", "text/plain");
  26999. });
  27000. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27001. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27002. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27003. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27004. proxy_mock_.wait_until_ready();
  27005. target_.wait_until_ready();
  27006. }
  27007. ~ProxyAndTargetServers() {
  27008. proxy_mock_.stop();
  27009. target_.stop();
  27010. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27011. if (target_thread_.joinable()) { target_thread_.join(); }
  27012. }
  27013. Server &proxy_mock() { return proxy_mock_; }
  27014. Server &target() { return target_; }
  27015. int proxy_port() const { return proxy_port_; }
  27016. int target_port() const { return target_port_; }
  27017. int proxy_hits() const { return proxy_hits_.load(); }
  27018. int target_hits() const { return target_hits_.load(); }
  27019. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27020. void reset_counters() {
  27021. proxy_hits_ = 0;
  27022. target_hits_ = 0;
  27023. last_had_proxy_authz_ = false;
  27024. }
  27025. private:
  27026. Server proxy_mock_;
  27027. Server target_;
  27028. std::thread proxy_thread_;
  27029. std::thread target_thread_;
  27030. int proxy_port_ = 0;
  27031. int target_port_ = 0;
  27032. std::atomic<int> proxy_hits_{0};
  27033. std::atomic<int> target_hits_{0};
  27034. std::atomic<bool> last_had_proxy_authz_{false};
  27035. };
  27036. inline std::unique_ptr<Client> make_client(const std::string &host,
  27037. ProxyAndTargetServers &s) {
  27038. auto cli = detail::make_unique<Client>(host, s.target_port());
  27039. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27040. cli->set_proxy("127.0.0.1", s.proxy_port());
  27041. return cli;
  27042. }
  27043. } // namespace no_proxy_test
  27044. using no_proxy_test::make_client;
  27045. using no_proxy_test::ProxyAndTargetServers;
  27046. // A stream request carries the credentials a buffered request does
  27047. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27048. no_proxy_test::ScopedServer origin;
  27049. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27050. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27051. });
  27052. origin.listen();
  27053. Client cli("127.0.0.1", origin.port());
  27054. cli.set_basic_auth("user", "pass");
  27055. auto handle = cli.open_stream("GET", "/x");
  27056. ASSERT_TRUE(handle.is_valid());
  27057. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27058. Client bearer("127.0.0.1", origin.port());
  27059. bearer.set_bearer_token_auth("tok");
  27060. auto handle2 = bearer.open_stream("GET", "/x");
  27061. ASSERT_TRUE(handle2.is_valid());
  27062. EXPECT_EQ("Bearer tok", read_all(handle2));
  27063. }
  27064. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27065. // takes its own credentials, as for a buffered request
  27066. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27067. std::string target, authz, proxy_authz;
  27068. no_proxy_test::ScopedServer proxy;
  27069. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27070. target = req.target;
  27071. authz = req.get_header_value("Authorization");
  27072. proxy_authz = req.get_header_value("Proxy-Authorization");
  27073. res.set_content("ok", "text/plain");
  27074. });
  27075. proxy.listen();
  27076. Client cli("origin.example", 8080);
  27077. cli.set_proxy("127.0.0.1", proxy.port());
  27078. cli.set_proxy_basic_auth("puser", "ppass");
  27079. cli.set_basic_auth("user", "pass");
  27080. auto handle = cli.open_stream("GET", "/x");
  27081. ASSERT_TRUE(handle.is_valid());
  27082. EXPECT_EQ("ok", read_all(handle));
  27083. EXPECT_EQ("http://origin.example:8080/x", target);
  27084. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27085. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27086. }
  27087. // In absolute-form the path follows the authority, so a path that does not
  27088. // begin with '/' would make the proxy connect to another host
  27089. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27090. std::vector<std::string> targets;
  27091. no_proxy_test::ScopedServer proxy;
  27092. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27093. targets.push_back(req.target);
  27094. res.set_content("ok", "text/plain");
  27095. });
  27096. proxy.listen();
  27097. Client cli("origin.example", 8080);
  27098. cli.set_proxy("127.0.0.1", proxy.port());
  27099. cli.set_basic_auth("user", "pass");
  27100. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27101. auto res = cli.Get(path);
  27102. EXPECT_FALSE(res) << path;
  27103. auto handle = cli.open_stream("GET", path);
  27104. EXPECT_FALSE(handle.is_valid()) << path;
  27105. }
  27106. EXPECT_TRUE(targets.empty());
  27107. auto res = cli.Get("/x");
  27108. ASSERT_TRUE(res);
  27109. ASSERT_EQ(1u, targets.size());
  27110. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27111. }
  27112. TEST(NoProxyTest, ExactHostnameBypasses) {
  27113. ProxyAndTargetServers s;
  27114. auto cli = make_client("example.com", s);
  27115. cli->set_no_proxy({"example.com"});
  27116. auto res = cli->Get("/");
  27117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27118. EXPECT_EQ(0, s.proxy_hits());
  27119. EXPECT_EQ(1, s.target_hits());
  27120. }
  27121. TEST(NoProxyTest, SubdomainBypasses) {
  27122. ProxyAndTargetServers s;
  27123. auto cli = make_client("foo.example.com", s);
  27124. cli->set_no_proxy({"example.com"});
  27125. auto res = cli->Get("/");
  27126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27127. EXPECT_EQ(0, s.proxy_hits());
  27128. EXPECT_EQ(1, s.target_hits());
  27129. }
  27130. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27131. // Regression guard: "evilexample.com" must not be considered a subdomain
  27132. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27133. // check would let traffic bypass the proxy and leak credentials direct
  27134. // to the attacker host.
  27135. ProxyAndTargetServers s;
  27136. auto cli = make_client("evilexample.com", s);
  27137. cli->set_no_proxy({"example.com"});
  27138. auto res = cli->Get("/");
  27139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27140. EXPECT_GE(s.proxy_hits(), 1);
  27141. EXPECT_EQ(0, s.target_hits());
  27142. }
  27143. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27144. ProxyAndTargetServers s;
  27145. auto cli = make_client("example.com.evil.com", s);
  27146. cli->set_no_proxy({"example.com"});
  27147. auto res = cli->Get("/");
  27148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27149. EXPECT_GE(s.proxy_hits(), 1);
  27150. EXPECT_EQ(0, s.target_hits());
  27151. }
  27152. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27153. ProxyAndTargetServers s;
  27154. auto cli = make_client("example.com", s);
  27155. cli->set_no_proxy({".example.com"});
  27156. auto res = cli->Get("/");
  27157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27158. EXPECT_EQ(0, s.proxy_hits());
  27159. EXPECT_EQ(1, s.target_hits());
  27160. }
  27161. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27162. ProxyAndTargetServers s;
  27163. auto cli = make_client("Example.COM", s);
  27164. cli->set_no_proxy({"EXAMPLE.com"});
  27165. auto res = cli->Get("/");
  27166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27167. EXPECT_EQ(0, s.proxy_hits());
  27168. EXPECT_EQ(1, s.target_hits());
  27169. }
  27170. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27171. ProxyAndTargetServers s;
  27172. auto cli = make_client("example.com.", s);
  27173. cli->set_no_proxy({"example.com"});
  27174. auto res = cli->Get("/");
  27175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27176. EXPECT_EQ(0, s.proxy_hits());
  27177. EXPECT_EQ(1, s.target_hits());
  27178. }
  27179. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27180. // Trailing dots must be normalized on BOTH sides — host and entry.
  27181. // An implementation that only strips the host-side trailing dot would
  27182. // fail to match host "example.com" against entry "example.com." because
  27183. // a literal substring search would compare 11 chars against 12.
  27184. ProxyAndTargetServers s;
  27185. auto cli = make_client("example.com", s);
  27186. cli->set_no_proxy({"example.com."});
  27187. auto res = cli->Get("/");
  27188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27189. EXPECT_EQ(0, s.proxy_hits());
  27190. EXPECT_EQ(1, s.target_hits());
  27191. }
  27192. TEST(NoProxyTest, WildcardBypassesEverything) {
  27193. ProxyAndTargetServers s;
  27194. auto cli = make_client("anything.invalid.test", s);
  27195. cli->set_no_proxy({"*"});
  27196. auto res = cli->Get("/");
  27197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27198. EXPECT_EQ(0, s.proxy_hits());
  27199. EXPECT_EQ(1, s.target_hits());
  27200. }
  27201. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27202. ProxyAndTargetServers s;
  27203. Client cli("127.0.0.1", s.target_port());
  27204. cli.set_proxy("127.0.0.1", s.proxy_port());
  27205. cli.set_no_proxy({"127.0.0.1"});
  27206. auto res = cli.Get("/");
  27207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27208. EXPECT_EQ(0, s.proxy_hits());
  27209. EXPECT_EQ(1, s.target_hits());
  27210. }
  27211. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27212. ProxyAndTargetServers s;
  27213. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27214. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27215. cli.set_proxy("127.0.0.1", s.proxy_port());
  27216. cli.set_no_proxy({"::1"});
  27217. auto res = cli.Get("/");
  27218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27219. EXPECT_EQ(0, s.proxy_hits());
  27220. EXPECT_EQ(1, s.target_hits());
  27221. }
  27222. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27223. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27224. // must still be recognized as IPv6 for CIDR matching. Implementations
  27225. // that detect IPv6 only when the host begins with '[' would parse the
  27226. // host as a hostname and miss the match.
  27227. ProxyAndTargetServers s;
  27228. Client cli("fe80::1", s.target_port());
  27229. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27230. cli.set_proxy("127.0.0.1", s.proxy_port());
  27231. cli.set_no_proxy({"fe80::/10"});
  27232. auto res = cli.Get("/");
  27233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27234. EXPECT_EQ(0, s.proxy_hits());
  27235. EXPECT_EQ(1, s.target_hits());
  27236. }
  27237. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27238. ProxyAndTargetServers s;
  27239. Client cli("::1", s.target_port());
  27240. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27241. cli.set_proxy("127.0.0.1", s.proxy_port());
  27242. cli.set_no_proxy({"[::1]"});
  27243. auto res = cli.Get("/");
  27244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27245. EXPECT_EQ(0, s.proxy_hits());
  27246. EXPECT_EQ(1, s.target_hits());
  27247. }
  27248. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27249. ProxyAndTargetServers s;
  27250. Client cli("fe80::1", s.target_port());
  27251. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27252. cli.set_proxy("127.0.0.1", s.proxy_port());
  27253. cli.set_no_proxy({"[fe80::]/10"});
  27254. auto res = cli.Get("/");
  27255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27256. EXPECT_EQ(0, s.proxy_hits());
  27257. EXPECT_EQ(1, s.target_hits());
  27258. }
  27259. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27260. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27261. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27262. // tricks via address-family conversion.
  27263. ProxyAndTargetServers s;
  27264. Client cli("::ffff:127.0.0.1", s.target_port());
  27265. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27266. cli.set_proxy("127.0.0.1", s.proxy_port());
  27267. cli.set_no_proxy({"127.0.0.1"});
  27268. auto res = cli.Get("/");
  27269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27270. EXPECT_GE(s.proxy_hits(), 1);
  27271. EXPECT_EQ(0, s.target_hits());
  27272. }
  27273. TEST(NoProxyTest, IPv4CidrMatch) {
  27274. ProxyAndTargetServers s;
  27275. Client cli("127.0.0.1", s.target_port());
  27276. cli.set_proxy("127.0.0.1", s.proxy_port());
  27277. cli.set_no_proxy({"127.0.0.0/8"});
  27278. auto res = cli.Get("/");
  27279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27280. EXPECT_EQ(0, s.proxy_hits());
  27281. EXPECT_EQ(1, s.target_hits());
  27282. }
  27283. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27284. ProxyAndTargetServers s;
  27285. Client cli("127.0.0.1", s.target_port());
  27286. cli.set_proxy("127.0.0.1", s.proxy_port());
  27287. cli.set_no_proxy({"10.0.0.0/8"});
  27288. auto res = cli.Get("/");
  27289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27290. EXPECT_GE(s.proxy_hits(), 1);
  27291. EXPECT_EQ(0, s.target_hits());
  27292. }
  27293. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27294. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27295. // IPv4 target matches.
  27296. ProxyAndTargetServers s;
  27297. Client cli("127.0.0.1", s.target_port());
  27298. cli.set_proxy("127.0.0.1", s.proxy_port());
  27299. cli.set_no_proxy({"0.0.0.0/0"});
  27300. auto res = cli.Get("/");
  27301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27302. EXPECT_EQ(0, s.proxy_hits());
  27303. EXPECT_EQ(1, s.target_hits());
  27304. }
  27305. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27306. ProxyAndTargetServers s;
  27307. Client cli("127.0.0.1", s.target_port());
  27308. cli.set_proxy("127.0.0.1", s.proxy_port());
  27309. cli.set_no_proxy({"127.0.0.1"});
  27310. auto res = cli.Get("/");
  27311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27312. EXPECT_EQ(0, s.proxy_hits());
  27313. EXPECT_EQ(1, s.target_hits());
  27314. }
  27315. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27316. ProxyAndTargetServers s;
  27317. Client cli("127.0.0.1", s.target_port());
  27318. cli.set_proxy("127.0.0.1", s.proxy_port());
  27319. cli.set_no_proxy({"127.0.0.0/33"});
  27320. auto res = cli.Get("/");
  27321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27322. EXPECT_GE(s.proxy_hits(), 1);
  27323. EXPECT_EQ(0, s.target_hits());
  27324. }
  27325. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27326. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27327. ProxyAndTargetServers s;
  27328. Client cli("127.0.0.1", s.target_port());
  27329. cli.set_proxy("127.0.0.1", s.proxy_port());
  27330. cli.set_no_proxy({"127.0.0.1/"});
  27331. auto res = cli.Get("/");
  27332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27333. EXPECT_GE(s.proxy_hits(), 1);
  27334. EXPECT_EQ(0, s.target_hits());
  27335. }
  27336. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27337. ProxyAndTargetServers s;
  27338. auto cli = make_client("internal.corp", s);
  27339. cli->set_proxy_basic_auth("u", "p");
  27340. cli->set_no_proxy({"internal.corp"});
  27341. auto res = cli->Get("/");
  27342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27343. EXPECT_EQ(1, s.target_hits());
  27344. EXPECT_EQ(0, s.proxy_hits());
  27345. EXPECT_FALSE(s.last_had_proxy_authz())
  27346. << "Proxy-Authorization must not be sent direct to the target";
  27347. }
  27348. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27349. ProxyAndTargetServers s;
  27350. auto cli = make_client("public.example", s);
  27351. cli->set_proxy_basic_auth("u", "p");
  27352. cli->set_no_proxy({"internal.corp"}); // does not match
  27353. auto res = cli->Get("/");
  27354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27355. EXPECT_GE(s.proxy_hits(), 1);
  27356. EXPECT_TRUE(s.last_had_proxy_authz());
  27357. }
  27358. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27359. std::atomic<int> hits{0};
  27360. std::atomic<int> hits_with_authz{0};
  27361. no_proxy_test::ScopedServer proxy_mock;
  27362. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27363. hits++;
  27364. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27365. if (req.target.find("/redir") != std::string::npos) {
  27366. res.set_redirect("http://other.example/landed");
  27367. } else {
  27368. res.set_content("via-proxy", "text/plain");
  27369. }
  27370. });
  27371. proxy_mock.listen();
  27372. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27373. hits = 0;
  27374. hits_with_authz = 0;
  27375. Client cli("public.example", 80);
  27376. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27377. cli.set_proxy_basic_auth(c.first, c.second);
  27378. cli.set_follow_location(true);
  27379. // The redirect to another host goes through the proxy as well
  27380. auto res = cli.Get("/redir");
  27381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27382. EXPECT_EQ(2, hits.load());
  27383. EXPECT_EQ(2, hits_with_authz.load());
  27384. }
  27385. }
  27386. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27387. ProxyAndTargetServers s;
  27388. auto cli = make_client("anything.test", s);
  27389. auto res = cli->Get("/");
  27390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27391. EXPECT_GE(s.proxy_hits(), 1);
  27392. EXPECT_EQ(0, s.target_hits());
  27393. }
  27394. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27395. ProxyAndTargetServers s;
  27396. auto cli = make_client("example.com", s);
  27397. cli->set_no_proxy({"example.com:8080"});
  27398. auto res = cli->Get("/");
  27399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27400. EXPECT_GE(s.proxy_hits(), 1);
  27401. EXPECT_EQ(0, s.target_hits());
  27402. }
  27403. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27404. ProxyAndTargetServers s;
  27405. auto cli = make_client("anything.test", s);
  27406. cli->set_no_proxy({"", " ", "\t"});
  27407. auto res = cli->Get("/");
  27408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27409. EXPECT_GE(s.proxy_hits(), 1);
  27410. EXPECT_EQ(0, s.target_hits());
  27411. }
  27412. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27413. // An entry with leading/trailing whitespace must still match — env-style
  27414. // values are commonly pasted with stray spaces and an implementation
  27415. // that feeds the raw token directly to inet_pton would fail to match
  27416. // valid CIDRs because of the spaces.
  27417. ProxyAndTargetServers s;
  27418. Client cli("127.0.0.1", s.target_port());
  27419. cli.set_proxy("127.0.0.1", s.proxy_port());
  27420. cli.set_no_proxy({" 127.0.0.0/8 "});
  27421. auto res = cli.Get("/");
  27422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27423. EXPECT_EQ(0, s.proxy_hits());
  27424. EXPECT_EQ(1, s.target_hits());
  27425. }
  27426. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27427. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27428. // go direct and must NOT carry Proxy-Authorization.
  27429. std::atomic<int> proxy_hits{0};
  27430. std::atomic<int> target_hits{0};
  27431. std::atomic<bool> target_saw_authz{false};
  27432. no_proxy_test::ScopedServer proxy_mock, target;
  27433. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27434. proxy_hits++;
  27435. res.status = 302;
  27436. res.set_header("Location", "http://127.0.0.1:" +
  27437. std::to_string(target.port()) + "/landed");
  27438. });
  27439. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27440. target_hits++;
  27441. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27442. res.set_content("direct", "text/plain");
  27443. });
  27444. proxy_mock.listen();
  27445. target.listen();
  27446. Client cli("public.example", target.port());
  27447. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27448. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27449. cli.set_proxy_basic_auth("u", "p");
  27450. cli.set_no_proxy({"127.0.0.1"});
  27451. cli.set_follow_location(true);
  27452. auto res = cli.Get("/redir");
  27453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27454. EXPECT_GE(proxy_hits.load(), 1);
  27455. EXPECT_GE(target_hits.load(), 1);
  27456. EXPECT_FALSE(target_saw_authz.load());
  27457. }
  27458. #ifdef CPPHTTPLIB_SSL_ENABLED
  27459. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27460. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27461. // proxy creds would be sent to the (possibly hostile) origin.
  27462. std::atomic<int> target_hits{0};
  27463. std::atomic<bool> target_saw_proxy_authz{false};
  27464. no_proxy_test::ScopedServer target;
  27465. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27466. target_hits++;
  27467. if (req.has_header("Proxy-Authorization")) {
  27468. target_saw_proxy_authz = true;
  27469. }
  27470. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27471. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27472. "nonce=\"abc\", algorithm=MD5");
  27473. });
  27474. target.listen();
  27475. // The proxy address is set to the target's port: the bypass MUST kick in;
  27476. // if it doesn't, the test still routes "via proxy" to the same server and
  27477. // the Proxy-Authorization assertion below catches the leak.
  27478. Client cli("evil.example", target.port());
  27479. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27480. cli.set_proxy("127.0.0.1", target.port());
  27481. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27482. cli.set_no_proxy({"evil.example"});
  27483. auto res = cli.Get("/x");
  27484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27485. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27486. EXPECT_EQ(1, target_hits.load());
  27487. EXPECT_FALSE(target_saw_proxy_authz.load());
  27488. }
  27489. #endif
  27490. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27491. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27492. std::atomic<int> proxy_hits{0};
  27493. std::atomic<int> bypass_hits{0};
  27494. std::atomic<bool> proxy_saw_c_url{false};
  27495. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  27496. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27497. proxy_hits++;
  27498. if (req.path.find("/start") != std::string::npos) {
  27499. res.status = 302;
  27500. res.set_header("Location", "http://127.0.0.1:" +
  27501. std::to_string(bypass_server.port()) +
  27502. "/middle");
  27503. return;
  27504. }
  27505. if (req.path.find("/end") != std::string::npos) {
  27506. proxy_saw_c_url = true;
  27507. res.set_content("c-via-proxy", "text/plain");
  27508. return;
  27509. }
  27510. res.set_content("unexpected", "text/plain");
  27511. });
  27512. // public.example's "advertised" port is arbitrary (the request never lands
  27513. // there — it goes through the proxy), but use a dynamic value to stay
  27514. // friendly with sharded parallel runs.
  27515. int public_port = bypass_server.port();
  27516. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  27517. bypass_hits++;
  27518. res.status = 302;
  27519. res.set_header("Location", "http://public.example:" +
  27520. std::to_string(public_port) + "/end");
  27521. });
  27522. proxy_mock.listen();
  27523. bypass_server.listen();
  27524. Client cli("public.example", public_port);
  27525. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27526. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27527. cli.set_no_proxy({"127.0.0.1"});
  27528. cli.set_follow_location(true);
  27529. auto res = cli.Get("/start");
  27530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27531. EXPECT_EQ(StatusCode::OK_200, res->status);
  27532. EXPECT_EQ("c-via-proxy", res->body);
  27533. EXPECT_GE(proxy_hits.load(), 2);
  27534. EXPECT_GE(bypass_hits.load(), 1);
  27535. EXPECT_TRUE(proxy_saw_c_url.load());
  27536. }
  27537. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27538. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27539. // request reconnects to the correct endpoint.
  27540. std::atomic<int> proxy_hits{0};
  27541. std::atomic<int> target_hits{0};
  27542. no_proxy_test::ScopedServer proxy_mock, target;
  27543. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27544. proxy_hits++;
  27545. res.set_content("via-proxy", "text/plain");
  27546. });
  27547. target.svr().Get(".*", [&](const Request &, Response &res) {
  27548. target_hits++;
  27549. res.set_content("direct", "text/plain");
  27550. });
  27551. proxy_mock.listen();
  27552. target.listen();
  27553. Client cli("public.example", target.port());
  27554. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27555. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27556. cli.set_keep_alive(true);
  27557. auto res1 = cli.Get("/a");
  27558. ASSERT_TRUE(res1);
  27559. EXPECT_EQ("via-proxy", res1->body);
  27560. EXPECT_EQ(1, proxy_hits.load());
  27561. EXPECT_EQ(0, target_hits.load());
  27562. cli.set_no_proxy({"public.example"});
  27563. auto res2 = cli.Get("/b");
  27564. ASSERT_TRUE(res2);
  27565. EXPECT_EQ("direct", res2->body);
  27566. EXPECT_EQ(1, proxy_hits.load());
  27567. EXPECT_EQ(1, target_hits.load());
  27568. }
  27569. // Forward declarations (see the base64_encode note).
  27570. namespace httplib {
  27571. namespace detail {
  27572. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27573. int shutdown_socket(socket_t sock) noexcept;
  27574. } // namespace detail
  27575. } // namespace httplib
  27576. namespace proxy_tunnel_test {
  27577. const char *const kTunnelEstablished =
  27578. "HTTP/1.1 200 Connection established\r\n\r\n";
  27579. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27580. using ConnectReply = std::function<std::string(const std::string &head)>;
  27581. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27582. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27583. class ScopedConnectProxy {
  27584. public:
  27585. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27586. : forward_port_(forward_port), reply_(std::move(reply)) {
  27587. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27588. if (listen_sock_ == INVALID_SOCKET) { return; }
  27589. auto a = loopback(0);
  27590. auto addr = reinterpret_cast<sockaddr *>(&a);
  27591. socklen_t alen = sizeof(a);
  27592. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27593. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27594. ::listen(listen_sock_, 4) != 0) {
  27595. return;
  27596. }
  27597. port_ = ntohs(a.sin_port);
  27598. th_ = std::thread([this] { run(); });
  27599. }
  27600. ~ScopedConnectProxy() {
  27601. if (th_.joinable()) {
  27602. stop_ = true;
  27603. auto wake = connect_to(port_);
  27604. th_.join();
  27605. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  27606. }
  27607. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  27608. }
  27609. int port() const { return port_; }
  27610. int connect_hits() const { return connect_hits_.load(); }
  27611. // Head of the last CONNECT request, as the proxy saw it on the wire.
  27612. std::string connect_request() const {
  27613. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27614. return connect_request_;
  27615. }
  27616. private:
  27617. static sockaddr_in loopback(int port) {
  27618. sockaddr_in a{};
  27619. a.sin_family = AF_INET;
  27620. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  27621. a.sin_port = htons(static_cast<unsigned short>(port));
  27622. return a;
  27623. }
  27624. static socket_t connect_to(int port) {
  27625. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  27626. if (sock == INVALID_SOCKET) { return sock; }
  27627. auto a = loopback(port);
  27628. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  27629. detail::close_socket(sock);
  27630. return INVALID_SOCKET;
  27631. }
  27632. return sock;
  27633. }
  27634. static bool send_all(socket_t sock, const char *data, size_t size) {
  27635. while (size > 0) {
  27636. auto n = detail::send_socket(sock, data, size, 0);
  27637. if (n <= 0) { return false; }
  27638. data += n;
  27639. size -= static_cast<size_t>(n);
  27640. }
  27641. return true;
  27642. }
  27643. void run() {
  27644. for (;;) {
  27645. auto client = ::accept(listen_sock_, nullptr, nullptr);
  27646. if (stop_) {
  27647. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  27648. return;
  27649. }
  27650. if (client == INVALID_SOCKET) { continue; }
  27651. serve(client);
  27652. detail::close_socket(client);
  27653. }
  27654. }
  27655. void serve(socket_t client) {
  27656. std::string head;
  27657. char buf[2048];
  27658. while (head.find("\r\n\r\n") == std::string::npos) {
  27659. if (detail::select_read(client, 5, 0) <= 0) { return; }
  27660. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  27661. if (n <= 0) { return; }
  27662. head.append(buf, static_cast<size_t>(n));
  27663. }
  27664. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  27665. connect_hits_++;
  27666. {
  27667. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27668. connect_request_ = head;
  27669. }
  27670. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  27671. if (!send_all(client, res.data(), res.size()) ||
  27672. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  27673. return;
  27674. }
  27675. auto origin = connect_to(forward_port_);
  27676. if (origin == INVALID_SOCKET) { return; }
  27677. // When either side stops, shut both down so the other pump returns too.
  27678. auto pump = [&](socket_t from, socket_t to) {
  27679. char b[8192];
  27680. for (;;) {
  27681. auto n = detail::read_socket(from, b, sizeof(b), 0);
  27682. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  27683. }
  27684. detail::shutdown_socket(client);
  27685. detail::shutdown_socket(origin);
  27686. };
  27687. std::thread up([&] { pump(client, origin); });
  27688. pump(origin, client);
  27689. up.join();
  27690. detail::close_socket(origin);
  27691. }
  27692. int forward_port_;
  27693. ConnectReply reply_;
  27694. socket_t listen_sock_ = INVALID_SOCKET;
  27695. int port_ = 0;
  27696. std::thread th_;
  27697. std::atomic<bool> stop_{false};
  27698. std::atomic<int> connect_hits_{0};
  27699. mutable std::mutex connect_request_mutex_;
  27700. std::string connect_request_;
  27701. };
  27702. } // namespace proxy_tunnel_test
  27703. #ifdef CPPHTTPLIB_SSL_ENABLED
  27704. namespace proxy_tunnel_test {
  27705. // SSLServer counterpart to no_proxy_test::ScopedServer.
  27706. class ScopedSSLServer {
  27707. public:
  27708. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  27709. port_ = svr_.bind_to_any_port("127.0.0.1");
  27710. }
  27711. ~ScopedSSLServer() {
  27712. svr_.stop();
  27713. if (th_.joinable()) { th_.join(); }
  27714. }
  27715. SSLServer &svr() { return svr_; }
  27716. int port() const { return port_; }
  27717. void listen() {
  27718. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27719. svr_.wait_until_ready();
  27720. }
  27721. private:
  27722. SSLServer svr_;
  27723. std::thread th_;
  27724. int port_ = 0;
  27725. };
  27726. // Sends one request through the CONNECT proxy to the TLS origin with a
  27727. // credential configured for each hop, and checks that each credential reaches
  27728. // only the hop it was configured for: the proxy's on the CONNECT request, the
  27729. // origin's (every header in origin_headers) on the tunnelled request.
  27730. void CredentialsStayWithTheirHop(
  27731. const std::function<void(SSLClient &)> &set_credentials,
  27732. const std::string &scheme,
  27733. const std::vector<std::string> &origin_headers = {"Authorization"},
  27734. bool stream = false) {
  27735. std::atomic<int> origin_hits{0};
  27736. std::atomic<bool> origin_saw_proxy_authz{false};
  27737. std::atomic<bool> origin_saw_headers{false};
  27738. ScopedSSLServer origin;
  27739. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27740. origin_hits++;
  27741. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  27742. origin_saw_headers =
  27743. std::all_of(origin_headers.begin(), origin_headers.end(),
  27744. [&](const std::string &h) { return req.has_header(h); });
  27745. res.set_content("ok", "text/plain");
  27746. });
  27747. origin.listen();
  27748. ScopedConnectProxy proxy(origin.port());
  27749. ASSERT_NE(0, proxy.port());
  27750. // Pinned to 127.0.0.1 for the same reason as the test below.
  27751. SSLClient cli("127.0.0.1", origin.port());
  27752. cli.enable_server_certificate_verification(false);
  27753. cli.set_proxy("127.0.0.1", proxy.port());
  27754. set_credentials(cli);
  27755. if (stream) {
  27756. auto handle = cli.open_stream("GET", "/x");
  27757. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27758. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27759. } else {
  27760. auto res = cli.Get("/x");
  27761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27762. EXPECT_EQ(StatusCode::OK_200, res->status);
  27763. }
  27764. EXPECT_EQ(1, origin_hits.load());
  27765. EXPECT_EQ(1, proxy.connect_hits());
  27766. EXPECT_TRUE(origin_saw_headers.load());
  27767. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27768. << "Proxy-Authorization must not be sent inside the tunnel";
  27769. auto connect_req = proxy.connect_request();
  27770. EXPECT_NE(std::string::npos,
  27771. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27772. for (const auto &h : origin_headers) {
  27773. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27774. << h << " must not be sent to the proxy on CONNECT";
  27775. }
  27776. }
  27777. } // namespace proxy_tunnel_test
  27778. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27779. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27780. [](SSLClient &cli) {
  27781. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27782. cli.set_basic_auth("origin-user", "origin-pass");
  27783. },
  27784. "Basic");
  27785. }
  27786. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27787. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27788. [](SSLClient &cli) {
  27789. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27790. cli.set_basic_auth("origin-user", "origin-pass");
  27791. },
  27792. "Basic", {"Authorization"}, true);
  27793. }
  27794. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27795. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27796. [](SSLClient &cli) {
  27797. cli.set_proxy_bearer_token_auth("proxy-token");
  27798. cli.set_bearer_token_auth("origin-token");
  27799. },
  27800. "Bearer");
  27801. }
  27802. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27803. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27804. [](SSLClient &cli) {
  27805. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27806. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27807. {"Cookie", "sid=origin-session"},
  27808. {"X-Api-Key", "origin-key"}});
  27809. },
  27810. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27811. }
  27812. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27813. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27814. // retry; otherwise proxy creds would be sent to the origin.
  27815. std::atomic<int> origin_hits{0};
  27816. std::atomic<bool> origin_saw_proxy_authz{false};
  27817. proxy_tunnel_test::ScopedSSLServer origin;
  27818. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27819. origin_hits++;
  27820. if (req.has_header("Proxy-Authorization")) {
  27821. origin_saw_proxy_authz = true;
  27822. }
  27823. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27824. res.set_header("Proxy-Authenticate",
  27825. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27826. "algorithm=MD5");
  27827. });
  27828. origin.listen();
  27829. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27830. ASSERT_NE(0, proxy.port());
  27831. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27832. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27833. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27834. // and answer with its own status, making this test flaky.
  27835. SSLClient cli("127.0.0.1", origin.port());
  27836. cli.enable_server_certificate_verification(false);
  27837. cli.set_proxy("127.0.0.1", proxy.port());
  27838. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27839. auto res = cli.Get("/x");
  27840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27841. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27842. EXPECT_EQ(1, origin_hits.load());
  27843. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27844. EXPECT_EQ(1, proxy.connect_hits());
  27845. }
  27846. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27847. std::string origin_sni;
  27848. std::string origin_host;
  27849. proxy_tunnel_test::ScopedSSLServer origin;
  27850. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27851. origin_sni = req.sni();
  27852. origin_host = req.get_header_value("Host");
  27853. res.set_content("ok", "text/plain");
  27854. });
  27855. origin.listen();
  27856. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27857. ASSERT_NE(0, proxy.port());
  27858. SSLClient cli("origin.example", origin.port());
  27859. cli.enable_server_certificate_verification(false);
  27860. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27861. cli.set_proxy("127.0.0.1", proxy.port());
  27862. auto res = cli.Get("/x");
  27863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27864. EXPECT_EQ(StatusCode::OK_200, res->status);
  27865. auto port = std::to_string(origin.port());
  27866. auto target = "127.0.0.1:" + port;
  27867. auto connect_req = proxy.connect_request();
  27868. EXPECT_EQ(1, proxy.connect_hits());
  27869. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27870. EXPECT_NE(std::string::npos,
  27871. connect_req.find("\r\nHost: " + target + "\r\n"));
  27872. EXPECT_EQ("origin.example", origin_sni);
  27873. EXPECT_EQ("origin.example:" + port, origin_host);
  27874. }
  27875. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27876. proxy_tunnel_test::ScopedSSLServer origin;
  27877. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27878. res.set_content("ok", "text/plain");
  27879. });
  27880. origin.listen();
  27881. proxy_tunnel_test::ScopedConnectProxy proxy(
  27882. origin.port(), [](const std::string &head) -> std::string {
  27883. if (head.find(
  27884. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27885. std::string::npos) {
  27886. return proxy_tunnel_test::kTunnelEstablished;
  27887. }
  27888. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27889. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27890. "nonce=\"abc\", algorithm=MD5\r\n"
  27891. "Content-Length: 0\r\n\r\n";
  27892. });
  27893. ASSERT_NE(0, proxy.port());
  27894. SSLClient cli("origin.example", origin.port());
  27895. cli.enable_server_certificate_verification(false);
  27896. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27897. cli.set_proxy("127.0.0.1", proxy.port());
  27898. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27899. auto res = cli.Get("/x");
  27900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27901. EXPECT_EQ(StatusCode::OK_200, res->status);
  27902. // The retried CONNECT is the one the proxy saw last.
  27903. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27904. auto connect_req = proxy.connect_request();
  27905. EXPECT_EQ(2, proxy.connect_hits());
  27906. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27907. EXPECT_NE(std::string::npos,
  27908. connect_req.find("\r\nHost: " + target + "\r\n"));
  27909. }
  27910. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27911. proxy_tunnel_test::ScopedSSLServer origin;
  27912. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27913. res.set_content("ok", "text/plain");
  27914. });
  27915. origin.listen();
  27916. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27917. ASSERT_NE(0, proxy.port());
  27918. SSLClient cli("origin.example", origin.port());
  27919. cli.enable_server_certificate_verification(false);
  27920. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27921. cli.set_proxy("127.0.0.1", proxy.port());
  27922. auto res = cli.Get("/x");
  27923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27924. EXPECT_EQ(StatusCode::OK_200, res->status);
  27925. auto target = "origin.example:" + std::to_string(origin.port());
  27926. auto connect_req = proxy.connect_request();
  27927. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27928. EXPECT_NE(std::string::npos,
  27929. connect_req.find("\r\nHost: " + target + "\r\n"));
  27930. }
  27931. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27932. proxy_tunnel_test::ScopedSSLServer origin;
  27933. auto port = std::to_string(origin.port());
  27934. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27935. res.set_redirect("https://next.example:" + port + "/y");
  27936. });
  27937. origin.svr().Get("/y", [](const Request &, Response &res) {
  27938. res.set_content("ok", "text/plain");
  27939. });
  27940. origin.listen();
  27941. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27942. ASSERT_NE(0, proxy.port());
  27943. SSLClient cli("origin.example", origin.port());
  27944. cli.enable_server_certificate_verification(false);
  27945. cli.set_tunnel_hostname_addr_map(
  27946. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27947. cli.set_proxy("127.0.0.1", proxy.port());
  27948. cli.set_follow_location(true);
  27949. auto res = cli.Get("/x");
  27950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27951. EXPECT_EQ("ok", res->body);
  27952. // The last CONNECT is the redirect client's.
  27953. ASSERT_EQ(2, proxy.connect_hits());
  27954. auto target = "127.0.0.1:" + port;
  27955. auto connect_req = proxy.connect_request();
  27956. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27957. EXPECT_NE(std::string::npos,
  27958. connect_req.find("\r\nHost: " + target + "\r\n"));
  27959. }
  27960. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  27961. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  27962. std::atomic<int> origin_hits{0};
  27963. proxy_tunnel_test::ScopedSSLServer origin;
  27964. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27965. origin_hits++;
  27966. res.set_content("ok", "text/plain");
  27967. });
  27968. origin.listen();
  27969. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27970. ASSERT_NE(0, proxy.port());
  27971. SSLClient cli("127.0.0.1", origin.port());
  27972. cli.enable_server_certificate_verification(false);
  27973. cli.set_proxy("127.0.0.1", proxy.port());
  27974. cli.set_keep_alive(true);
  27975. cli.set_session_verifier(
  27976. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  27977. auto res = cli.Get("/x");
  27978. EXPECT_FALSE(res);
  27979. ASSERT_FALSE(cli.is_socket_open());
  27980. res = cli.Get("/x");
  27981. EXPECT_FALSE(res);
  27982. EXPECT_EQ(2, proxy.connect_hits());
  27983. auto handle = cli.open_stream("GET", "/x");
  27984. EXPECT_FALSE(handle.is_valid());
  27985. EXPECT_EQ(3, proxy.connect_hits());
  27986. EXPECT_EQ(0, origin_hits.load());
  27987. }
  27988. #endif
  27989. namespace proxy_tunnel_test {
  27990. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  27991. // anything else gets a 407 with `challenge`.
  27992. ConnectReply require_proxy_auth(const std::string &expected,
  27993. const std::string &challenge) {
  27994. return [=](const std::string &head) -> std::string {
  27995. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  27996. std::string::npos) {
  27997. return kTunnelEstablished;
  27998. }
  27999. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28000. "Proxy-Authenticate: " +
  28001. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28002. };
  28003. }
  28004. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28005. // request, then echoes.
  28006. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28007. ws.send(
  28008. "authorization:" + req.get_header_value("Authorization") +
  28009. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28010. std::string msg;
  28011. while (ws.read(msg)) {
  28012. ws.send(msg);
  28013. }
  28014. }
  28015. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28016. class ScopedWebSocketOrigin {
  28017. public:
  28018. ScopedWebSocketOrigin() {
  28019. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28020. server_.listen();
  28021. }
  28022. int port() const { return server_.port(); }
  28023. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28024. std::string url() const {
  28025. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28026. }
  28027. private:
  28028. no_proxy_test::ScopedServer server_;
  28029. };
  28030. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28031. // passed as a constructor header, and checks that each reaches only its hop.
  28032. void WebSocketCredentialsStayWithTheirHop(
  28033. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28034. const std::string &proxy_authz, const std::string &origin_authz) {
  28035. ScopedWebSocketOrigin origin;
  28036. ScopedConnectProxy proxy(
  28037. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28038. ASSERT_NE(0, proxy.port());
  28039. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28040. client.set_proxy("127.0.0.1", proxy.port());
  28041. set_proxy_credentials(client);
  28042. auto res = client.connect();
  28043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28044. std::string msg;
  28045. ASSERT_TRUE(client.read(msg));
  28046. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28047. client.close();
  28048. EXPECT_EQ(1, proxy.connect_hits());
  28049. EXPECT_EQ(std::string::npos,
  28050. proxy.connect_request().find("\r\nAuthorization: "))
  28051. << "origin credentials must not be sent to the proxy";
  28052. }
  28053. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28054. void WebSocketSetterCredentialsStayWithTheirHop(
  28055. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28056. const std::string &proxy_authz, const std::string &origin_authz) {
  28057. ScopedWebSocketOrigin origin;
  28058. ScopedConnectProxy proxy(
  28059. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28060. ASSERT_NE(0, proxy.port());
  28061. ws::WebSocketClient client(origin.url());
  28062. client.set_proxy("127.0.0.1", proxy.port());
  28063. set_credentials(client);
  28064. auto res = client.connect();
  28065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28066. std::string msg;
  28067. ASSERT_TRUE(client.read(msg));
  28068. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28069. client.close();
  28070. EXPECT_EQ(1, proxy.connect_hits());
  28071. EXPECT_EQ(std::string::npos,
  28072. proxy.connect_request().find("\r\nAuthorization: "))
  28073. << "origin credentials must not be sent to the proxy";
  28074. }
  28075. } // namespace proxy_tunnel_test
  28076. namespace {
  28077. // Connects `client` and returns the Authorization header its upgrade
  28078. // request carried, or "<failed>" when the connection could not be opened.
  28079. std::string websocket_authorization(ws::WebSocketClient &client) {
  28080. if (!client.connect()) { return "<failed>"; }
  28081. std::string msg;
  28082. if (!client.read(msg)) { return "<failed>"; }
  28083. client.close();
  28084. auto prefix = std::string("authorization:");
  28085. auto end = msg.find("|proxy-authorization:");
  28086. return msg.substr(prefix.size(), end - prefix.size());
  28087. }
  28088. } // namespace
  28089. TEST(WebSocketClientAuthTest, BasicAuth) {
  28090. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28091. ws::WebSocketClient client(origin.url());
  28092. client.set_basic_auth("user", "pass");
  28093. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28094. websocket_authorization(client));
  28095. }
  28096. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28097. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28098. ws::WebSocketClient client(origin.url());
  28099. client.set_basic_auth("user", "");
  28100. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28101. websocket_authorization(client));
  28102. }
  28103. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28104. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28105. ws::WebSocketClient client(origin.url());
  28106. client.set_bearer_token_auth("token123");
  28107. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28108. }
  28109. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28110. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28111. ws::WebSocketClient client(origin.url());
  28112. client.set_bearer_token_auth("token123");
  28113. client.set_basic_auth("user", "pass");
  28114. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28115. websocket_authorization(client));
  28116. }
  28117. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28118. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28119. ws::WebSocketClient client(origin.url(),
  28120. {{"Authorization", "Bearer from-header"}});
  28121. client.set_bearer_token_auth("from-setter");
  28122. client.set_basic_auth("user", "pass");
  28123. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28124. }
  28125. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28126. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28127. ws::WebSocketClient client(origin.url());
  28128. EXPECT_EQ("", websocket_authorization(client));
  28129. client.set_bearer_token_auth("first");
  28130. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28131. client.set_bearer_token_auth("second");
  28132. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28133. client.set_bearer_token_auth("");
  28134. EXPECT_EQ("", websocket_authorization(client));
  28135. }
  28136. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28137. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28138. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28139. ASSERT_NE(0, proxy.port());
  28140. ws::WebSocketClient client(origin.url());
  28141. client.set_proxy("127.0.0.1", proxy.port());
  28142. auto res = client.connect();
  28143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28144. std::string msg;
  28145. ASSERT_TRUE(client.read(msg));
  28146. ASSERT_TRUE(client.send("hello"));
  28147. ASSERT_TRUE(client.read(msg));
  28148. EXPECT_EQ("hello", msg);
  28149. client.close();
  28150. EXPECT_EQ(1, proxy.connect_hits());
  28151. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28152. auto connect_req = proxy.connect_request();
  28153. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28154. EXPECT_NE(std::string::npos,
  28155. connect_req.find("\r\nHost: " + target + "\r\n"));
  28156. }
  28157. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28158. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28159. [](ws::WebSocketClient &cli) {
  28160. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28161. },
  28162. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28163. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28164. }
  28165. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28166. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28167. [](ws::WebSocketClient &cli) {
  28168. cli.set_proxy_bearer_token_auth("proxy-token");
  28169. },
  28170. "Bearer proxy-token", "Bearer origin-token");
  28171. }
  28172. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28173. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28174. [](ws::WebSocketClient &cli) {
  28175. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28176. cli.set_basic_auth("origin-user", "origin-pass");
  28177. },
  28178. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28179. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28180. }
  28181. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28182. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28183. [](ws::WebSocketClient &cli) {
  28184. cli.set_proxy_bearer_token_auth("proxy-token");
  28185. cli.set_bearer_token_auth("origin-token");
  28186. },
  28187. "Bearer proxy-token", "Bearer origin-token");
  28188. }
  28189. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28190. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28191. proxy_tunnel_test::ScopedConnectProxy proxy(
  28192. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28193. "Basic " + detail::base64_encode("proxy-user:"),
  28194. "Basic realm=\"proxy\""));
  28195. ASSERT_NE(0, proxy.port());
  28196. ws::WebSocketClient client(origin.url());
  28197. client.set_proxy("127.0.0.1", proxy.port());
  28198. client.set_proxy_basic_auth("proxy-user", "");
  28199. auto res = client.connect();
  28200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28201. client.close();
  28202. EXPECT_EQ(1, proxy.connect_hits());
  28203. }
  28204. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28205. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28206. proxy_tunnel_test::ScopedConnectProxy proxy(
  28207. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28208. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28209. ASSERT_NE(0, proxy.port());
  28210. ws::WebSocketClient client(origin.url());
  28211. client.set_proxy("127.0.0.1", proxy.port());
  28212. auto res = client.connect();
  28213. EXPECT_FALSE(res);
  28214. EXPECT_EQ(Error::ProxyConnection, res.error());
  28215. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28216. EXPECT_EQ("Basic realm=\"proxy\"",
  28217. res.get_header_value("Proxy-Authenticate"));
  28218. EXPECT_FALSE(client.is_open());
  28219. }
  28220. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28221. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28222. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28223. ASSERT_NE(0, proxy.port());
  28224. ws::WebSocketClient client(origin.url());
  28225. client.set_proxy("127.0.0.1", proxy.port());
  28226. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28227. client.set_no_proxy({"127.0.0.1"});
  28228. auto res = client.connect();
  28229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28230. std::string msg;
  28231. ASSERT_TRUE(client.read(msg));
  28232. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28233. << "proxy credentials must not reach a bypassed origin";
  28234. client.close();
  28235. EXPECT_EQ(0, proxy.connect_hits());
  28236. }
  28237. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28238. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28239. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28240. ASSERT_NE(0, proxy.port());
  28241. ws::WebSocketClient client(origin.url());
  28242. client.set_proxy("127.0.0.1", proxy.port());
  28243. ASSERT_TRUE(client.connect());
  28244. ASSERT_TRUE(client.connect());
  28245. client.close();
  28246. EXPECT_EQ(2, proxy.connect_hits());
  28247. }
  28248. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28249. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28250. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28251. ASSERT_NE(0, proxy.port());
  28252. auto port = std::to_string(origin.port());
  28253. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28254. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28255. client.set_proxy("127.0.0.1", proxy.port());
  28256. auto res = client.connect();
  28257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28258. std::string msg;
  28259. ASSERT_TRUE(client.read(msg));
  28260. client.close();
  28261. EXPECT_EQ(1, proxy.connect_hits());
  28262. auto target = "127.0.0.1:" + port;
  28263. auto connect_req = proxy.connect_request();
  28264. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28265. EXPECT_NE(std::string::npos,
  28266. connect_req.find("\r\nHost: " + target + "\r\n"));
  28267. }
  28268. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28269. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28270. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28271. ASSERT_NE(0, proxy.port());
  28272. auto port = std::to_string(origin.port());
  28273. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28274. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28275. client.set_proxy("127.0.0.1", proxy.port());
  28276. auto res = client.connect();
  28277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28278. client.close();
  28279. auto target = "origin.example:" + port;
  28280. auto connect_req = proxy.connect_request();
  28281. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28282. EXPECT_NE(std::string::npos,
  28283. connect_req.find("\r\nHost: " + target + "\r\n"));
  28284. }
  28285. #ifdef CPPHTTPLIB_SSL_ENABLED
  28286. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28287. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28288. proxy_tunnel_test::ScopedConnectProxy proxy(
  28289. origin.port(), [](const std::string &head) -> std::string {
  28290. if (head.find(
  28291. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28292. std::string::npos) {
  28293. return proxy_tunnel_test::kTunnelEstablished;
  28294. }
  28295. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28296. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28297. "nonce=\"abc\", algorithm=MD5\r\n"
  28298. "Content-Length: 0\r\n\r\n";
  28299. });
  28300. ASSERT_NE(0, proxy.port());
  28301. ws::WebSocketClient client(origin.url());
  28302. client.set_proxy("127.0.0.1", proxy.port());
  28303. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28304. auto res = client.connect();
  28305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28306. std::string msg;
  28307. ASSERT_TRUE(client.read(msg));
  28308. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28309. client.close();
  28310. EXPECT_EQ(2, proxy.connect_hits());
  28311. }
  28312. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28313. proxy_tunnel_test::ScopedSSLServer origin;
  28314. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28315. origin.listen();
  28316. proxy_tunnel_test::ScopedConnectProxy proxy(
  28317. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28318. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28319. ASSERT_NE(0, proxy.port());
  28320. ws::WebSocketClient client(
  28321. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28322. client.enable_server_certificate_verification(false);
  28323. client.set_proxy("127.0.0.1", proxy.port());
  28324. client.set_proxy_bearer_token_auth("proxy-token");
  28325. auto res = client.connect();
  28326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28327. std::string msg;
  28328. ASSERT_TRUE(client.read(msg));
  28329. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28330. << "Proxy-Authorization must not be sent inside the tunnel";
  28331. client.close();
  28332. EXPECT_EQ(1, proxy.connect_hits());
  28333. }
  28334. #endif