test.cc 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546
  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, CloseEndsAReadOfEndlessFragments) {
  25780. #ifndef _WIN32
  25781. signal(SIGPIPE, SIG_IGN);
  25782. #endif
  25783. std::atomic<bool> read_ended{false};
  25784. std::atomic<bool> sending{true};
  25785. Server svr;
  25786. svr.set_websocket_ping_interval(0);
  25787. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25788. std::thread reader([&]() {
  25789. std::string msg;
  25790. while (ws.read(msg)) {}
  25791. read_ended = true;
  25792. });
  25793. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  25794. ws.close();
  25795. reader.join();
  25796. });
  25797. auto port = svr.bind_to_any_port("127.0.0.1");
  25798. std::thread t([&]() { svr.listen_after_bind(); });
  25799. auto se = detail::scope_exit([&] {
  25800. svr.stop();
  25801. t.join();
  25802. });
  25803. svr.wait_until_ready();
  25804. auto sock = connect_raw_websocket(port, "/ws");
  25805. ASSERT_NE(INVALID_SOCKET, sock);
  25806. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25807. // A Text message whose empty continuation frames never end
  25808. std::thread sender([&]() {
  25809. auto data = masked_frame(0x01, "");
  25810. while (sending) {
  25811. data += masked_frame(0x00, "");
  25812. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  25813. return;
  25814. }
  25815. data.clear();
  25816. }
  25817. });
  25818. for (int i = 0; i < 300 && !read_ended; i++) {
  25819. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25820. }
  25821. sending = false;
  25822. sender.join();
  25823. EXPECT_TRUE(read_ended);
  25824. }
  25825. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  25826. Server svr;
  25827. svr.set_websocket_ping_interval(-1);
  25828. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25829. std::string msg;
  25830. while (ws.read(msg)) {}
  25831. });
  25832. auto port = svr.bind_to_any_port("127.0.0.1");
  25833. std::thread t([&]() { svr.listen_after_bind(); });
  25834. auto se = detail::scope_exit([&] {
  25835. svr.stop();
  25836. t.join();
  25837. });
  25838. svr.wait_until_ready();
  25839. auto sock = connect_raw_websocket(port, "/ws");
  25840. ASSERT_NE(INVALID_SOCKET, sock);
  25841. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25842. // Nothing comes while the client stays quiet.
  25843. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  25844. char c;
  25845. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  25846. }
  25847. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  25848. // and that has to end a read() already waiting on the peer, on every platform.
  25849. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  25850. // The peer sends no pings, and its handler never calls read(), which is
  25851. // where pongs are written.
  25852. std::mutex mutex;
  25853. std::condition_variable cv;
  25854. auto release = false;
  25855. svr.set_websocket_ping_interval(0);
  25856. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  25857. std::unique_lock<std::mutex> lock(mutex);
  25858. cv.wait(lock, [&] { return release; });
  25859. });
  25860. auto port = svr.bind_to_any_port(HOST);
  25861. std::thread t([&]() { svr.listen_after_bind(); });
  25862. auto se = detail::scope_exit([&] {
  25863. {
  25864. std::lock_guard<std::mutex> lock(mutex);
  25865. release = true;
  25866. }
  25867. cv.notify_all();
  25868. svr.stop();
  25869. t.join();
  25870. });
  25871. svr.wait_until_ready();
  25872. ws::WebSocketClient client(std::string(scheme) +
  25873. "://localhost:" + std::to_string(port) + "/ws");
  25874. #ifdef CPPHTTPLIB_SSL_ENABLED
  25875. client.enable_server_certificate_verification(false);
  25876. #endif
  25877. // A ping a second, given up on after two go unanswered: about 3s
  25878. client.set_websocket_ping_interval(1);
  25879. client.set_websocket_max_missed_pongs(2);
  25880. // Well past that, so that a read the timeout ends instead stands out
  25881. client.set_read_timeout(10);
  25882. ASSERT_TRUE(client.connect());
  25883. auto start = std::chrono::steady_clock::now();
  25884. std::string msg;
  25885. EXPECT_EQ(ws::Fail, client.read(msg));
  25886. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  25887. std::chrono::steady_clock::now() - start)
  25888. .count(),
  25889. 6000);
  25890. EXPECT_FALSE(client.is_open());
  25891. }
  25892. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  25893. Server svr;
  25894. check_pong_timeout_ends_read(svr, "ws");
  25895. }
  25896. #ifdef CPPHTTPLIB_SSL_ENABLED
  25897. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  25898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25899. ASSERT_TRUE(svr.is_valid());
  25900. check_pong_timeout_ends_read(svr, "wss");
  25901. }
  25902. #endif
  25903. // listen() returns only after every handler has, so Server::stop() has to end
  25904. // a WebSocket handler's read() waiting on a client that stays connected and
  25905. // quiet, whether or not the handler bounded its reads, and the client's
  25906. // connection ends with it.
  25907. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  25908. bool bounded) {
  25909. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25910. if (bounded) { ws.set_read_timeout(0, 50000); }
  25911. std::string msg;
  25912. while (ws.read(msg) != ws::Fail) {}
  25913. });
  25914. auto port = svr.bind_to_any_port(HOST);
  25915. std::thread t([&]() { svr.listen_after_bind(); });
  25916. auto se = detail::scope_exit([&] {
  25917. if (t.joinable()) {
  25918. svr.stop();
  25919. t.join();
  25920. }
  25921. });
  25922. svr.wait_until_ready();
  25923. ws::WebSocketClient client(std::string(scheme) +
  25924. "://localhost:" + std::to_string(port) + "/ws");
  25925. #ifdef CPPHTTPLIB_SSL_ENABLED
  25926. client.enable_server_certificate_verification(false);
  25927. #endif
  25928. client.set_read_timeout(2);
  25929. ASSERT_TRUE(client.connect());
  25930. auto stopped = std::async(std::launch::async, [&] {
  25931. svr.stop();
  25932. t.join();
  25933. });
  25934. std::string msg;
  25935. EXPECT_EQ(ws::Fail, client.read(msg));
  25936. EXPECT_FALSE(client.is_open());
  25937. auto in_time =
  25938. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  25939. // A handler the stop did not reach ends when the client leaves
  25940. if (!in_time) { client.close(); }
  25941. stopped.wait();
  25942. EXPECT_TRUE(in_time);
  25943. }
  25944. TEST(WebSocketTest, StopEndsAWaitingRead) {
  25945. Server svr;
  25946. check_stop_ends_websocket_read(svr, "ws", false);
  25947. }
  25948. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  25949. Server svr;
  25950. check_stop_ends_websocket_read(svr, "ws", true);
  25951. }
  25952. #ifdef CPPHTTPLIB_SSL_ENABLED
  25953. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  25954. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25955. ASSERT_TRUE(svr.is_valid());
  25956. check_stop_ends_websocket_read(svr, "wss", false);
  25957. }
  25958. #endif
  25959. // The stop reaches the client as a Close with 1001 Going Away, not as a
  25960. // dropped connection, whether the handler waits for a message or for the rest
  25961. // of one: `sent` is what the client sends first.
  25962. static void check_stop_closes_with_going_away(const std::string &sent) {
  25963. Server svr;
  25964. svr.set_websocket_ping_interval(0);
  25965. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25966. std::string msg;
  25967. while (ws.read(msg)) {}
  25968. });
  25969. auto port = svr.bind_to_any_port("127.0.0.1");
  25970. std::thread t([&]() { svr.listen_after_bind(); });
  25971. auto se = detail::scope_exit([&] {
  25972. svr.stop();
  25973. t.join();
  25974. });
  25975. svr.wait_until_ready();
  25976. // Closed before the join above, which a handler the stop did not reach
  25977. // would otherwise hold up.
  25978. auto sock = connect_raw_websocket(port, "/ws");
  25979. ASSERT_NE(INVALID_SOCKET, sock);
  25980. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25981. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  25982. detail::send_socket(sock, sent.data(), sent.size(), 0));
  25983. // Let the handler take what was sent and wait for more
  25984. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25985. svr.stop();
  25986. // FIN + Close, its length, then the code: unmasked, from a server
  25987. std::string head;
  25988. char c;
  25989. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  25990. head += c;
  25991. }
  25992. const std::string reason = "server stopping";
  25993. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  25994. "\x03\xe9",
  25995. head);
  25996. }
  25997. TEST(WebSocketTest, StopClosesWithGoingAway) {
  25998. check_stop_closes_with_going_away("");
  25999. }
  26000. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26001. // A Text frame without FIN: the first fragment of a message
  26002. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26003. }
  26004. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26005. Server svr;
  26006. svr.set_websocket_ping_interval(0);
  26007. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26008. std::string msg;
  26009. while (ws.read(msg)) {}
  26010. });
  26011. auto port = svr.bind_to_any_port("127.0.0.1");
  26012. std::thread t([&]() { svr.listen_after_bind(); });
  26013. auto se = detail::scope_exit([&] {
  26014. svr.stop();
  26015. t.join();
  26016. });
  26017. svr.wait_until_ready();
  26018. // Each Close payload and the reply it should get: an echo when valid, 1002
  26019. // otherwise.
  26020. std::vector<std::pair<std::string, std::string>> cases = {
  26021. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26022. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26023. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26024. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26025. };
  26026. // Also between the fragments of a message.
  26027. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26028. for (const auto &c : cases) {
  26029. auto sock = connect_raw_websocket(port, "/ws");
  26030. ASSERT_NE(INVALID_SOCKET, sock);
  26031. auto frames = prefix + masked_frame(0x88, c.first);
  26032. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26033. std::string reply;
  26034. char buf[256];
  26035. while (reply.size() < 2 + c.second.size()) {
  26036. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26037. if (n <= 0) { break; }
  26038. reply.append(buf, static_cast<size_t>(n));
  26039. }
  26040. detail::close_socket(sock);
  26041. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26042. c.second,
  26043. reply);
  26044. }
  26045. }
  26046. }
  26047. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26048. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26049. protected:
  26050. void SetUp() override {
  26051. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26052. SERVER_PRIVATE_KEY_FILE);
  26053. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26054. std::string msg;
  26055. ws::ReadResult ret;
  26056. while ((ret = ws.read(msg))) {
  26057. if (ret == ws::Binary) {
  26058. ws.send(msg.data(), msg.size());
  26059. } else {
  26060. ws.send(msg);
  26061. }
  26062. }
  26063. });
  26064. port_ = server_->bind_to_any_port(HOST);
  26065. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26066. server_->wait_until_ready();
  26067. }
  26068. void TearDown() override {
  26069. server_->stop();
  26070. if (server_thread_.joinable()) { server_thread_.join(); }
  26071. }
  26072. std::unique_ptr<SSLServer> server_;
  26073. std::thread server_thread_;
  26074. int port_ = 0;
  26075. };
  26076. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26077. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26078. {
  26079. ws::WebSocketClient client(url);
  26080. client.enable_server_certificate_verification(false);
  26081. auto calls = 0;
  26082. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26083. calls++;
  26084. return false;
  26085. });
  26086. EXPECT_FALSE(client.connect());
  26087. EXPECT_GT(calls, 0);
  26088. }
  26089. {
  26090. ws::WebSocketClient client(url);
  26091. client.enable_server_certificate_verification(false);
  26092. client.set_session_verifier([](tls::session_t) {
  26093. return SSLVerifierResponse::CertificateRejected;
  26094. });
  26095. EXPECT_FALSE(client.connect());
  26096. }
  26097. {
  26098. ws::WebSocketClient client(url);
  26099. client.enable_server_certificate_verification(false);
  26100. client.set_session_verifier([](tls::session_t) {
  26101. return SSLVerifierResponse::CertificateAccepted;
  26102. });
  26103. EXPECT_TRUE(client.connect());
  26104. }
  26105. }
  26106. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26107. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26108. "/ws-echo");
  26109. client.enable_server_certificate_verification(false);
  26110. ASSERT_TRUE(client.connect());
  26111. ASSERT_TRUE(client.is_open());
  26112. ASSERT_TRUE(client.send("Hello WSS"));
  26113. std::string msg;
  26114. EXPECT_EQ(ws::Text, client.read(msg));
  26115. EXPECT_EQ("Hello WSS", msg);
  26116. client.close();
  26117. }
  26118. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26119. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26120. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26121. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26122. // client (without calling close() first) is the only path that runs
  26123. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26124. // bug exactly.
  26125. //
  26126. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26127. // when linked against an instrumented libssl; run under Valgrind to catch it
  26128. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26129. // suite (the freed session otherwise stalls on the close handshake) — this test
  26130. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26131. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26132. {
  26133. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26134. "/ws-echo");
  26135. client.enable_server_certificate_verification(false);
  26136. client.set_read_timeout(2, 0);
  26137. client.set_write_timeout(2, 0);
  26138. ASSERT_TRUE(client.connect());
  26139. ASSERT_TRUE(client.is_open());
  26140. ASSERT_TRUE(client.send("still open"));
  26141. // Intentionally do NOT call client.close(): leaving scope runs
  26142. // shutdown_and_close() with the WebSocket still open, which must send the
  26143. // close frame while the TLS session is still alive.
  26144. }
  26145. }
  26146. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26147. // shutdown_and_close() at the start of connect(), reproducing the same
  26148. // use-after-free within the test body rather than at scope exit. The second
  26149. // connect must succeed and echo, proving the close handshake ran over a live
  26150. // session. See the note above about memory-tool requirements.
  26151. TEST_F(WebSocketSSLIntegrationTest,
  26152. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26153. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26154. "/ws-echo");
  26155. client.enable_server_certificate_verification(false);
  26156. client.set_read_timeout(2, 0);
  26157. client.set_write_timeout(2, 0);
  26158. ASSERT_TRUE(client.connect());
  26159. ASSERT_TRUE(client.is_open());
  26160. ASSERT_TRUE(client.send("still open"));
  26161. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26162. // the still-open connection, which must not touch a freed TLS session.
  26163. ASSERT_TRUE(client.connect());
  26164. ASSERT_TRUE(client.is_open());
  26165. ASSERT_TRUE(client.send("after reconnect"));
  26166. std::string msg;
  26167. EXPECT_EQ(ws::Text, client.read(msg));
  26168. EXPECT_EQ("after reconnect", msg);
  26169. client.close();
  26170. }
  26171. #endif
  26172. #ifdef CPPHTTPLIB_SSL_ENABLED
  26173. class WebSocketSSLCATest : public ::testing::Test {
  26174. protected:
  26175. void SetUp() override {
  26176. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26177. SERVER_PRIVATE_KEY_FILE);
  26178. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26179. std::string msg;
  26180. while (ws.read(msg)) {
  26181. ws.send(msg);
  26182. }
  26183. });
  26184. port_ = server_->bind_to_any_port("127.0.0.1");
  26185. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26186. server_->wait_until_ready();
  26187. }
  26188. void TearDown() override {
  26189. server_->stop();
  26190. if (server_thread_.joinable()) { server_thread_.join(); }
  26191. }
  26192. std::string url() const {
  26193. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26194. }
  26195. std::unique_ptr<SSLServer> server_;
  26196. std::thread server_thread_;
  26197. int port_ = 0;
  26198. };
  26199. // A custom CA loaded as PEM verifies the server with full certificate
  26200. // verification enabled
  26201. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26202. ws::WebSocketClient client(url());
  26203. std::string cert;
  26204. read_file(SERVER_CERT2_FILE, cert);
  26205. client.load_ca_cert_store(cert.c_str(), cert.size());
  26206. ASSERT_TRUE(client.connect());
  26207. ASSERT_TRUE(client.send("hello"));
  26208. std::string msg;
  26209. EXPECT_EQ(ws::Text, client.read(msg));
  26210. EXPECT_EQ("hello", msg);
  26211. client.close();
  26212. }
  26213. // A custom CA that does not cover the server must fail verification (the
  26214. // custom CA is exclusive; system certs are not loaded alongside it)
  26215. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26216. ws::WebSocketClient client(url());
  26217. std::string cert;
  26218. read_file(CLIENT_CA_CERT_FILE, cert);
  26219. client.load_ca_cert_store(cert.c_str(), cert.size());
  26220. auto res = client.connect();
  26221. ASSERT_FALSE(res);
  26222. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26223. EXPECT_EQ(-1, res.status());
  26224. EXPECT_NE(0u, res.ssl_backend_error());
  26225. }
  26226. // The same CA as a file path rather than PEM in memory
  26227. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26228. ws::WebSocketClient client(url());
  26229. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26230. ASSERT_TRUE(client.connect());
  26231. ASSERT_TRUE(client.send("hello"));
  26232. std::string msg;
  26233. EXPECT_EQ(ws::Text, client.read(msg));
  26234. EXPECT_EQ("hello", msg);
  26235. client.close();
  26236. }
  26237. // ...and a CA file that does not cover the server still fails, so it is the
  26238. // path above that decides the outcome
  26239. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26240. ws::WebSocketClient client(url());
  26241. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26242. ASSERT_FALSE(client.connect());
  26243. }
  26244. // Regression test: reconnecting with a native custom CA store used to reuse
  26245. // a store handle the previous TLS context had already freed (use-after-free
  26246. // under the OpenSSL backend). The context now lives as long as the client.
  26247. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26248. ws::WebSocketClient client(url());
  26249. std::string cert;
  26250. read_file(SERVER_CERT2_FILE, cert);
  26251. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26252. ASSERT_TRUE(client.connect());
  26253. client.close();
  26254. ASSERT_TRUE(client.connect());
  26255. ASSERT_TRUE(client.send("again"));
  26256. std::string msg;
  26257. EXPECT_EQ(ws::Text, client.read(msg));
  26258. EXPECT_EQ("again", msg);
  26259. client.close();
  26260. }
  26261. // Regression test: a certificate with a trusted chain but no identity match
  26262. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26263. // verification entirely for IP hosts, so this connection succeeded there.
  26264. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26265. // chain verification while the identity check must still fail.
  26266. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26267. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26268. ASSERT_TRUE(svr.is_valid());
  26269. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26270. std::string msg;
  26271. while (ws.read(msg)) {
  26272. ws.send(msg);
  26273. }
  26274. });
  26275. auto port = svr.bind_to_any_port("127.0.0.1");
  26276. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26277. auto se = detail::scope_exit([&] {
  26278. svr.stop();
  26279. t.join();
  26280. });
  26281. svr.wait_until_ready();
  26282. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26283. "/echo");
  26284. std::string cert;
  26285. read_file(SERVER_CERT_FILE, cert);
  26286. client.load_ca_cert_store(cert.c_str(), cert.size());
  26287. ASSERT_FALSE(client.connect());
  26288. }
  26289. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26290. // SNI, so nothing binds the host name to the TLS session. These bind the
  26291. // server to "localhost" instead, the only shape that exercises the SNI and
  26292. // hostname-verification path with certificate verification left enabled.
  26293. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26294. protected:
  26295. void Start(const char *cert_file) {
  26296. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26297. SERVER_PRIVATE_KEY_FILE);
  26298. ASSERT_TRUE(server_->is_valid());
  26299. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26300. std::string msg;
  26301. while (ws.read(msg)) {
  26302. ws.send(msg);
  26303. }
  26304. });
  26305. port_ = server_->bind_to_any_port("localhost");
  26306. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26307. server_->wait_until_ready();
  26308. }
  26309. void TearDown() override {
  26310. if (server_) { server_->stop(); }
  26311. if (server_thread_.joinable()) { server_thread_.join(); }
  26312. }
  26313. std::string url() const {
  26314. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26315. }
  26316. std::unique_ptr<SSLServer> server_;
  26317. std::thread server_thread_;
  26318. int port_ = 0;
  26319. };
  26320. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26321. // out and the connection is usable
  26322. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26323. Start(SERVER_CERT2_FILE);
  26324. ws::WebSocketClient client(url());
  26325. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26326. ASSERT_TRUE(client.connect());
  26327. ASSERT_TRUE(client.send("hello"));
  26328. std::string msg;
  26329. EXPECT_EQ(ws::Text, client.read(msg));
  26330. EXPECT_EQ("hello", msg);
  26331. client.close();
  26332. }
  26333. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26334. // while the identity check must still reject "localhost"
  26335. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26336. Start(SERVER_CERT_FILE);
  26337. ws::WebSocketClient client(url());
  26338. client.set_ca_cert_path(SERVER_CERT_FILE);
  26339. auto res = client.connect();
  26340. ASSERT_FALSE(res);
  26341. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26342. EXPECT_EQ(-1, res.status());
  26343. }
  26344. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26345. // disabled: the chain is still checked, only the identity check is skipped
  26346. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26347. Start(SERVER_CERT_FILE);
  26348. ws::WebSocketClient client(url());
  26349. client.set_ca_cert_path(SERVER_CERT_FILE);
  26350. client.enable_server_hostname_verification(false);
  26351. ASSERT_TRUE(client.connect());
  26352. ASSERT_TRUE(client.send("hello"));
  26353. std::string msg;
  26354. EXPECT_EQ(ws::Text, client.read(msg));
  26355. EXPECT_EQ("hello", msg);
  26356. client.close();
  26357. }
  26358. // A CA that did not sign the server certificate fails the chain, even though
  26359. // the name would match
  26360. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26361. Start(SERVER_CERT2_FILE);
  26362. ws::WebSocketClient client(url());
  26363. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26364. ASSERT_FALSE(client.connect());
  26365. }
  26366. // With verification disabled, neither the chain nor the name is checked
  26367. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26368. Start(SERVER_CERT_FILE);
  26369. ws::WebSocketClient client(url());
  26370. client.enable_server_certificate_verification(false);
  26371. ASSERT_TRUE(client.connect());
  26372. ASSERT_TRUE(client.send("hello"));
  26373. std::string msg;
  26374. EXPECT_EQ(ws::Text, client.read(msg));
  26375. EXPECT_EQ("hello", msg);
  26376. client.close();
  26377. }
  26378. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26379. protected:
  26380. void SetUp() override {
  26381. server_ = httplib::detail::make_unique<SSLServer>(
  26382. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26383. ASSERT_TRUE(server_->is_valid());
  26384. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26385. std::string msg;
  26386. while (ws.read(msg)) {
  26387. ws.send(msg);
  26388. }
  26389. });
  26390. port_ = server_->bind_to_any_port("localhost");
  26391. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26392. server_->wait_until_ready();
  26393. }
  26394. void TearDown() override {
  26395. server_->stop();
  26396. if (server_thread_.joinable()) { server_thread_.join(); }
  26397. }
  26398. std::string url() const {
  26399. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26400. }
  26401. void ConnectWithClientCert(const std::string &client_cert_file,
  26402. const std::string &client_private_key_file,
  26403. const char *private_key_password) {
  26404. std::string cert_pem, key_pem;
  26405. read_file(client_cert_file, cert_pem);
  26406. read_file(client_private_key_file, key_pem);
  26407. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26408. key_pem.c_str(), key_pem.size(),
  26409. private_key_password};
  26410. ConnectWithPem(pem);
  26411. }
  26412. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26413. ws::WebSocketClient client(url(), pem);
  26414. ASSERT_TRUE(client.is_valid());
  26415. client.enable_server_certificate_verification(false);
  26416. ASSERT_TRUE(client.connect());
  26417. ASSERT_TRUE(client.send("hello"));
  26418. std::string msg;
  26419. EXPECT_EQ(ws::Text, client.read(msg));
  26420. EXPECT_EQ("hello", msg);
  26421. client.close();
  26422. }
  26423. std::unique_ptr<SSLServer> server_;
  26424. std::thread server_thread_;
  26425. int port_ = 0;
  26426. };
  26427. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26428. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26429. }
  26430. // Control for the tests above: the fixture's server really does require a
  26431. // client certificate, so it is the PEM the constructor installed that decides
  26432. // the outcome.
  26433. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26434. ws::WebSocketClient client(url());
  26435. ASSERT_TRUE(client.is_valid());
  26436. client.enable_server_certificate_verification(false);
  26437. EXPECT_FALSE(client.connect());
  26438. }
  26439. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26440. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26441. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26442. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26443. }
  26444. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26445. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26446. std::string cert_pem, key_pem;
  26447. read_file(CLIENT_CERT_FILE, cert_pem);
  26448. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26449. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26450. std::vector<char> key(key_pem.begin(), key_pem.end());
  26451. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26452. key.size(), nullptr};
  26453. ConnectWithPem(pem);
  26454. }
  26455. #endif
  26456. #if !defined(_WIN32)
  26457. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26458. auto secret_dir = std::string("./symlink_test_secret");
  26459. auto served_dir = std::string("./symlink_test_served");
  26460. auto secret_file = secret_dir + "/secret.txt";
  26461. auto symlink_path = served_dir + "/escape";
  26462. // Setup: create directories and files
  26463. mkdir(secret_dir.c_str(), 0755);
  26464. mkdir(served_dir.c_str(), 0755);
  26465. {
  26466. std::ofstream ofs(secret_file);
  26467. ofs << "SECRET_DATA";
  26468. }
  26469. // Create symlink using absolute path so it resolves correctly
  26470. #ifdef PATH_MAX
  26471. char abs_secret[PATH_MAX];
  26472. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26473. #else
  26474. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26475. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26476. ASSERT_NE(nullptr, abs_secret);
  26477. #endif
  26478. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26479. auto se = detail::scope_exit([&] {
  26480. unlink(symlink_path.c_str());
  26481. unlink(secret_file.c_str());
  26482. rmdir(served_dir.c_str());
  26483. rmdir(secret_dir.c_str());
  26484. });
  26485. Server svr;
  26486. svr.set_mount_point("/", served_dir);
  26487. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26488. auto se2 = detail::scope_exit([&] {
  26489. svr.stop();
  26490. listen_thread.join();
  26491. });
  26492. svr.wait_until_ready();
  26493. Client cli("localhost", PORT);
  26494. // Symlink pointing outside base dir should be blocked
  26495. auto res = cli.Get("/escape/secret.txt");
  26496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26497. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26498. }
  26499. #else
  26500. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26501. auto secret_dir = std::string("junction_test_secret");
  26502. auto served_dir = std::string("junction_test_served");
  26503. auto secret_file = secret_dir + "\\secret.txt";
  26504. auto junction_path = served_dir + "\\escape";
  26505. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26506. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26507. {
  26508. std::ofstream ofs(secret_file);
  26509. ofs << "SECRET_DATA";
  26510. }
  26511. // A junction needs no privilege to create, unlike a symlink
  26512. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26513. ASSERT_EQ(0, std::system(cmd.c_str()));
  26514. auto se = detail::scope_exit([&] {
  26515. ::RemoveDirectoryA(junction_path.c_str());
  26516. std::remove(secret_file.c_str());
  26517. ::RemoveDirectoryA(served_dir.c_str());
  26518. ::RemoveDirectoryA(secret_dir.c_str());
  26519. });
  26520. Server svr;
  26521. svr.set_mount_point("/", served_dir);
  26522. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26523. auto se2 = detail::scope_exit([&] {
  26524. svr.stop();
  26525. listen_thread.join();
  26526. });
  26527. svr.wait_until_ready();
  26528. Client cli("localhost", PORT);
  26529. // Junction pointing outside base dir should be blocked
  26530. auto res = cli.Get("/escape/secret.txt");
  26531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26532. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26533. }
  26534. #endif
  26535. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26536. // "GET /smuggled" request), reads the first response, and only then sends the
  26537. // embedded request as the body. Returns how many times /smuggled ran.
  26538. //
  26539. // The body is sent AFTER receiving the first response (as in the original
  26540. // PoC) so that the stream_line_reader cannot buffer it together with the
  26541. // headers of the first request.
  26542. static int count_smuggled_requests(const std::string &outer_head,
  26543. std::string &first_response) {
  26544. Server svr;
  26545. svr.set_mount_point("/", "./www");
  26546. std::atomic<int> smuggled_count(0);
  26547. svr.Get("/smuggled", [&](const Request &, Response &res) {
  26548. smuggled_count++;
  26549. res.set_content("oops", "text/plain");
  26550. });
  26551. svr.Post("/post", [&](const Request &req, Response &res) {
  26552. res.set_content(req.body, "text/plain");
  26553. });
  26554. auto port = svr.bind_to_any_port("localhost");
  26555. thread t = thread([&] { svr.listen_after_bind(); });
  26556. auto se = detail::scope_exit([&] {
  26557. svr.stop();
  26558. t.join();
  26559. });
  26560. svr.wait_until_ready();
  26561. auto error = Error::Success;
  26562. auto sock = detail::create_client_socket(
  26563. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  26564. /*connection_timeout_sec=*/2, 0,
  26565. /*read_timeout_sec=*/2, 0,
  26566. /*write_timeout_sec=*/2, 0, std::string(), error);
  26567. EXPECT_NE(INVALID_SOCKET, sock);
  26568. if (sock == INVALID_SOCKET) { return -1; }
  26569. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26570. // The "smuggled" request will be sent as the body of the outer request
  26571. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  26572. "Host: localhost\r\n"
  26573. "Connection: close\r\n"
  26574. "\r\n";
  26575. auto head = outer_head;
  26576. auto len = std::to_string(smuggled.size());
  26577. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26578. pos = head.find("{len}", pos + len.size())) {
  26579. head.replace(pos, 5, len);
  26580. }
  26581. // Step 1: Send only the outer request headers (no body yet)
  26582. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26583. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26584. // Step 2: Read the first response
  26585. char buf[4096];
  26586. for (;;) {
  26587. auto n = recv(sock, buf, sizeof(buf), 0);
  26588. if (n <= 0) break;
  26589. first_response.append(buf, static_cast<size_t>(n));
  26590. // Stop once we have a complete response (headers + body)
  26591. auto hdr_end = first_response.find("\r\n\r\n");
  26592. if (hdr_end != std::string::npos) {
  26593. // Check for Content-Length to know when the body is complete
  26594. auto cl_pos = first_response.find("Content-Length:");
  26595. if (cl_pos != std::string::npos) {
  26596. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26597. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26598. auto cl = std::stoul(
  26599. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26600. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26601. } else {
  26602. break; // No Content-Length, assume headers-only response
  26603. }
  26604. }
  26605. }
  26606. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26607. // vulnerable server the keep-alive loop reads this as a second request. The
  26608. // server may already have closed the connection, so the result is ignored.
  26609. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26610. // Half-close so that a server which drained the body sees EOF and closes,
  26611. // instead of the read below waiting for the read timeout.
  26612. #ifdef _WIN32
  26613. ::shutdown(sock, SD_SEND);
  26614. #else
  26615. ::shutdown(sock, SHUT_WR);
  26616. #endif
  26617. // Step 4: Read until the server closes the connection
  26618. for (;;) {
  26619. auto n = recv(sock, buf, sizeof(buf), 0);
  26620. if (n <= 0) break;
  26621. }
  26622. return smuggled_count.load();
  26623. }
  26624. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26625. // A GET request with Content-Length to a static file handler must have its
  26626. // body drained before the keep-alive connection is reused. Otherwise the
  26627. // unread body bytes are interpreted as the next HTTP request.
  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. "Content-Length: {len}\r\n"
  26632. "\r\n",
  26633. first_response));
  26634. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26635. }
  26636. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26637. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26638. // be answered with 400 and the connection closed. Treating it as "no body"
  26639. // leaves the body to be parsed as the next request.
  26640. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26641. const char *targets[] = {
  26642. "GET /file", // handler that never reads the body
  26643. "GET /not-found", // no handler matches (404)
  26644. "POST /post", // handler that reads the body
  26645. };
  26646. for (auto target : targets) {
  26647. for (auto value : values) {
  26648. std::string first_response;
  26649. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26650. " HTTP/1.1\r\n"
  26651. "Host: localhost\r\n"
  26652. "Content-Length: " +
  26653. value + "\r\n\r\n",
  26654. first_response))
  26655. << target << " with Content-Length: " << value;
  26656. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  26657. << target << " with Content-Length: " << value;
  26658. }
  26659. }
  26660. }
  26661. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  26662. // A 400 for an unparseable request line leaves the rest of the message
  26663. // unread, so the connection must be closed rather than reused.
  26664. std::string first_response;
  26665. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  26666. "Host: localhost\r\n"
  26667. "Content-Length: {len}\r\n"
  26668. "\r\n",
  26669. first_response));
  26670. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26671. }
  26672. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  26673. // Same as above for a header block that fails to parse.
  26674. std::string first_response;
  26675. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26676. "Host: localhost\r\n"
  26677. "Bad Header\r\n"
  26678. "Content-Length: {len}\r\n"
  26679. "\r\n",
  26680. first_response));
  26681. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26682. }
  26683. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  26684. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  26685. // server must not read another request on that connection, even when the
  26686. // request had no body to drain.
  26687. std::string first_response;
  26688. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  26689. "Host: localhost\r\n"
  26690. "\r\n",
  26691. first_response));
  26692. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  26693. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  26694. }
  26695. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  26696. // A content reader that stops early leaves the stream inside the body.
  26697. // Draining the whole Content-Length from there, or reading the body again,
  26698. // reads into the next request, and whatever follows is parsed as a request
  26699. // of its own.
  26700. Server svr;
  26701. std::atomic<int> smuggled_count(0);
  26702. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  26703. svr.Post("/upload", [](const Request &req, Response &res,
  26704. const ContentReader &content_reader) {
  26705. // Stop at the last chunk, so the whole body has been read however it
  26706. // arrives.
  26707. auto length = req.get_header_value_u64("Content-Length");
  26708. size_t total = 0;
  26709. auto consumed = content_reader([&](const char *, size_t n) {
  26710. total += n;
  26711. return total < length;
  26712. });
  26713. EXPECT_FALSE(consumed);
  26714. if (req.has_param("retry")) {
  26715. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  26716. }
  26717. // Replace the 400 the aborted read set, which would close the connection.
  26718. res.set_redirect("/done");
  26719. });
  26720. auto port = svr.bind_to_any_port(HOST);
  26721. thread t = thread([&] { svr.listen_after_bind(); });
  26722. auto se = detail::scope_exit([&] {
  26723. svr.stop();
  26724. t.join();
  26725. });
  26726. svr.wait_until_ready();
  26727. // A front end sees the second request as a POST whose body is the GET. The
  26728. // first body is as long as the POST's headers, so draining it again reads
  26729. // exactly those and leaves the GET to be parsed next.
  26730. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  26731. "Host: localhost\r\n"
  26732. "\r\n";
  26733. std::string second_head = "POST /post HTTP/1.1\r\n"
  26734. "Host: localhost\r\n"
  26735. "Content-Length: " +
  26736. std::to_string(inner.size()) +
  26737. "\r\n"
  26738. "\r\n";
  26739. for (auto target : {"/upload", "/upload?retry"}) {
  26740. smuggled_count = 0;
  26741. std::string request = "POST " + std::string(target) +
  26742. " HTTP/1.1\r\n"
  26743. "Host: localhost\r\n"
  26744. "Content-Length: " +
  26745. std::to_string(second_head.size()) +
  26746. "\r\n"
  26747. "\r\n" +
  26748. std::string(second_head.size(), 'A') + second_head +
  26749. inner;
  26750. std::string response;
  26751. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  26752. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  26753. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  26754. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  26755. EXPECT_EQ(0, smuggled_count.load()) << target;
  26756. }
  26757. }
  26758. // An error response closes the connection anyway, so the body is left unread
  26759. // with a redirect, such as one to a login page.
  26760. static void serve_redirects(Server &svr,
  26761. const std::function<void(int)> &client) {
  26762. svr.set_pre_routing_handler([](const Request &, Response &res) {
  26763. res.set_redirect("/login");
  26764. return Server::HandlerResponse::Handled;
  26765. });
  26766. auto port = svr.bind_to_any_port(HOST);
  26767. ASSERT_GT(port, 0);
  26768. thread t = thread([&] { svr.listen_after_bind(); });
  26769. auto se = detail::scope_exit([&] {
  26770. svr.stop();
  26771. t.join();
  26772. ASSERT_FALSE(svr.is_running());
  26773. });
  26774. svr.wait_until_ready();
  26775. client(port);
  26776. }
  26777. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  26778. Server svr;
  26779. serve_redirects(svr, [](int port) {
  26780. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  26781. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  26782. std::to_string(body.size()) + "\r\n\r\n" + body +
  26783. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  26784. std::string resp;
  26785. ASSERT_TRUE(send_request(1, req, &resp, port));
  26786. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  26787. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  26788. });
  26789. }
  26790. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  26791. Server svr;
  26792. svr.set_read_timeout(0, 200000);
  26793. serve_redirects(svr, [](int port) {
  26794. // A byte every 100 ms keeps each read within the read timeout, but not the
  26795. // body as a whole, so the server closes and the bytes sent after that fail.
  26796. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  26797. "Content-Length: 10\r\n\r\n"};
  26798. parts.resize(11, "x");
  26799. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  26800. });
  26801. }
  26802. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  26803. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  26804. // must be rejected with 400 Bad Request.
  26805. Server svr;
  26806. svr.Post("/test", [&](const Request &, Response &res) {
  26807. res.set_content("ok", "text/plain");
  26808. });
  26809. thread t = thread([&] { svr.listen(HOST, PORT); });
  26810. auto se = detail::scope_exit([&] {
  26811. svr.stop();
  26812. t.join();
  26813. ASSERT_FALSE(svr.is_running());
  26814. });
  26815. svr.wait_until_ready();
  26816. // Exact "chunked"
  26817. {
  26818. auto req = "POST /test HTTP/1.1\r\n"
  26819. "Host: localhost\r\n"
  26820. "Content-Length: 5\r\n"
  26821. "Transfer-Encoding: chunked\r\n"
  26822. "Connection: close\r\n"
  26823. "\r\n"
  26824. "hello";
  26825. std::string response;
  26826. ASSERT_TRUE(send_request(1, req, &response));
  26827. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26828. response.substr(0, response.find("\r\n")));
  26829. }
  26830. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  26831. {
  26832. auto req = "POST /test HTTP/1.1\r\n"
  26833. "Host: localhost\r\n"
  26834. "Content-Length: 5\r\n"
  26835. "Transfer-Encoding: gzip, chunked\r\n"
  26836. "Connection: close\r\n"
  26837. "\r\n"
  26838. "hello";
  26839. std::string response;
  26840. ASSERT_TRUE(send_request(1, req, &response));
  26841. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26842. response.substr(0, response.find("\r\n")));
  26843. }
  26844. }
  26845. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  26846. Server svr;
  26847. svr.Post("/test", [&](const Request &, Response &res) {
  26848. res.set_content("ok", "text/plain");
  26849. });
  26850. thread t = thread([&] { svr.listen(HOST, PORT); });
  26851. auto se = detail::scope_exit([&] {
  26852. svr.stop();
  26853. t.join();
  26854. ASSERT_FALSE(svr.is_running());
  26855. });
  26856. svr.wait_until_ready();
  26857. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  26858. // length cannot be determined, so the server must answer 400 and close
  26859. // rather than treat the request as bodyless and leave the body in the
  26860. // socket for the next request to pick up.
  26861. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  26862. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  26863. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  26864. std::string response;
  26865. ASSERT_TRUE(send_request(1, req, &response));
  26866. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26867. response.substr(0, response.find("\r\n")))
  26868. << transfer_encoding;
  26869. }
  26870. // RFC 9110 5.3: the codings may also be split across several
  26871. // Transfer-Encoding lines, which combine in the order they were received.
  26872. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  26873. // just like the single-line "chunked, gzip" above.
  26874. {
  26875. auto req = "POST /test HTTP/1.1\r\n"
  26876. "Host: localhost\r\n"
  26877. "Transfer-Encoding: chunked\r\n"
  26878. "Transfer-Encoding: gzip\r\n"
  26879. "\r\n"
  26880. "0\r\n\r\n";
  26881. std::string response;
  26882. ASSERT_TRUE(send_request(1, req, &response));
  26883. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  26884. response.substr(0, response.find("\r\n")));
  26885. }
  26886. }
  26887. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  26888. Server svr;
  26889. svr.Post("/test", [&](const Request &, Response &res) {
  26890. res.set_content("ok", "text/plain");
  26891. });
  26892. auto port = svr.bind_to_any_port(HOST);
  26893. ASSERT_GT(port, 0);
  26894. thread t = thread([&] { svr.listen_after_bind(); });
  26895. auto se = detail::scope_exit([&] {
  26896. svr.stop();
  26897. t.join();
  26898. ASSERT_FALSE(svr.is_running());
  26899. });
  26900. svr.wait_until_ready();
  26901. for (auto transfer_encoding :
  26902. {"Transfer-Encoding: gzip, chunked\r\n",
  26903. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  26904. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  26905. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  26906. transfer_encoding + "\r\n0\r\n\r\n";
  26907. std::string response;
  26908. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  26909. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  26910. response.substr(0, response.find("\r\n")))
  26911. << transfer_encoding;
  26912. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  26913. << transfer_encoding;
  26914. }
  26915. }
  26916. // Regression for issue #2450: a DELETE without Content-Length on a
  26917. // keep-alive connection must not let the post-response drain consume the
  26918. // next request's bytes.
  26919. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  26920. Server svr;
  26921. std::atomic<int> delete_count(0);
  26922. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  26923. delete_count++;
  26924. res.status = StatusCode::NoContent_204;
  26925. });
  26926. auto port = svr.bind_to_any_port(HOST);
  26927. thread t = thread([&] { svr.listen_after_bind(); });
  26928. auto se = detail::scope_exit([&] {
  26929. svr.stop();
  26930. t.join();
  26931. });
  26932. svr.wait_until_ready();
  26933. auto error = Error::Success;
  26934. auto sock = detail::create_client_socket(
  26935. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26936. /*connection_timeout_sec=*/2, 0,
  26937. /*read_timeout_sec=*/2, 0,
  26938. /*write_timeout_sec=*/2, 0, std::string(), error);
  26939. ASSERT_NE(INVALID_SOCKET, sock);
  26940. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26941. auto send_request_and_read_response = [&](const std::string &req,
  26942. std::string &out) -> bool {
  26943. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  26944. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  26945. char buf[4096];
  26946. for (;;) {
  26947. auto n = recv(sock, buf, sizeof(buf), 0);
  26948. if (n <= 0) { return !out.empty(); }
  26949. out.append(buf, static_cast<size_t>(n));
  26950. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  26951. }
  26952. };
  26953. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  26954. "Host: localhost\r\n"
  26955. "\r\n";
  26956. std::string resp1;
  26957. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  26958. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  26959. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  26960. "Host: localhost\r\n"
  26961. "Connection: close\r\n"
  26962. "\r\n";
  26963. std::string resp2;
  26964. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  26965. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  26966. EXPECT_EQ(2, delete_count.load());
  26967. }
  26968. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  26969. Server svr;
  26970. svr.Post("/ingest", [&](const Request &, Response &res,
  26971. const ContentReader &content_reader) {
  26972. auto consumed = content_reader([](const char *, size_t) { return false; });
  26973. EXPECT_FALSE(consumed);
  26974. res.status = StatusCode::Conflict_409;
  26975. res.set_header("Connection", "close");
  26976. });
  26977. auto port = svr.bind_to_any_port(HOST);
  26978. thread t = thread([&] { svr.listen_after_bind(); });
  26979. auto se = detail::scope_exit([&] {
  26980. svr.stop();
  26981. t.join();
  26982. });
  26983. svr.wait_until_ready();
  26984. auto error = Error::Success;
  26985. auto sock = detail::create_client_socket(
  26986. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  26987. /*connection_timeout_sec=*/2, 0,
  26988. /*read_timeout_sec=*/1, 0,
  26989. /*write_timeout_sec=*/2, 0, std::string(), error);
  26990. ASSERT_NE(INVALID_SOCKET, sock);
  26991. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26992. std::string request = "POST /ingest HTTP/1.1\r\n"
  26993. "Host: localhost\r\n"
  26994. "Transfer-Encoding: chunked\r\n"
  26995. "\r\n"
  26996. "4\r\n"
  26997. "data\r\n";
  26998. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  26999. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27000. std::string response;
  27001. ssize_t received = 0;
  27002. do {
  27003. char buf[4096];
  27004. received = recv(sock, buf, sizeof(buf), 0);
  27005. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27006. } while (received > 0);
  27007. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27008. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27009. EXPECT_EQ(0, received);
  27010. }
  27011. namespace no_proxy_test {
  27012. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27013. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27014. // calling listen().
  27015. class ScopedServer {
  27016. public:
  27017. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27018. ~ScopedServer() {
  27019. svr_.stop();
  27020. if (th_.joinable()) { th_.join(); }
  27021. }
  27022. Server &svr() { return svr_; }
  27023. int port() const { return port_; }
  27024. void listen() {
  27025. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27026. svr_.wait_until_ready();
  27027. }
  27028. private:
  27029. Server svr_;
  27030. std::thread th_;
  27031. int port_ = 0;
  27032. };
  27033. class ProxyAndTargetServers {
  27034. public:
  27035. ProxyAndTargetServers() {
  27036. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27037. proxy_hits_++;
  27038. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27039. res.set_content("via-proxy", "text/plain");
  27040. });
  27041. target_.Get(".*", [this](const Request &req, Response &res) {
  27042. target_hits_++;
  27043. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27044. res.set_content("direct", "text/plain");
  27045. });
  27046. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27047. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27048. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27049. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27050. proxy_mock_.wait_until_ready();
  27051. target_.wait_until_ready();
  27052. }
  27053. ~ProxyAndTargetServers() {
  27054. proxy_mock_.stop();
  27055. target_.stop();
  27056. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27057. if (target_thread_.joinable()) { target_thread_.join(); }
  27058. }
  27059. Server &proxy_mock() { return proxy_mock_; }
  27060. Server &target() { return target_; }
  27061. int proxy_port() const { return proxy_port_; }
  27062. int target_port() const { return target_port_; }
  27063. int proxy_hits() const { return proxy_hits_.load(); }
  27064. int target_hits() const { return target_hits_.load(); }
  27065. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27066. void reset_counters() {
  27067. proxy_hits_ = 0;
  27068. target_hits_ = 0;
  27069. last_had_proxy_authz_ = false;
  27070. }
  27071. private:
  27072. Server proxy_mock_;
  27073. Server target_;
  27074. std::thread proxy_thread_;
  27075. std::thread target_thread_;
  27076. int proxy_port_ = 0;
  27077. int target_port_ = 0;
  27078. std::atomic<int> proxy_hits_{0};
  27079. std::atomic<int> target_hits_{0};
  27080. std::atomic<bool> last_had_proxy_authz_{false};
  27081. };
  27082. inline std::unique_ptr<Client> make_client(const std::string &host,
  27083. ProxyAndTargetServers &s) {
  27084. auto cli = detail::make_unique<Client>(host, s.target_port());
  27085. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27086. cli->set_proxy("127.0.0.1", s.proxy_port());
  27087. return cli;
  27088. }
  27089. } // namespace no_proxy_test
  27090. using no_proxy_test::make_client;
  27091. using no_proxy_test::ProxyAndTargetServers;
  27092. // A stream request carries the credentials a buffered request does
  27093. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27094. no_proxy_test::ScopedServer origin;
  27095. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27096. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27097. });
  27098. origin.listen();
  27099. Client cli("127.0.0.1", origin.port());
  27100. cli.set_basic_auth("user", "pass");
  27101. auto handle = cli.open_stream("GET", "/x");
  27102. ASSERT_TRUE(handle.is_valid());
  27103. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27104. Client bearer("127.0.0.1", origin.port());
  27105. bearer.set_bearer_token_auth("tok");
  27106. auto handle2 = bearer.open_stream("GET", "/x");
  27107. ASSERT_TRUE(handle2.is_valid());
  27108. EXPECT_EQ("Bearer tok", read_all(handle2));
  27109. }
  27110. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27111. // takes its own credentials, as for a buffered request
  27112. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27113. std::string target, authz, proxy_authz;
  27114. no_proxy_test::ScopedServer proxy;
  27115. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27116. target = req.target;
  27117. authz = req.get_header_value("Authorization");
  27118. proxy_authz = req.get_header_value("Proxy-Authorization");
  27119. res.set_content("ok", "text/plain");
  27120. });
  27121. proxy.listen();
  27122. Client cli("origin.example", 8080);
  27123. cli.set_proxy("127.0.0.1", proxy.port());
  27124. cli.set_proxy_basic_auth("puser", "ppass");
  27125. cli.set_basic_auth("user", "pass");
  27126. auto handle = cli.open_stream("GET", "/x");
  27127. ASSERT_TRUE(handle.is_valid());
  27128. EXPECT_EQ("ok", read_all(handle));
  27129. EXPECT_EQ("http://origin.example:8080/x", target);
  27130. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27131. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27132. }
  27133. // In absolute-form the path follows the authority, so a path that does not
  27134. // begin with '/' would make the proxy connect to another host
  27135. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27136. std::vector<std::string> targets;
  27137. no_proxy_test::ScopedServer proxy;
  27138. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27139. targets.push_back(req.target);
  27140. res.set_content("ok", "text/plain");
  27141. });
  27142. proxy.listen();
  27143. Client cli("origin.example", 8080);
  27144. cli.set_proxy("127.0.0.1", proxy.port());
  27145. cli.set_basic_auth("user", "pass");
  27146. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27147. auto res = cli.Get(path);
  27148. EXPECT_FALSE(res) << path;
  27149. auto handle = cli.open_stream("GET", path);
  27150. EXPECT_FALSE(handle.is_valid()) << path;
  27151. }
  27152. EXPECT_TRUE(targets.empty());
  27153. auto res = cli.Get("/x");
  27154. ASSERT_TRUE(res);
  27155. ASSERT_EQ(1u, targets.size());
  27156. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27157. }
  27158. TEST(NoProxyTest, ExactHostnameBypasses) {
  27159. ProxyAndTargetServers s;
  27160. auto cli = make_client("example.com", s);
  27161. cli->set_no_proxy({"example.com"});
  27162. auto res = cli->Get("/");
  27163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27164. EXPECT_EQ(0, s.proxy_hits());
  27165. EXPECT_EQ(1, s.target_hits());
  27166. }
  27167. TEST(NoProxyTest, SubdomainBypasses) {
  27168. ProxyAndTargetServers s;
  27169. auto cli = make_client("foo.example.com", s);
  27170. cli->set_no_proxy({"example.com"});
  27171. auto res = cli->Get("/");
  27172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27173. EXPECT_EQ(0, s.proxy_hits());
  27174. EXPECT_EQ(1, s.target_hits());
  27175. }
  27176. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27177. // Regression guard: "evilexample.com" must not be considered a subdomain
  27178. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27179. // check would let traffic bypass the proxy and leak credentials direct
  27180. // to the attacker host.
  27181. ProxyAndTargetServers s;
  27182. auto cli = make_client("evilexample.com", s);
  27183. cli->set_no_proxy({"example.com"});
  27184. auto res = cli->Get("/");
  27185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27186. EXPECT_GE(s.proxy_hits(), 1);
  27187. EXPECT_EQ(0, s.target_hits());
  27188. }
  27189. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27190. ProxyAndTargetServers s;
  27191. auto cli = make_client("example.com.evil.com", s);
  27192. cli->set_no_proxy({"example.com"});
  27193. auto res = cli->Get("/");
  27194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27195. EXPECT_GE(s.proxy_hits(), 1);
  27196. EXPECT_EQ(0, s.target_hits());
  27197. }
  27198. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27199. ProxyAndTargetServers s;
  27200. auto cli = make_client("example.com", s);
  27201. cli->set_no_proxy({".example.com"});
  27202. auto res = cli->Get("/");
  27203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27204. EXPECT_EQ(0, s.proxy_hits());
  27205. EXPECT_EQ(1, s.target_hits());
  27206. }
  27207. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27208. ProxyAndTargetServers s;
  27209. auto cli = make_client("Example.COM", s);
  27210. cli->set_no_proxy({"EXAMPLE.com"});
  27211. auto res = cli->Get("/");
  27212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27213. EXPECT_EQ(0, s.proxy_hits());
  27214. EXPECT_EQ(1, s.target_hits());
  27215. }
  27216. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27217. ProxyAndTargetServers s;
  27218. auto cli = make_client("example.com.", s);
  27219. cli->set_no_proxy({"example.com"});
  27220. auto res = cli->Get("/");
  27221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27222. EXPECT_EQ(0, s.proxy_hits());
  27223. EXPECT_EQ(1, s.target_hits());
  27224. }
  27225. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27226. // Trailing dots must be normalized on BOTH sides — host and entry.
  27227. // An implementation that only strips the host-side trailing dot would
  27228. // fail to match host "example.com" against entry "example.com." because
  27229. // a literal substring search would compare 11 chars against 12.
  27230. ProxyAndTargetServers s;
  27231. auto cli = make_client("example.com", s);
  27232. cli->set_no_proxy({"example.com."});
  27233. auto res = cli->Get("/");
  27234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27235. EXPECT_EQ(0, s.proxy_hits());
  27236. EXPECT_EQ(1, s.target_hits());
  27237. }
  27238. TEST(NoProxyTest, WildcardBypassesEverything) {
  27239. ProxyAndTargetServers s;
  27240. auto cli = make_client("anything.invalid.test", s);
  27241. cli->set_no_proxy({"*"});
  27242. auto res = cli->Get("/");
  27243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27244. EXPECT_EQ(0, s.proxy_hits());
  27245. EXPECT_EQ(1, s.target_hits());
  27246. }
  27247. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27248. ProxyAndTargetServers s;
  27249. Client cli("127.0.0.1", s.target_port());
  27250. cli.set_proxy("127.0.0.1", s.proxy_port());
  27251. cli.set_no_proxy({"127.0.0.1"});
  27252. auto res = cli.Get("/");
  27253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27254. EXPECT_EQ(0, s.proxy_hits());
  27255. EXPECT_EQ(1, s.target_hits());
  27256. }
  27257. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27258. ProxyAndTargetServers s;
  27259. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27260. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27261. cli.set_proxy("127.0.0.1", s.proxy_port());
  27262. cli.set_no_proxy({"::1"});
  27263. auto res = cli.Get("/");
  27264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27265. EXPECT_EQ(0, s.proxy_hits());
  27266. EXPECT_EQ(1, s.target_hits());
  27267. }
  27268. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27269. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27270. // must still be recognized as IPv6 for CIDR matching. Implementations
  27271. // that detect IPv6 only when the host begins with '[' would parse the
  27272. // host as a hostname and miss the match.
  27273. ProxyAndTargetServers s;
  27274. Client cli("fe80::1", s.target_port());
  27275. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27276. cli.set_proxy("127.0.0.1", s.proxy_port());
  27277. cli.set_no_proxy({"fe80::/10"});
  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, BracketedIPv6EntryAccepted) {
  27284. ProxyAndTargetServers s;
  27285. Client cli("::1", s.target_port());
  27286. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27287. cli.set_proxy("127.0.0.1", s.proxy_port());
  27288. cli.set_no_proxy({"[::1]"});
  27289. auto res = cli.Get("/");
  27290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27291. EXPECT_EQ(0, s.proxy_hits());
  27292. EXPECT_EQ(1, s.target_hits());
  27293. }
  27294. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27295. ProxyAndTargetServers s;
  27296. Client cli("fe80::1", s.target_port());
  27297. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27298. cli.set_proxy("127.0.0.1", s.proxy_port());
  27299. cli.set_no_proxy({"[fe80::]/10"});
  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, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27306. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27307. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27308. // tricks via address-family conversion.
  27309. ProxyAndTargetServers s;
  27310. Client cli("::ffff:127.0.0.1", s.target_port());
  27311. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27312. cli.set_proxy("127.0.0.1", s.proxy_port());
  27313. cli.set_no_proxy({"127.0.0.1"});
  27314. auto res = cli.Get("/");
  27315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27316. EXPECT_GE(s.proxy_hits(), 1);
  27317. EXPECT_EQ(0, s.target_hits());
  27318. }
  27319. TEST(NoProxyTest, IPv4CidrMatch) {
  27320. ProxyAndTargetServers s;
  27321. Client cli("127.0.0.1", s.target_port());
  27322. cli.set_proxy("127.0.0.1", s.proxy_port());
  27323. cli.set_no_proxy({"127.0.0.0/8"});
  27324. auto res = cli.Get("/");
  27325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27326. EXPECT_EQ(0, s.proxy_hits());
  27327. EXPECT_EQ(1, s.target_hits());
  27328. }
  27329. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27330. ProxyAndTargetServers s;
  27331. Client cli("127.0.0.1", s.target_port());
  27332. cli.set_proxy("127.0.0.1", s.proxy_port());
  27333. cli.set_no_proxy({"10.0.0.0/8"});
  27334. auto res = cli.Get("/");
  27335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27336. EXPECT_GE(s.proxy_hits(), 1);
  27337. EXPECT_EQ(0, s.target_hits());
  27338. }
  27339. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27340. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27341. // IPv4 target matches.
  27342. ProxyAndTargetServers s;
  27343. Client cli("127.0.0.1", s.target_port());
  27344. cli.set_proxy("127.0.0.1", s.proxy_port());
  27345. cli.set_no_proxy({"0.0.0.0/0"});
  27346. auto res = cli.Get("/");
  27347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27348. EXPECT_EQ(0, s.proxy_hits());
  27349. EXPECT_EQ(1, s.target_hits());
  27350. }
  27351. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27352. ProxyAndTargetServers s;
  27353. Client cli("127.0.0.1", s.target_port());
  27354. cli.set_proxy("127.0.0.1", s.proxy_port());
  27355. cli.set_no_proxy({"127.0.0.1"});
  27356. auto res = cli.Get("/");
  27357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27358. EXPECT_EQ(0, s.proxy_hits());
  27359. EXPECT_EQ(1, s.target_hits());
  27360. }
  27361. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27362. ProxyAndTargetServers s;
  27363. Client cli("127.0.0.1", s.target_port());
  27364. cli.set_proxy("127.0.0.1", s.proxy_port());
  27365. cli.set_no_proxy({"127.0.0.0/33"});
  27366. auto res = cli.Get("/");
  27367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27368. EXPECT_GE(s.proxy_hits(), 1);
  27369. EXPECT_EQ(0, s.target_hits());
  27370. }
  27371. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27372. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27373. ProxyAndTargetServers s;
  27374. Client cli("127.0.0.1", s.target_port());
  27375. cli.set_proxy("127.0.0.1", s.proxy_port());
  27376. cli.set_no_proxy({"127.0.0.1/"});
  27377. auto res = cli.Get("/");
  27378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27379. EXPECT_GE(s.proxy_hits(), 1);
  27380. EXPECT_EQ(0, s.target_hits());
  27381. }
  27382. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27383. ProxyAndTargetServers s;
  27384. auto cli = make_client("internal.corp", s);
  27385. cli->set_proxy_basic_auth("u", "p");
  27386. cli->set_no_proxy({"internal.corp"});
  27387. auto res = cli->Get("/");
  27388. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27389. EXPECT_EQ(1, s.target_hits());
  27390. EXPECT_EQ(0, s.proxy_hits());
  27391. EXPECT_FALSE(s.last_had_proxy_authz())
  27392. << "Proxy-Authorization must not be sent direct to the target";
  27393. }
  27394. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27395. ProxyAndTargetServers s;
  27396. auto cli = make_client("public.example", s);
  27397. cli->set_proxy_basic_auth("u", "p");
  27398. cli->set_no_proxy({"internal.corp"}); // does not match
  27399. auto res = cli->Get("/");
  27400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27401. EXPECT_GE(s.proxy_hits(), 1);
  27402. EXPECT_TRUE(s.last_had_proxy_authz());
  27403. }
  27404. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27405. std::atomic<int> hits{0};
  27406. std::atomic<int> hits_with_authz{0};
  27407. no_proxy_test::ScopedServer proxy_mock;
  27408. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27409. hits++;
  27410. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27411. if (req.target.find("/redir") != std::string::npos) {
  27412. res.set_redirect("http://other.example/landed");
  27413. } else {
  27414. res.set_content("via-proxy", "text/plain");
  27415. }
  27416. });
  27417. proxy_mock.listen();
  27418. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27419. hits = 0;
  27420. hits_with_authz = 0;
  27421. Client cli("public.example", 80);
  27422. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27423. cli.set_proxy_basic_auth(c.first, c.second);
  27424. cli.set_follow_location(true);
  27425. // The redirect to another host goes through the proxy as well
  27426. auto res = cli.Get("/redir");
  27427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27428. EXPECT_EQ(2, hits.load());
  27429. EXPECT_EQ(2, hits_with_authz.load());
  27430. }
  27431. }
  27432. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27433. ProxyAndTargetServers s;
  27434. auto cli = make_client("anything.test", s);
  27435. auto res = cli->Get("/");
  27436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27437. EXPECT_GE(s.proxy_hits(), 1);
  27438. EXPECT_EQ(0, s.target_hits());
  27439. }
  27440. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27441. ProxyAndTargetServers s;
  27442. auto cli = make_client("example.com", s);
  27443. cli->set_no_proxy({"example.com:8080"});
  27444. auto res = cli->Get("/");
  27445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27446. EXPECT_GE(s.proxy_hits(), 1);
  27447. EXPECT_EQ(0, s.target_hits());
  27448. }
  27449. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27450. ProxyAndTargetServers s;
  27451. auto cli = make_client("anything.test", s);
  27452. cli->set_no_proxy({"", " ", "\t"});
  27453. auto res = cli->Get("/");
  27454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27455. EXPECT_GE(s.proxy_hits(), 1);
  27456. EXPECT_EQ(0, s.target_hits());
  27457. }
  27458. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27459. // An entry with leading/trailing whitespace must still match — env-style
  27460. // values are commonly pasted with stray spaces and an implementation
  27461. // that feeds the raw token directly to inet_pton would fail to match
  27462. // valid CIDRs because of the spaces.
  27463. ProxyAndTargetServers s;
  27464. Client cli("127.0.0.1", s.target_port());
  27465. cli.set_proxy("127.0.0.1", s.proxy_port());
  27466. cli.set_no_proxy({" 127.0.0.0/8 "});
  27467. auto res = cli.Get("/");
  27468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27469. EXPECT_EQ(0, s.proxy_hits());
  27470. EXPECT_EQ(1, s.target_hits());
  27471. }
  27472. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27473. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27474. // go direct and must NOT carry Proxy-Authorization.
  27475. std::atomic<int> proxy_hits{0};
  27476. std::atomic<int> target_hits{0};
  27477. std::atomic<bool> target_saw_authz{false};
  27478. no_proxy_test::ScopedServer proxy_mock, target;
  27479. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27480. proxy_hits++;
  27481. res.status = 302;
  27482. res.set_header("Location", "http://127.0.0.1:" +
  27483. std::to_string(target.port()) + "/landed");
  27484. });
  27485. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27486. target_hits++;
  27487. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27488. res.set_content("direct", "text/plain");
  27489. });
  27490. proxy_mock.listen();
  27491. target.listen();
  27492. Client cli("public.example", target.port());
  27493. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27494. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27495. cli.set_proxy_basic_auth("u", "p");
  27496. cli.set_no_proxy({"127.0.0.1"});
  27497. cli.set_follow_location(true);
  27498. auto res = cli.Get("/redir");
  27499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27500. EXPECT_GE(proxy_hits.load(), 1);
  27501. EXPECT_GE(target_hits.load(), 1);
  27502. EXPECT_FALSE(target_saw_authz.load());
  27503. }
  27504. #ifdef CPPHTTPLIB_SSL_ENABLED
  27505. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27506. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27507. // proxy creds would be sent to the (possibly hostile) origin.
  27508. std::atomic<int> target_hits{0};
  27509. std::atomic<bool> target_saw_proxy_authz{false};
  27510. no_proxy_test::ScopedServer target;
  27511. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27512. target_hits++;
  27513. if (req.has_header("Proxy-Authorization")) {
  27514. target_saw_proxy_authz = true;
  27515. }
  27516. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27517. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27518. "nonce=\"abc\", algorithm=MD5");
  27519. });
  27520. target.listen();
  27521. // The proxy address is set to the target's port: the bypass MUST kick in;
  27522. // if it doesn't, the test still routes "via proxy" to the same server and
  27523. // the Proxy-Authorization assertion below catches the leak.
  27524. Client cli("evil.example", target.port());
  27525. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27526. cli.set_proxy("127.0.0.1", target.port());
  27527. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27528. cli.set_no_proxy({"evil.example"});
  27529. auto res = cli.Get("/x");
  27530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27531. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27532. EXPECT_EQ(1, target_hits.load());
  27533. EXPECT_FALSE(target_saw_proxy_authz.load());
  27534. }
  27535. #endif
  27536. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27537. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27538. std::atomic<int> proxy_hits{0};
  27539. std::atomic<int> bypass_hits{0};
  27540. std::atomic<bool> proxy_saw_c_url{false};
  27541. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  27542. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27543. proxy_hits++;
  27544. if (req.path.find("/start") != std::string::npos) {
  27545. res.status = 302;
  27546. res.set_header("Location", "http://127.0.0.1:" +
  27547. std::to_string(bypass_server.port()) +
  27548. "/middle");
  27549. return;
  27550. }
  27551. if (req.path.find("/end") != std::string::npos) {
  27552. proxy_saw_c_url = true;
  27553. res.set_content("c-via-proxy", "text/plain");
  27554. return;
  27555. }
  27556. res.set_content("unexpected", "text/plain");
  27557. });
  27558. // public.example's "advertised" port is arbitrary (the request never lands
  27559. // there — it goes through the proxy), but use a dynamic value to stay
  27560. // friendly with sharded parallel runs.
  27561. int public_port = bypass_server.port();
  27562. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  27563. bypass_hits++;
  27564. res.status = 302;
  27565. res.set_header("Location", "http://public.example:" +
  27566. std::to_string(public_port) + "/end");
  27567. });
  27568. proxy_mock.listen();
  27569. bypass_server.listen();
  27570. Client cli("public.example", public_port);
  27571. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27572. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27573. cli.set_no_proxy({"127.0.0.1"});
  27574. cli.set_follow_location(true);
  27575. auto res = cli.Get("/start");
  27576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27577. EXPECT_EQ(StatusCode::OK_200, res->status);
  27578. EXPECT_EQ("c-via-proxy", res->body);
  27579. EXPECT_GE(proxy_hits.load(), 2);
  27580. EXPECT_GE(bypass_hits.load(), 1);
  27581. EXPECT_TRUE(proxy_saw_c_url.load());
  27582. }
  27583. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27584. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27585. // request reconnects to the correct endpoint.
  27586. std::atomic<int> proxy_hits{0};
  27587. std::atomic<int> target_hits{0};
  27588. no_proxy_test::ScopedServer proxy_mock, target;
  27589. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27590. proxy_hits++;
  27591. res.set_content("via-proxy", "text/plain");
  27592. });
  27593. target.svr().Get(".*", [&](const Request &, Response &res) {
  27594. target_hits++;
  27595. res.set_content("direct", "text/plain");
  27596. });
  27597. proxy_mock.listen();
  27598. target.listen();
  27599. Client cli("public.example", target.port());
  27600. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27601. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27602. cli.set_keep_alive(true);
  27603. auto res1 = cli.Get("/a");
  27604. ASSERT_TRUE(res1);
  27605. EXPECT_EQ("via-proxy", res1->body);
  27606. EXPECT_EQ(1, proxy_hits.load());
  27607. EXPECT_EQ(0, target_hits.load());
  27608. cli.set_no_proxy({"public.example"});
  27609. auto res2 = cli.Get("/b");
  27610. ASSERT_TRUE(res2);
  27611. EXPECT_EQ("direct", res2->body);
  27612. EXPECT_EQ(1, proxy_hits.load());
  27613. EXPECT_EQ(1, target_hits.load());
  27614. }
  27615. // Forward declarations (see the base64_encode note).
  27616. namespace httplib {
  27617. namespace detail {
  27618. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27619. int shutdown_socket(socket_t sock) noexcept;
  27620. } // namespace detail
  27621. } // namespace httplib
  27622. namespace proxy_tunnel_test {
  27623. const char *const kTunnelEstablished =
  27624. "HTTP/1.1 200 Connection established\r\n\r\n";
  27625. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27626. using ConnectReply = std::function<std::string(const std::string &head)>;
  27627. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27628. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27629. class ScopedConnectProxy {
  27630. public:
  27631. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27632. : forward_port_(forward_port), reply_(std::move(reply)) {
  27633. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27634. if (listen_sock_ == INVALID_SOCKET) { return; }
  27635. auto a = loopback(0);
  27636. auto addr = reinterpret_cast<sockaddr *>(&a);
  27637. socklen_t alen = sizeof(a);
  27638. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27639. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27640. ::listen(listen_sock_, 4) != 0) {
  27641. return;
  27642. }
  27643. port_ = ntohs(a.sin_port);
  27644. th_ = std::thread([this] { run(); });
  27645. }
  27646. ~ScopedConnectProxy() {
  27647. if (th_.joinable()) {
  27648. stop_ = true;
  27649. auto wake = connect_to(port_);
  27650. th_.join();
  27651. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  27652. }
  27653. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  27654. }
  27655. int port() const { return port_; }
  27656. int connect_hits() const { return connect_hits_.load(); }
  27657. // Head of the last CONNECT request, as the proxy saw it on the wire.
  27658. std::string connect_request() const {
  27659. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27660. return connect_request_;
  27661. }
  27662. private:
  27663. static sockaddr_in loopback(int port) {
  27664. sockaddr_in a{};
  27665. a.sin_family = AF_INET;
  27666. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  27667. a.sin_port = htons(static_cast<unsigned short>(port));
  27668. return a;
  27669. }
  27670. static socket_t connect_to(int port) {
  27671. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  27672. if (sock == INVALID_SOCKET) { return sock; }
  27673. auto a = loopback(port);
  27674. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  27675. detail::close_socket(sock);
  27676. return INVALID_SOCKET;
  27677. }
  27678. return sock;
  27679. }
  27680. static bool send_all(socket_t sock, const char *data, size_t size) {
  27681. while (size > 0) {
  27682. auto n = detail::send_socket(sock, data, size, 0);
  27683. if (n <= 0) { return false; }
  27684. data += n;
  27685. size -= static_cast<size_t>(n);
  27686. }
  27687. return true;
  27688. }
  27689. void run() {
  27690. for (;;) {
  27691. auto client = ::accept(listen_sock_, nullptr, nullptr);
  27692. if (stop_) {
  27693. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  27694. return;
  27695. }
  27696. if (client == INVALID_SOCKET) { continue; }
  27697. serve(client);
  27698. detail::close_socket(client);
  27699. }
  27700. }
  27701. void serve(socket_t client) {
  27702. std::string head;
  27703. char buf[2048];
  27704. while (head.find("\r\n\r\n") == std::string::npos) {
  27705. if (detail::select_read(client, 5, 0) <= 0) { return; }
  27706. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  27707. if (n <= 0) { return; }
  27708. head.append(buf, static_cast<size_t>(n));
  27709. }
  27710. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  27711. connect_hits_++;
  27712. {
  27713. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27714. connect_request_ = head;
  27715. }
  27716. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  27717. if (!send_all(client, res.data(), res.size()) ||
  27718. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  27719. return;
  27720. }
  27721. auto origin = connect_to(forward_port_);
  27722. if (origin == INVALID_SOCKET) { return; }
  27723. // When either side stops, shut both down so the other pump returns too.
  27724. auto pump = [&](socket_t from, socket_t to) {
  27725. char b[8192];
  27726. for (;;) {
  27727. auto n = detail::read_socket(from, b, sizeof(b), 0);
  27728. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  27729. }
  27730. detail::shutdown_socket(client);
  27731. detail::shutdown_socket(origin);
  27732. };
  27733. std::thread up([&] { pump(client, origin); });
  27734. pump(origin, client);
  27735. up.join();
  27736. detail::close_socket(origin);
  27737. }
  27738. int forward_port_;
  27739. ConnectReply reply_;
  27740. socket_t listen_sock_ = INVALID_SOCKET;
  27741. int port_ = 0;
  27742. std::thread th_;
  27743. std::atomic<bool> stop_{false};
  27744. std::atomic<int> connect_hits_{0};
  27745. mutable std::mutex connect_request_mutex_;
  27746. std::string connect_request_;
  27747. };
  27748. } // namespace proxy_tunnel_test
  27749. #ifdef CPPHTTPLIB_SSL_ENABLED
  27750. namespace proxy_tunnel_test {
  27751. // SSLServer counterpart to no_proxy_test::ScopedServer.
  27752. class ScopedSSLServer {
  27753. public:
  27754. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  27755. port_ = svr_.bind_to_any_port("127.0.0.1");
  27756. }
  27757. ~ScopedSSLServer() {
  27758. svr_.stop();
  27759. if (th_.joinable()) { th_.join(); }
  27760. }
  27761. SSLServer &svr() { return svr_; }
  27762. int port() const { return port_; }
  27763. void listen() {
  27764. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27765. svr_.wait_until_ready();
  27766. }
  27767. private:
  27768. SSLServer svr_;
  27769. std::thread th_;
  27770. int port_ = 0;
  27771. };
  27772. // Sends one request through the CONNECT proxy to the TLS origin with a
  27773. // credential configured for each hop, and checks that each credential reaches
  27774. // only the hop it was configured for: the proxy's on the CONNECT request, the
  27775. // origin's (every header in origin_headers) on the tunnelled request.
  27776. void CredentialsStayWithTheirHop(
  27777. const std::function<void(SSLClient &)> &set_credentials,
  27778. const std::string &scheme,
  27779. const std::vector<std::string> &origin_headers = {"Authorization"},
  27780. bool stream = false) {
  27781. std::atomic<int> origin_hits{0};
  27782. std::atomic<bool> origin_saw_proxy_authz{false};
  27783. std::atomic<bool> origin_saw_headers{false};
  27784. ScopedSSLServer origin;
  27785. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27786. origin_hits++;
  27787. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  27788. origin_saw_headers =
  27789. std::all_of(origin_headers.begin(), origin_headers.end(),
  27790. [&](const std::string &h) { return req.has_header(h); });
  27791. res.set_content("ok", "text/plain");
  27792. });
  27793. origin.listen();
  27794. ScopedConnectProxy proxy(origin.port());
  27795. ASSERT_NE(0, proxy.port());
  27796. // Pinned to 127.0.0.1 for the same reason as the test below.
  27797. SSLClient cli("127.0.0.1", origin.port());
  27798. cli.enable_server_certificate_verification(false);
  27799. cli.set_proxy("127.0.0.1", proxy.port());
  27800. set_credentials(cli);
  27801. if (stream) {
  27802. auto handle = cli.open_stream("GET", "/x");
  27803. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  27804. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  27805. } else {
  27806. auto res = cli.Get("/x");
  27807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27808. EXPECT_EQ(StatusCode::OK_200, res->status);
  27809. }
  27810. EXPECT_EQ(1, origin_hits.load());
  27811. EXPECT_EQ(1, proxy.connect_hits());
  27812. EXPECT_TRUE(origin_saw_headers.load());
  27813. EXPECT_FALSE(origin_saw_proxy_authz.load())
  27814. << "Proxy-Authorization must not be sent inside the tunnel";
  27815. auto connect_req = proxy.connect_request();
  27816. EXPECT_NE(std::string::npos,
  27817. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  27818. for (const auto &h : origin_headers) {
  27819. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  27820. << h << " must not be sent to the proxy on CONNECT";
  27821. }
  27822. }
  27823. } // namespace proxy_tunnel_test
  27824. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  27825. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27826. [](SSLClient &cli) {
  27827. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27828. cli.set_basic_auth("origin-user", "origin-pass");
  27829. },
  27830. "Basic");
  27831. }
  27832. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  27833. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27834. [](SSLClient &cli) {
  27835. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27836. cli.set_basic_auth("origin-user", "origin-pass");
  27837. },
  27838. "Basic", {"Authorization"}, true);
  27839. }
  27840. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  27841. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27842. [](SSLClient &cli) {
  27843. cli.set_proxy_bearer_token_auth("proxy-token");
  27844. cli.set_bearer_token_auth("origin-token");
  27845. },
  27846. "Bearer");
  27847. }
  27848. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  27849. proxy_tunnel_test::CredentialsStayWithTheirHop(
  27850. [](SSLClient &cli) {
  27851. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  27852. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  27853. {"Cookie", "sid=origin-session"},
  27854. {"X-Api-Key", "origin-key"}});
  27855. },
  27856. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  27857. }
  27858. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  27859. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  27860. // retry; otherwise proxy creds would be sent to the origin.
  27861. std::atomic<int> origin_hits{0};
  27862. std::atomic<bool> origin_saw_proxy_authz{false};
  27863. proxy_tunnel_test::ScopedSSLServer origin;
  27864. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27865. origin_hits++;
  27866. if (req.has_header("Proxy-Authorization")) {
  27867. origin_saw_proxy_authz = true;
  27868. }
  27869. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27870. res.set_header("Proxy-Authenticate",
  27871. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  27872. "algorithm=MD5");
  27873. });
  27874. origin.listen();
  27875. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27876. ASSERT_NE(0, proxy.port());
  27877. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  27878. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  27879. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  27880. // and answer with its own status, making this test flaky.
  27881. SSLClient cli("127.0.0.1", origin.port());
  27882. cli.enable_server_certificate_verification(false);
  27883. cli.set_proxy("127.0.0.1", proxy.port());
  27884. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27885. auto res = cli.Get("/x");
  27886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27887. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27888. EXPECT_EQ(1, origin_hits.load());
  27889. EXPECT_FALSE(origin_saw_proxy_authz.load());
  27890. EXPECT_EQ(1, proxy.connect_hits());
  27891. }
  27892. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  27893. std::string origin_sni;
  27894. std::string origin_host;
  27895. proxy_tunnel_test::ScopedSSLServer origin;
  27896. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  27897. origin_sni = req.sni();
  27898. origin_host = req.get_header_value("Host");
  27899. res.set_content("ok", "text/plain");
  27900. });
  27901. origin.listen();
  27902. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27903. ASSERT_NE(0, proxy.port());
  27904. SSLClient cli("origin.example", origin.port());
  27905. cli.enable_server_certificate_verification(false);
  27906. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27907. cli.set_proxy("127.0.0.1", proxy.port());
  27908. auto res = cli.Get("/x");
  27909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27910. EXPECT_EQ(StatusCode::OK_200, res->status);
  27911. auto port = std::to_string(origin.port());
  27912. auto target = "127.0.0.1:" + port;
  27913. auto connect_req = proxy.connect_request();
  27914. EXPECT_EQ(1, proxy.connect_hits());
  27915. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27916. EXPECT_NE(std::string::npos,
  27917. connect_req.find("\r\nHost: " + target + "\r\n"));
  27918. EXPECT_EQ("origin.example", origin_sni);
  27919. EXPECT_EQ("origin.example:" + port, origin_host);
  27920. }
  27921. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  27922. proxy_tunnel_test::ScopedSSLServer origin;
  27923. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27924. res.set_content("ok", "text/plain");
  27925. });
  27926. origin.listen();
  27927. proxy_tunnel_test::ScopedConnectProxy proxy(
  27928. origin.port(), [](const std::string &head) -> std::string {
  27929. if (head.find(
  27930. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27931. std::string::npos) {
  27932. return proxy_tunnel_test::kTunnelEstablished;
  27933. }
  27934. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27935. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27936. "nonce=\"abc\", algorithm=MD5\r\n"
  27937. "Content-Length: 0\r\n\r\n";
  27938. });
  27939. ASSERT_NE(0, proxy.port());
  27940. SSLClient cli("origin.example", origin.port());
  27941. cli.enable_server_certificate_verification(false);
  27942. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27943. cli.set_proxy("127.0.0.1", proxy.port());
  27944. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27945. auto res = cli.Get("/x");
  27946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27947. EXPECT_EQ(StatusCode::OK_200, res->status);
  27948. // The retried CONNECT is the one the proxy saw last.
  27949. auto target = "127.0.0.1:" + std::to_string(origin.port());
  27950. auto connect_req = proxy.connect_request();
  27951. EXPECT_EQ(2, proxy.connect_hits());
  27952. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27953. EXPECT_NE(std::string::npos,
  27954. connect_req.find("\r\nHost: " + target + "\r\n"));
  27955. }
  27956. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  27957. proxy_tunnel_test::ScopedSSLServer origin;
  27958. origin.svr().Get(".*", [&](const Request &, Response &res) {
  27959. res.set_content("ok", "text/plain");
  27960. });
  27961. origin.listen();
  27962. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27963. ASSERT_NE(0, proxy.port());
  27964. SSLClient cli("origin.example", origin.port());
  27965. cli.enable_server_certificate_verification(false);
  27966. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  27967. cli.set_proxy("127.0.0.1", proxy.port());
  27968. auto res = cli.Get("/x");
  27969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27970. EXPECT_EQ(StatusCode::OK_200, res->status);
  27971. auto target = "origin.example:" + std::to_string(origin.port());
  27972. auto connect_req = proxy.connect_request();
  27973. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  27974. EXPECT_NE(std::string::npos,
  27975. connect_req.find("\r\nHost: " + target + "\r\n"));
  27976. }
  27977. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  27978. proxy_tunnel_test::ScopedSSLServer origin;
  27979. auto port = std::to_string(origin.port());
  27980. origin.svr().Get("/x", [&](const Request &, Response &res) {
  27981. res.set_redirect("https://next.example:" + port + "/y");
  27982. });
  27983. origin.svr().Get("/y", [](const Request &, Response &res) {
  27984. res.set_content("ok", "text/plain");
  27985. });
  27986. origin.listen();
  27987. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27988. ASSERT_NE(0, proxy.port());
  27989. SSLClient cli("origin.example", origin.port());
  27990. cli.enable_server_certificate_verification(false);
  27991. cli.set_tunnel_hostname_addr_map(
  27992. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  27993. cli.set_proxy("127.0.0.1", proxy.port());
  27994. cli.set_follow_location(true);
  27995. auto res = cli.Get("/x");
  27996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27997. EXPECT_EQ("ok", res->body);
  27998. // The last CONNECT is the redirect client's.
  27999. ASSERT_EQ(2, proxy.connect_hits());
  28000. auto target = "127.0.0.1:" + port;
  28001. auto connect_req = proxy.connect_request();
  28002. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28003. EXPECT_NE(std::string::npos,
  28004. connect_req.find("\r\nHost: " + target + "\r\n"));
  28005. }
  28006. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28007. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28008. std::atomic<int> origin_hits{0};
  28009. proxy_tunnel_test::ScopedSSLServer origin;
  28010. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28011. origin_hits++;
  28012. res.set_content("ok", "text/plain");
  28013. });
  28014. origin.listen();
  28015. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28016. ASSERT_NE(0, proxy.port());
  28017. SSLClient cli("127.0.0.1", origin.port());
  28018. cli.enable_server_certificate_verification(false);
  28019. cli.set_proxy("127.0.0.1", proxy.port());
  28020. cli.set_keep_alive(true);
  28021. cli.set_session_verifier(
  28022. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28023. auto res = cli.Get("/x");
  28024. EXPECT_FALSE(res);
  28025. ASSERT_FALSE(cli.is_socket_open());
  28026. res = cli.Get("/x");
  28027. EXPECT_FALSE(res);
  28028. EXPECT_EQ(2, proxy.connect_hits());
  28029. auto handle = cli.open_stream("GET", "/x");
  28030. EXPECT_FALSE(handle.is_valid());
  28031. EXPECT_EQ(3, proxy.connect_hits());
  28032. EXPECT_EQ(0, origin_hits.load());
  28033. }
  28034. #endif
  28035. namespace proxy_tunnel_test {
  28036. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28037. // anything else gets a 407 with `challenge`.
  28038. ConnectReply require_proxy_auth(const std::string &expected,
  28039. const std::string &challenge) {
  28040. return [=](const std::string &head) -> std::string {
  28041. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28042. std::string::npos) {
  28043. return kTunnelEstablished;
  28044. }
  28045. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28046. "Proxy-Authenticate: " +
  28047. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28048. };
  28049. }
  28050. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28051. // request, then echoes.
  28052. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28053. ws.send(
  28054. "authorization:" + req.get_header_value("Authorization") +
  28055. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28056. std::string msg;
  28057. while (ws.read(msg)) {
  28058. ws.send(msg);
  28059. }
  28060. }
  28061. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28062. class ScopedWebSocketOrigin {
  28063. public:
  28064. ScopedWebSocketOrigin() {
  28065. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28066. server_.listen();
  28067. }
  28068. int port() const { return server_.port(); }
  28069. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28070. std::string url() const {
  28071. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28072. }
  28073. private:
  28074. no_proxy_test::ScopedServer server_;
  28075. };
  28076. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28077. // passed as a constructor header, and checks that each reaches only its hop.
  28078. void WebSocketCredentialsStayWithTheirHop(
  28079. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28080. const std::string &proxy_authz, const std::string &origin_authz) {
  28081. ScopedWebSocketOrigin origin;
  28082. ScopedConnectProxy proxy(
  28083. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28084. ASSERT_NE(0, proxy.port());
  28085. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28086. client.set_proxy("127.0.0.1", proxy.port());
  28087. set_proxy_credentials(client);
  28088. auto res = client.connect();
  28089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28090. std::string msg;
  28091. ASSERT_TRUE(client.read(msg));
  28092. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28093. client.close();
  28094. EXPECT_EQ(1, proxy.connect_hits());
  28095. EXPECT_EQ(std::string::npos,
  28096. proxy.connect_request().find("\r\nAuthorization: "))
  28097. << "origin credentials must not be sent to the proxy";
  28098. }
  28099. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28100. void WebSocketSetterCredentialsStayWithTheirHop(
  28101. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28102. const std::string &proxy_authz, const std::string &origin_authz) {
  28103. ScopedWebSocketOrigin origin;
  28104. ScopedConnectProxy proxy(
  28105. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28106. ASSERT_NE(0, proxy.port());
  28107. ws::WebSocketClient client(origin.url());
  28108. client.set_proxy("127.0.0.1", proxy.port());
  28109. set_credentials(client);
  28110. auto res = client.connect();
  28111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28112. std::string msg;
  28113. ASSERT_TRUE(client.read(msg));
  28114. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28115. client.close();
  28116. EXPECT_EQ(1, proxy.connect_hits());
  28117. EXPECT_EQ(std::string::npos,
  28118. proxy.connect_request().find("\r\nAuthorization: "))
  28119. << "origin credentials must not be sent to the proxy";
  28120. }
  28121. } // namespace proxy_tunnel_test
  28122. namespace {
  28123. // Connects `client` and returns the Authorization header its upgrade
  28124. // request carried, or "<failed>" when the connection could not be opened.
  28125. std::string websocket_authorization(ws::WebSocketClient &client) {
  28126. if (!client.connect()) { return "<failed>"; }
  28127. std::string msg;
  28128. if (!client.read(msg)) { return "<failed>"; }
  28129. client.close();
  28130. auto prefix = std::string("authorization:");
  28131. auto end = msg.find("|proxy-authorization:");
  28132. return msg.substr(prefix.size(), end - prefix.size());
  28133. }
  28134. } // namespace
  28135. TEST(WebSocketClientAuthTest, BasicAuth) {
  28136. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28137. ws::WebSocketClient client(origin.url());
  28138. client.set_basic_auth("user", "pass");
  28139. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28140. websocket_authorization(client));
  28141. }
  28142. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28143. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28144. ws::WebSocketClient client(origin.url());
  28145. client.set_basic_auth("user", "");
  28146. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28147. websocket_authorization(client));
  28148. }
  28149. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28150. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28151. ws::WebSocketClient client(origin.url());
  28152. client.set_bearer_token_auth("token123");
  28153. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28154. }
  28155. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28156. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28157. ws::WebSocketClient client(origin.url());
  28158. client.set_bearer_token_auth("token123");
  28159. client.set_basic_auth("user", "pass");
  28160. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28161. websocket_authorization(client));
  28162. }
  28163. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28164. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28165. ws::WebSocketClient client(origin.url(),
  28166. {{"Authorization", "Bearer from-header"}});
  28167. client.set_bearer_token_auth("from-setter");
  28168. client.set_basic_auth("user", "pass");
  28169. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28170. }
  28171. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28172. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28173. ws::WebSocketClient client(origin.url());
  28174. EXPECT_EQ("", websocket_authorization(client));
  28175. client.set_bearer_token_auth("first");
  28176. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28177. client.set_bearer_token_auth("second");
  28178. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28179. client.set_bearer_token_auth("");
  28180. EXPECT_EQ("", websocket_authorization(client));
  28181. }
  28182. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28183. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28184. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28185. ASSERT_NE(0, proxy.port());
  28186. ws::WebSocketClient client(origin.url());
  28187. client.set_proxy("127.0.0.1", proxy.port());
  28188. auto res = client.connect();
  28189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28190. std::string msg;
  28191. ASSERT_TRUE(client.read(msg));
  28192. ASSERT_TRUE(client.send("hello"));
  28193. ASSERT_TRUE(client.read(msg));
  28194. EXPECT_EQ("hello", msg);
  28195. client.close();
  28196. EXPECT_EQ(1, proxy.connect_hits());
  28197. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28198. auto connect_req = proxy.connect_request();
  28199. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28200. EXPECT_NE(std::string::npos,
  28201. connect_req.find("\r\nHost: " + target + "\r\n"));
  28202. }
  28203. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28204. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28205. [](ws::WebSocketClient &cli) {
  28206. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28207. },
  28208. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28209. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28210. }
  28211. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28212. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28213. [](ws::WebSocketClient &cli) {
  28214. cli.set_proxy_bearer_token_auth("proxy-token");
  28215. },
  28216. "Bearer proxy-token", "Bearer origin-token");
  28217. }
  28218. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28219. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28220. [](ws::WebSocketClient &cli) {
  28221. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28222. cli.set_basic_auth("origin-user", "origin-pass");
  28223. },
  28224. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28225. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28226. }
  28227. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28228. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28229. [](ws::WebSocketClient &cli) {
  28230. cli.set_proxy_bearer_token_auth("proxy-token");
  28231. cli.set_bearer_token_auth("origin-token");
  28232. },
  28233. "Bearer proxy-token", "Bearer origin-token");
  28234. }
  28235. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28236. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28237. proxy_tunnel_test::ScopedConnectProxy proxy(
  28238. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28239. "Basic " + detail::base64_encode("proxy-user:"),
  28240. "Basic realm=\"proxy\""));
  28241. ASSERT_NE(0, proxy.port());
  28242. ws::WebSocketClient client(origin.url());
  28243. client.set_proxy("127.0.0.1", proxy.port());
  28244. client.set_proxy_basic_auth("proxy-user", "");
  28245. auto res = client.connect();
  28246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28247. client.close();
  28248. EXPECT_EQ(1, proxy.connect_hits());
  28249. }
  28250. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28251. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28252. proxy_tunnel_test::ScopedConnectProxy proxy(
  28253. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28254. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28255. ASSERT_NE(0, proxy.port());
  28256. ws::WebSocketClient client(origin.url());
  28257. client.set_proxy("127.0.0.1", proxy.port());
  28258. auto res = client.connect();
  28259. EXPECT_FALSE(res);
  28260. EXPECT_EQ(Error::ProxyConnection, res.error());
  28261. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28262. EXPECT_EQ("Basic realm=\"proxy\"",
  28263. res.get_header_value("Proxy-Authenticate"));
  28264. EXPECT_FALSE(client.is_open());
  28265. }
  28266. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28267. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28268. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28269. ASSERT_NE(0, proxy.port());
  28270. ws::WebSocketClient client(origin.url());
  28271. client.set_proxy("127.0.0.1", proxy.port());
  28272. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28273. client.set_no_proxy({"127.0.0.1"});
  28274. auto res = client.connect();
  28275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28276. std::string msg;
  28277. ASSERT_TRUE(client.read(msg));
  28278. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28279. << "proxy credentials must not reach a bypassed origin";
  28280. client.close();
  28281. EXPECT_EQ(0, proxy.connect_hits());
  28282. }
  28283. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28284. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28285. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28286. ASSERT_NE(0, proxy.port());
  28287. ws::WebSocketClient client(origin.url());
  28288. client.set_proxy("127.0.0.1", proxy.port());
  28289. ASSERT_TRUE(client.connect());
  28290. ASSERT_TRUE(client.connect());
  28291. client.close();
  28292. EXPECT_EQ(2, proxy.connect_hits());
  28293. }
  28294. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28295. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28296. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28297. ASSERT_NE(0, proxy.port());
  28298. auto port = std::to_string(origin.port());
  28299. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28300. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28301. client.set_proxy("127.0.0.1", proxy.port());
  28302. auto res = client.connect();
  28303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28304. std::string msg;
  28305. ASSERT_TRUE(client.read(msg));
  28306. client.close();
  28307. EXPECT_EQ(1, proxy.connect_hits());
  28308. auto target = "127.0.0.1:" + port;
  28309. auto connect_req = proxy.connect_request();
  28310. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28311. EXPECT_NE(std::string::npos,
  28312. connect_req.find("\r\nHost: " + target + "\r\n"));
  28313. }
  28314. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28315. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28316. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28317. ASSERT_NE(0, proxy.port());
  28318. auto port = std::to_string(origin.port());
  28319. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28320. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28321. client.set_proxy("127.0.0.1", proxy.port());
  28322. auto res = client.connect();
  28323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28324. client.close();
  28325. auto target = "origin.example:" + port;
  28326. auto connect_req = proxy.connect_request();
  28327. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28328. EXPECT_NE(std::string::npos,
  28329. connect_req.find("\r\nHost: " + target + "\r\n"));
  28330. }
  28331. #ifdef CPPHTTPLIB_SSL_ENABLED
  28332. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28333. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28334. proxy_tunnel_test::ScopedConnectProxy proxy(
  28335. origin.port(), [](const std::string &head) -> std::string {
  28336. if (head.find(
  28337. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28338. std::string::npos) {
  28339. return proxy_tunnel_test::kTunnelEstablished;
  28340. }
  28341. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28342. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28343. "nonce=\"abc\", algorithm=MD5\r\n"
  28344. "Content-Length: 0\r\n\r\n";
  28345. });
  28346. ASSERT_NE(0, proxy.port());
  28347. ws::WebSocketClient client(origin.url());
  28348. client.set_proxy("127.0.0.1", proxy.port());
  28349. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28350. auto res = client.connect();
  28351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28352. std::string msg;
  28353. ASSERT_TRUE(client.read(msg));
  28354. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28355. client.close();
  28356. EXPECT_EQ(2, proxy.connect_hits());
  28357. }
  28358. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28359. proxy_tunnel_test::ScopedSSLServer origin;
  28360. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28361. origin.listen();
  28362. proxy_tunnel_test::ScopedConnectProxy proxy(
  28363. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28364. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28365. ASSERT_NE(0, proxy.port());
  28366. ws::WebSocketClient client(
  28367. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28368. client.enable_server_certificate_verification(false);
  28369. client.set_proxy("127.0.0.1", proxy.port());
  28370. client.set_proxy_bearer_token_auth("proxy-token");
  28371. auto res = client.connect();
  28372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28373. std::string msg;
  28374. ASSERT_TRUE(client.read(msg));
  28375. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28376. << "Proxy-Authorization must not be sent inside the tunnel";
  28377. client.close();
  28378. EXPECT_EQ(1, proxy.connect_hits());
  28379. }
  28380. #endif